gilt 2.0.0

Fast, beautiful terminal formatting for Rust — styles, tables, trees, syntax highlighting, progress bars, markdown.
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
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
//! Comprehensive showcase of gilt features as a continuous live demo.
//!
//! Run with: `cargo run --example showcase --all-features`
//!
//! Cycles through every major feature group with animated pacing,
//! demonstrating text styling, widgets, highlighting, progress bars,
//! status spinners, and more.

use std::collections::HashMap;
use std::io;
use std::thread;
use std::time::Duration;

use gilt::align_widget::Align;
use gilt::ansi::AnsiDecoder;
use gilt::bar::Bar;
use gilt::canvas::Canvas;
use gilt::color::Color;
use gilt::color_triplet::ColorTriplet;
use gilt::columns::Columns;
use gilt::console::Console;
use gilt::constrain::Constrain;
use gilt::csv_table::CsvTable;
use gilt::diff::Diff;
use gilt::emoji::Emoji;
use gilt::emoji_replace::emoji_replace;
use gilt::figlet::Figlet;
use gilt::filesize;
use gilt::gradient::Gradient;
use gilt::highlighter::*;
use gilt::inspect::Inspect;
use gilt::layout::Layout;
use gilt::live::Live;
use gilt::padding::{Padding, PaddingDimensions};
use gilt::panel::Panel;
use gilt::prelude::*;
use gilt::pretty::Pretty;
use gilt::progress::Progress;
use gilt::rule::Rule;
use gilt::scope::Scope;
use gilt::sparkline::Sparkline;
use gilt::spinners::SPINNERS;
use gilt::status::Status;
use gilt::styled::Styled;
use gilt::theme::Theme;
use gilt::traceback::{Frame, Traceback};
use gilt::tree::Tree;

use serde_json::json;

/// Pause between sections for a live-demo feel.
fn pause() {
    thread::sleep(Duration::from_millis(300));
}

fn main() {
    let mut console = Console::builder()
        .width(90)
        .force_terminal(true)
        .no_color(false)
        .build();

    // =========================================================================
    // 1. Welcome Banner
    // =========================================================================
    console.line(1);
    let banner = Gradient::rainbow("  gilt -- Rich Terminal Formatting for Rust  ")
        .with_style(Style::parse("bold"));
    console.print(&banner);
    console.line(1);
    console.rule(Some("Welcome"));
    pause();

    // =========================================================================
    // 2. Text Styling (Stylize trait)
    // =========================================================================
    console.rule(Some("Text Styling"));

    console.print(&"Bold text".bold());
    console.print(&"Italic text".italic());
    console.print(&"Underlined text".underline());
    console.print(&"Strikethrough text".strikethrough());
    console.print(&"Dim text".dim());
    console.print(&"Bold + Italic + Underline".bold().italic().underline());
    console.line(1);

    // Standard colors
    console.print(&"Red".red());
    console.print(&"Green".green());
    console.print(&"Blue".blue());
    console.print(&"Yellow".yellow());
    console.print(&"Magenta".magenta());
    console.print(&"Cyan".cyan());
    console.print(&"White".white());
    console.print(&"Black on white".black().on_white());
    console.print(&"Bright Red".bright_red());
    console.print(&"Bright Green".bright_green());
    console.print(&"Bright Blue".bright_blue());
    console.print(&"Bright Yellow".bright_yellow());
    console.print(&"Bright Magenta".bright_magenta());
    console.print(&"Bright Cyan".bright_cyan());
    console.print(&"Bright White".bright_white());
    console.line(1);

    // RGB / TrueColor
    console.print(&"TrueColor: #ff6600 (orange)".fg("#ff6600"));
    console.print(&"TrueColor: #00ccff (sky blue)".fg("#00ccff"));
    console.print(
        &"TrueColor: bold + #00ff88 fg + #222222 bg"
            .bold()
            .fg("#00ff88")
            .bg("#222222"),
    );
    pause();

    // =========================================================================
    // 3. Markup
    // =========================================================================
    console.rule(Some("Markup"));

    console.print_text("[bold magenta]This text uses markup[/bold magenta] for [italic cyan]inline styling[/italic cyan].");
    console.print_text("[red]Error:[/red] something went wrong in [bold]module.rs[/bold]");
    console.print_text("[dim]Dim text[/dim], [underline]underlined[/underline], and [bold green]bold green[/bold green].");
    pause();

    // =========================================================================
    // 4. Panel
    // =========================================================================
    console.rule(Some("Panel"));

    let content = Text::new(
        "Gilt is a Rust port of Python's rich library.\nIt brings beautiful terminal formatting to the Rust ecosystem.",
        Style::null(),
    );
    let panel = Panel::fit(content)
        .with_title(Text::new("About Gilt", Style::parse("bold cyan")))
        .with_subtitle(Text::new("v0.5.0", Style::parse("dim")))
        .with_border_style(Style::parse("bright_blue"));
    console.print(&panel);
    pause();

    // =========================================================================
    // 5. Table
    // =========================================================================
    console.rule(Some("Table"));

    let mut table = Table::new(&["Language", "Paradigm", "Year", "Typing"]);
    table.title = Some("Programming Languages".to_string());
    table.title_style = "bold".to_string();
    table.header_style = "bold magenta".to_string();
    table.border_style = "bright_green".to_string();
    table.add_row(&["Rust", "Systems / Multi", "2010", "Static, Strong"]);
    table.add_row(&["Python", "Multi-paradigm", "1991", "Dynamic, Strong"]);
    table.add_row(&["Haskell", "Functional", "1990", "Static, Strong"]);
    table.add_row(&["Go", "Concurrent / Imperative", "2009", "Static, Strong"]);
    table.add_row(&["TypeScript", "Multi-paradigm", "2012", "Static, Gradual"]);
    console.print(&table);
    pause();

    // =========================================================================
    // 6. Tree
    // =========================================================================
    console.rule(Some("Tree"));

    let bold_blue = Style::parse("bold blue");
    let green = Style::parse("green");
    let default = Style::null();

    let mut tree = Tree::new(Text::new("my_project/", bold_blue.clone()))
        .with_guide_style(Style::parse("dim"));

    {
        let src = tree.add(Text::new("src/", bold_blue.clone()));
        src.add(Text::new("main.rs", green.clone()));
        src.add(Text::new("lib.rs", green.clone()));
        let models = src.add(Text::new("models/", bold_blue.clone()));
        models.add(Text::new("user.rs", default.clone()));
        models.add(Text::new("post.rs", default.clone()));
    }
    {
        let tests = tree.add(Text::new("tests/", bold_blue.clone()));
        tests.add(Text::new("integration.rs", default.clone()));
        tests.add(Text::new("unit.rs", default.clone()));
    }
    tree.add(Text::new("Cargo.toml", green.clone()));
    tree.add(Text::new("README.md", default.clone()));

    console.print(&tree);
    pause();

    // =========================================================================
    // 7. Columns
    // =========================================================================
    console.rule(Some("Columns"));

    let items = [
        "Rust",
        "Python",
        "Go",
        "TypeScript",
        "Java",
        "C++",
        "Ruby",
        "Swift",
        "Kotlin",
        "Haskell",
        "Elixir",
        "Zig",
        "Scala",
        "Clojure",
        "Erlang",
        "OCaml",
    ];

    let mut cols = Columns::new().with_equal(true);
    for item in &items {
        cols.add_renderable(item);
    }
    console.print(&cols);
    pause();

    // =========================================================================
    // 8. Rule
    // =========================================================================
    console.rule(Some("Rules"));

    console.print(&Rule::new());
    console.print(&Rule::with_title("Centered Title"));
    console.print(
        &Rule::with_title("Heavy Rule")
            .with_characters("\u{2501}")
            .with_style(Style::parse("bold red")),
    );
    console.print(
        &Rule::with_title("Double Line")
            .with_characters("=")
            .with_style(Style::parse("green")),
    );
    console.print(
        &Rule::with_title("Dotted")
            .with_characters(".")
            .with_style(Style::parse("dim")),
    );
    pause();

    // =========================================================================
    // 9. Emoji
    // =========================================================================
    console.rule(Some("Emoji"));

    let emoji_names = ["heart", "rocket", "star", "fire", "sparkles", "thumbs_up"];
    for name in &emoji_names {
        match Emoji::new(name) {
            Ok(emoji) => {
                let line = Text::new(&format!("  :{name}:  =>  {emoji}"), Style::null());
                console.print(&line);
            }
            Err(_) => {
                let line = Text::new(&format!("  :{name}:  =>  (not found)"), Style::null());
                console.print(&line);
            }
        }
    }
    console.line(1);

    let replaced = emoji_replace("I :heart: Rust! :rocket: :sparkles:", None);
    console.print(&Text::new(
        &format!("  Replaced: {replaced}"),
        Style::null(),
    ));
    pause();

    // =========================================================================
    // 10. Gradient Text
    // =========================================================================
    console.rule(Some("Gradient Text"));

    let rainbow =
        Gradient::rainbow("ROYGBIV: Red Orange Yellow Green Blue Indigo Violet - full spectrum!");
    console.print(&rainbow);

    let blue_to_green = Gradient::two_color(
        "Smooth transition from ocean blue to forest green",
        Color::from_rgb(0, 100, 255),
        Color::from_rgb(0, 200, 80),
    );
    console.print(&blue_to_green);

    let sunset = Gradient::new(
        "Sunset gradient: deep red through orange to warm gold",
        vec![
            Color::from_rgb(139, 0, 0),
            Color::from_rgb(255, 69, 0),
            Color::from_rgb(255, 200, 0),
        ],
    );
    console.print(&sunset);
    pause();

    // =========================================================================
    // 11. Syntax Highlighting (feature-gated)
    // =========================================================================
    #[cfg(feature = "syntax")]
    {
        console.rule(Some("Syntax Highlighting"));

        let rust_code = r#"use std::collections::HashMap;

fn main() {
    let mut scores: HashMap<&str, i32> = HashMap::new();
    scores.insert("Alice", 100);
    scores.insert("Bob", 85);

    for (name, score) in &scores {
        println!("{name}: {score}");
    }
}"#;

        let syntax = gilt::syntax::Syntax::new(rust_code, "rs")
            .with_line_numbers(true)
            .with_theme("base16-ocean.dark");
        console.print(&syntax);
        pause();
    }

    // =========================================================================
    // 12. Markdown (feature-gated)
    // =========================================================================
    #[cfg(feature = "markdown")]
    {
        console.rule(Some("Markdown"));

        let md_source = r#"# Gilt Features

Gilt supports **bold**, *italic*, and `inline code` in markdown.

## Bullet List

- Rich text rendering
- Progress bars and spinners
- Tables, trees, and panels

> The best way to predict the future is to invent it. -- Alan Kay
"#;

        let md = gilt::markdown::Markdown::new(md_source);
        console.print(&md);
        pause();
    }

    // =========================================================================
    // 13. JSON (feature-gated)
    // =========================================================================
    #[cfg(feature = "json")]
    {
        console.rule(Some("JSON"));

        let json_str = r#"{
    "name": "Gilt",
    "version": "0.1.0",
    "features": ["syntax", "markdown", "json"],
    "metadata": {
        "stars": 42,
        "active": true
    }
}"#;

        let json_widget =
            gilt::json::Json::new(json_str, gilt::json::JsonOptions::default()).unwrap();
        console.print(&json_widget);
        pause();
    }

    // =========================================================================
    // 14. Highlighters
    // =========================================================================
    console.rule(Some("Highlighters"));

    let url_hl = URLHighlighter::new();
    let text = url_hl.apply("Visit https://example.com or http://localhost:8080/api");
    console.print_text("[dim]URL:[/dim]");
    console.print(&text);

    let uuid_hl = UUIDHighlighter::new();
    let text = uuid_hl.apply("Request ID: 550e8400-e29b-41d4-a716-446655440000");
    console.print_text("[dim]UUID:[/dim]");
    console.print(&text);

    let iso_hl = ISODateHighlighter::new();
    let text = iso_hl.apply("Created: 2024-01-15T10:30:00Z  Updated: 2024-06-20");
    console.print_text("[dim]ISO Date:[/dim]");
    console.print(&text);

    let jp_hl = JSONPathHighlighter::new();
    let text = jp_hl.apply("Access $.config.database.host or .users[0].name");
    console.print_text("[dim]JSONPath:[/dim]");
    console.print(&text);
    pause();

    // =========================================================================
    // 15. Inspect
    // =========================================================================
    console.rule(Some("Inspect"));

    let numbers = vec![1, 2, 3, 42, 100];
    let inspect = Inspect::new(&numbers).with_label("numbers");
    console.print(&inspect);

    let mut config: HashMap<String, String> = HashMap::new();
    config.insert("host".into(), "localhost".into());
    config.insert("port".into(), "8080".into());
    config.insert("debug".into(), "true".into());
    let inspect = Inspect::new(&config)
        .with_label("config")
        .with_doc("Application configuration map");
    console.print(&inspect);
    pause();

    // =========================================================================
    // 16. Pretty Printing
    // =========================================================================
    console.rule(Some("Pretty Printing"));

    let nested = json!({
        "server": {
            "host": "0.0.0.0",
            "port": 8080,
            "tls": { "enabled": true, "cert": "/etc/ssl/cert.pem" }
        },
        "database": {
            "url": "postgres://localhost:5432/myapp",
            "pool_size": 10
        }
    });
    let pretty = Pretty::from_json(&nested);
    console.print(&pretty);
    pause();

    // =========================================================================
    // 17. Accessibility
    // =========================================================================
    console.rule(Some("Accessibility"));

    let pairs: &[(&str, ColorTriplet, &str, ColorTriplet)] = &[
        (
            "Black",
            ColorTriplet::new(0, 0, 0),
            "White",
            ColorTriplet::new(255, 255, 255),
        ),
        (
            "Dark Blue",
            ColorTriplet::new(0, 0, 139),
            "Light Yellow",
            ColorTriplet::new(255, 255, 224),
        ),
        (
            "Red",
            ColorTriplet::new(255, 0, 0),
            "White",
            ColorTriplet::new(255, 255, 255),
        ),
        (
            "Gray",
            ColorTriplet::new(128, 128, 128),
            "Black",
            ColorTriplet::new(0, 0, 0),
        ),
    ];

    for (fg_name, fg, bg_name, bg) in pairs {
        let ratio = contrast_ratio(fg, bg);
        let aa = if meets_aa(fg, bg) { "PASS" } else { "FAIL" };
        let aaa = if meets_aaa(fg, bg) { "PASS" } else { "FAIL" };
        let line = format!("  {fg_name} on {bg_name}: ratio={ratio:.1}:1  AA={aa}  AAA={aaa}");
        console.print(&Text::new(&line, Style::null()));
    }
    pause();

    // =========================================================================
    // 18. Progress Bars (Animated)
    // =========================================================================
    console.rule(Some("Progress Bars (Animated)"));

    {
        let progress_console = Console::builder()
            .width(90)
            .force_terminal(true)
            .no_color(false)
            .build();

        let mut progress = Progress::new(Progress::default_columns())
            .with_console(progress_console)
            .with_auto_refresh(false);

        let task1 = progress.add_task("Downloading dataset.tar.gz", Some(1000.0), true);
        let task2 = progress.add_task("Processing model-weights.bin", Some(500.0), true);
        let task3 = progress.add_task("Compiling config.json", Some(200.0), true);

        progress.start();

        let mut done1 = false;
        let mut done2 = false;
        let mut done3 = false;

        loop {
            if !done1 {
                progress.advance(task1, 20.0);
                if let Some(t) = progress.get_task(task1) {
                    if t.finished() {
                        done1 = true;
                    }
                }
            }
            if !done2 {
                progress.advance(task2, 8.0);
                if let Some(t) = progress.get_task(task2) {
                    if t.finished() {
                        done2 = true;
                    }
                }
            }
            if !done3 {
                progress.advance(task3, 5.0);
                if let Some(t) = progress.get_task(task3) {
                    if t.finished() {
                        done3 = true;
                    }
                }
            }

            progress.refresh();

            if done1 && done2 && done3 {
                break;
            }

            thread::sleep(Duration::from_millis(50));
        }

        progress.stop();
    }
    pause();

    // =========================================================================
    // 19. Status Spinner (Animated)
    // =========================================================================
    console.rule(Some("Status Spinner (Animated)"));

    {
        let status_console = Console::builder()
            .force_terminal(true)
            .no_color(false)
            .build();

        let messages = [
            "Connecting to server...",
            "Authenticating...",
            "Fetching data...",
            "Almost done...",
        ];

        let mut status = Status::new(messages[0]).with_console(status_console);
        status.start();

        for msg in &messages[1..] {
            thread::sleep(Duration::from_millis(500));
            status.set(msg);
        }

        thread::sleep(Duration::from_millis(500));
        status.stop();
    }
    pause();

    // =========================================================================
    // 20. Bar
    // =========================================================================
    console.rule(Some("Bar Widgets"));

    let bar_width: usize = 40;
    let levels: &[(&str, f64)] = &[
        ("  0% ", 0.0),
        (" 25% ", 10.0),
        (" 50% ", 20.0),
        (" 75% ", 30.0),
        ("100% ", 40.0),
    ];

    for (label, end) in levels {
        let label_text = Text::new(label, Style::parse("bold"));
        console.print(&label_text);
        let bar = Bar::new(40.0, 0.0, *end).with_width(bar_width);
        console.print(&bar);
    }

    console.line(1);

    let colors: &[(&str, &str, f64)] = &[
        ("Red   ", "red", 15.0),
        ("Green ", "green", 25.0),
        ("Blue  ", "blue", 35.0),
        ("Yellow", "yellow", 40.0),
    ];

    for (label, color_name, end) in colors {
        let label_text = Text::new(&format!("{label} "), Style::null());
        console.print(&label_text);
        let bar = Bar::new(40.0, 0.0, *end)
            .with_width(bar_width)
            .with_color(Color::parse(color_name).unwrap());
        console.print(&bar);
    }
    pause();

    // =========================================================================
    // 21. Filesize (Decimal & Binary)
    // =========================================================================
    console.rule(Some("Filesize (Decimal & Binary)"));

    let sizes: &[(&str, u64)] = &[
        ("Empty file", 0),
        ("Small file", 1),
        ("Text file", 4_096),
        ("Photo", 3_500_000),
        ("Video", 1_200_000_000),
        ("Dataset", 5_000_000_000_000),
    ];

    console.print(&Text::new(
        &format!(
            "  {:.<20} {:>14}  {:>14}",
            "Name", "Decimal (SI)", "Binary (IEC)"
        ),
        Style::parse("bold"),
    ));
    for (name, size) in sizes {
        let dec = filesize::decimal(*size, 1, " ");
        let bin = filesize::binary(*size, 1, " ");
        let line = format!("  {name:.<20} {dec:>14}  {bin:>14}");
        console.print(&Text::new(&line, Style::null()));
    }
    pause();

    // =========================================================================
    // 22. Layout
    // =========================================================================
    console.rule(Some("Layout"));

    {
        let mut layout_console = Console::builder()
            .width(90)
            .height(12)
            .force_terminal(true)
            .no_color(false)
            .build();

        let mut layout = Layout::new(None, Some("root".to_string()), None, None, None, None);
        let header = Layout::new(
            Some("HEADER: gilt layout system".to_string()),
            Some("header".to_string()),
            Some(3),
            None,
            None,
            None,
        );
        let mut body = Layout::new(None, Some("body".to_string()), None, None, Some(1), None);
        let sidebar = Layout::new(
            Some("Sidebar".to_string()),
            Some("sidebar".to_string()),
            Some(20),
            None,
            None,
            None,
        );
        let main = Layout::new(
            Some("Main content area".to_string()),
            Some("main".to_string()),
            None,
            None,
            Some(1),
            None,
        );
        body.split_row(vec![sidebar, main]);
        let footer = Layout::new(
            Some("FOOTER".to_string()),
            Some("footer".to_string()),
            Some(3),
            None,
            None,
            None,
        );
        layout.split_column(vec![header, body, footer]);
        layout_console.print(&layout);
    }
    pause();

    // =========================================================================
    // 23. Align
    // =========================================================================
    console.rule(Some("Alignment"));

    let left = Align::left(Text::new("Left-aligned text", Style::null()));
    console.print(&left);

    let center = Align::center(Text::new("Center-aligned text", Style::null()));
    console.print(&center);

    let right = Align::right(Text::new("Right-aligned text", Style::null()));
    console.print(&right);
    pause();

    // =========================================================================
    // 24. Padding
    // =========================================================================
    console.rule(Some("Padding"));

    let padded = Padding::new(
        Text::new(
            "This text has padding: top=1, right=4, bottom=1, left=8",
            Style::null(),
        ),
        PaddingDimensions::Full(1, 4, 1, 8),
        Style::null(),
        true,
    );
    console.print(&padded);

    let indented = Padding::indent(Text::new("Indented text (left=6)", Style::null()), 6);
    console.print(&indented);
    pause();

    // =========================================================================
    // 25. Constrain
    // =========================================================================
    console.rule(Some("Constrain"));

    let wide_text = Text::new(
        "This text would normally fill the full 90-column width, but Constrain limits it to 50 characters, causing it to wrap earlier.",
        Style::null(),
    );
    let constrained = Constrain::new(wide_text, Some(50));
    console.print(&constrained);
    pause();

    // =========================================================================
    // 26. Styled Containers
    // =========================================================================
    console.rule(Some("Styled Containers"));

    let inner = Text::new("Bold + italic overlay via Styled container", Style::null());
    let styled_widget = Styled::new(inner, Style::parse("bold italic cyan"));
    console.print(&styled_widget);

    let inner2 = Text::new("Red on dark background", Style::parse("red"));
    let styled_widget2 = Styled::new(inner2, Style::parse("on grey11"));
    console.print(&styled_widget2);
    pause();

    // =========================================================================
    // 27. Text Justify Modes
    // =========================================================================
    console.rule(Some("Text Justification"));

    let justify_modes = [
        ("Left", JustifyMethod::Left),
        ("Center", JustifyMethod::Center),
        ("Right", JustifyMethod::Right),
        ("Full", JustifyMethod::Full),
    ];

    for (label, justify) in &justify_modes {
        let mut text = Text::new(
            &format!("{label}: The quick brown fox jumps over the lazy dog near the riverbank."),
            Style::null(),
        );
        text.justify = Some(*justify);
        let panel = Panel::fit(text)
            .with_title(Text::new(label, Style::parse("bold")))
            .with_border_style(Style::parse("dim"));
        console.print(&panel);
    }
    pause();

    // =========================================================================
    // 28. Text Overflow
    // =========================================================================
    console.rule(Some("Text Overflow"));

    let overflow_modes = [
        ("Fold", OverflowMethod::Fold),
        ("Crop", OverflowMethod::Crop),
        ("Ellipsis", OverflowMethod::Ellipsis),
    ];

    for (label, overflow) in &overflow_modes {
        let mut text = Text::new(
            "Superlongwordwithoutanyspacesthatexceedsthenormalwidth_and_continues_going_forever",
            Style::null(),
        );
        text.overflow = Some(*overflow);
        let constrained_overflow = Constrain::new(text, Some(40));
        console.print(&Text::new(&format!("  {label}:"), Style::parse("bold")));
        console.print(&constrained_overflow);
    }
    pause();

    // =========================================================================
    // 29. Scope
    // =========================================================================
    console.rule(Some("Scope"));

    let scope = Scope::from_pairs(&[
        ("host", "localhost"),
        ("port", "8080"),
        ("debug", "true"),
        ("workers", "4"),
        ("database_url", "postgres://localhost/myapp"),
    ])
    .title("Server Config");
    console.print(&scope);
    pause();

    // =========================================================================
    // 30. Logging
    // =========================================================================
    console.rule(Some("Logging (console.log)"));

    console.log("Application started");
    console.log("[bold green]Server[/bold green] listening on port 8080");
    console.log("[yellow]Warning:[/yellow] cache miss for key 'user:42'");
    console.log("[red]Error:[/red] connection timeout after 30s");
    pause();

    // =========================================================================
    // 31. Color Systems
    // =========================================================================
    console.rule(Some("Color Systems"));

    let color_systems = [
        ("truecolor", "TrueColor (16M)"),
        ("256", "256 colors"),
        ("standard", "Standard (16)"),
    ];

    for (cs, label) in &color_systems {
        let mut cs_console = Console::builder()
            .width(90)
            .force_terminal(true)
            .color_system(cs)
            .build();
        cs_console.begin_capture();
        cs_console.print(&Text::styled(
            format!("  {label}: Hello from rgb(255,102,0) on rgb(0,51,102)"),
            "rgb(255,102,0) on rgb(0,51,102) bold",
        ));
        let captured = cs_console.end_capture();
        console.print(&Text::new(captured.trim_end(), Style::null()));
    }

    // No color
    {
        let mut nc_console = Console::builder()
            .width(90)
            .force_terminal(true)
            .no_color(true)
            .build();
        nc_console.begin_capture();
        nc_console.print(&Text::styled(
            "  No Color: Hello (styles stripped)",
            "bold red",
        ));
        let captured = nc_console.end_capture();
        console.print(&Text::new(captured.trim_end(), Style::null()));
    }
    pause();

    // =========================================================================
    // 32. Theme Push/Pop
    // =========================================================================
    console.rule(Some("Theme Push/Pop"));

    console.print_text("[bold]Default theme:[/bold] [info]info style[/info]");

    let mut custom_styles = HashMap::new();
    custom_styles.insert("info".to_string(), Style::parse("bold magenta on grey15"));
    let custom_theme = Theme::new(Some(custom_styles), true);
    console.push_theme(custom_theme, true);

    console.print_text("[bold]Custom theme:[/bold] [info]info is now magenta on grey[/info]");

    console.pop_theme();
    console.print_text("[bold]After pop:[/bold] [info]info reverted to default[/info]");
    pause();

    // =========================================================================
    // 33. Console Capture & Export
    // =========================================================================
    console.rule(Some("Console Capture"));

    {
        let mut cap_console = Console::builder()
            .width(60)
            .force_terminal(true)
            .no_color(true)
            .build();

        cap_console.begin_capture();
        cap_console.print(&Text::new("First captured line", Style::null()));
        cap_console.print(&Text::new("Second captured line", Style::null()));
        cap_console.print(&Text::new("Third captured line", Style::null()));
        let captured = cap_console.end_capture();

        console.print(&Text::new(
            "  Captured output (3 lines):",
            Style::parse("bold"),
        ));
        for line in captured.lines() {
            console.print(&Text::new(&format!("    | {line}"), Style::parse("dim")));
        }
    }
    pause();

    // =========================================================================
    // 34. Synchronized Output
    // =========================================================================
    console.rule(Some("Synchronized Output"));

    console.synchronized(|c| {
        c.print(&Text::new(
            "  These lines are rendered atomically",
            Style::parse("bold green"),
        ));
        c.print(&Text::new(
            "  inside a DEC Mode 2026 sync block.",
            Style::parse("green"),
        ));
        c.print(&Text::new(
            "  The terminal buffers until the block ends.",
            Style::parse("dim green"),
        ));
    });
    pause();

    // =========================================================================
    // 35. Traceback
    // =========================================================================
    console.rule(Some("Traceback"));

    // Error chain traceback
    let inner_err = io::Error::new(io::ErrorKind::ConnectionRefused, "connection refused");
    let outer_err = io::Error::other(format!("failed to connect to database: {}", inner_err));
    let tb = Traceback::from_error(&outer_err);
    console.print(&tb);

    // Custom traceback with source lines
    let frames = vec![
        Frame::new("src/database.rs", Some(87), "Database::connect")
            .with_source_line("    let conn = TcpStream::connect(&self.addr)?;"),
        Frame::new("src/main.rs", Some(28), "main")
            .with_source_line("    server.run(handle_request).await?;"),
    ];
    let tb = Traceback {
        title: "ConnectionError".to_string(),
        message: "failed to establish connection".to_string(),
        frames,
        ..Traceback::new()
    };
    console.print(&tb);
    pause();

    // =========================================================================
    // 36. Wrap Modes
    // =========================================================================
    console.rule(Some("Text Wrapping"));

    let long_text = "word1 word2 word3 word4 word5 word6 word7 word8 word9 word10 word11 word12 word13 word14 word15";
    let wrapped = Text::new(long_text, Style::null());
    let lines = wrapped.wrap(
        &console,
        40,
        Some(JustifyMethod::Left),
        Some(OverflowMethod::Fold),
        8,
        false,
    );
    console.print(&Text::new("  Wrapped at 40 cols:", Style::parse("bold")));
    for line in lines.iter() {
        console.print(&Text::new(
            &format!("    {}", line.plain()),
            Style::parse("dim"),
        ));
    }

    let tab_text = Text::new("col1\tcol2\tcol3\tcol4", Style::null());
    let tab_lines = tab_text.wrap(&console, 60, Some(JustifyMethod::Left), None, 8, false);
    console.print(&Text::new(
        "  Tab stops (tab_size=8):",
        Style::parse("bold"),
    ));
    for line in tab_lines.iter() {
        console.print(&Text::new(
            &format!("    {}", line.plain()),
            Style::parse("dim"),
        ));
    }
    pause();

    // =========================================================================
    // 37. #[derive(Table)] (feature-gated)
    // =========================================================================
    #[cfg(feature = "derive")]
    {
        console.rule(Some("Derive Table"));

        use gilt::Table as DeriveTable;

        #[derive(DeriveTable)]
        struct Planet {
            name: String,
            distance_au: f64,
            moons: u32,
        }

        let planets = vec![
            Planet {
                name: "Mercury".into(),
                distance_au: 0.39,
                moons: 0,
            },
            Planet {
                name: "Venus".into(),
                distance_au: 0.72,
                moons: 0,
            },
            Planet {
                name: "Earth".into(),
                distance_au: 1.00,
                moons: 1,
            },
            Planet {
                name: "Mars".into(),
                distance_au: 1.52,
                moons: 2,
            },
        ];

        let table = Planet::to_table(&planets);
        console.print(&table);
        pause();
    }

    // =========================================================================
    // 38. Spinners Gallery
    // =========================================================================
    console.rule(Some("Spinner Gallery"));

    let spinner_names = [
        "dots",
        "dots2",
        "dots3",
        "line",
        "pipe",
        "simpleDots",
        "star",
        "arc",
        "bouncingBar",
        "moon",
    ];

    for name in &spinner_names {
        if let Some(data) = SPINNERS.get(name) {
            let frames_preview: String = data
                .frames
                .iter()
                .take(10)
                .cloned()
                .collect::<Vec<_>>()
                .join(" ");
            let line = format!("  {:<20} {}", name, frames_preview);
            console.print(&Text::new(&line, Style::null()));
        }
    }
    pause();

    // =========================================================================
    // 39. ANSI Parsing
    // =========================================================================
    console.rule(Some("ANSI Parsing"));

    let ansi_input = "\x1b[1mBold\x1b[0m \x1b[31mRed\x1b[0m \x1b[32mGreen\x1b[0m \x1b[1;34mBold Blue\x1b[0m Normal";
    let mut decoder = AnsiDecoder::new();
    let decoded_lines = decoder.decode(ansi_input);
    console.print(&Text::new(
        "  Raw ANSI input parsed into styled Text:",
        Style::parse("bold"),
    ));
    for line in &decoded_lines {
        console.print(line);
    }
    pause();

    // =========================================================================
    // 40. Color Palette
    // =========================================================================
    console.rule(Some("Standard Color Palette"));

    let color_names = [
        ("black", "color(0)"),
        ("red", "color(1)"),
        ("green", "color(2)"),
        ("yellow", "color(3)"),
        ("blue", "color(4)"),
        ("magenta", "color(5)"),
        ("cyan", "color(6)"),
        ("white", "color(7)"),
        ("bright_black", "color(8)"),
        ("bright_red", "color(9)"),
        ("bright_green", "color(10)"),
        ("bright_yellow", "color(11)"),
        ("bright_blue", "color(12)"),
        ("bright_magenta", "color(13)"),
        ("bright_cyan", "color(14)"),
        ("bright_white", "color(15)"),
    ];

    for (name, color_spec) in &color_names {
        let combined = format!("  \u{2588}\u{2588}  {name}");
        let combined_style = Style::parse(color_spec);
        console.print(&Text::styled_with(&combined, combined_style));
    }
    pause();

    // =========================================================================
    // 41. Sparkline
    // =========================================================================
    console.rule(Some("Sparkline"));

    // Simulated CPU usage over time (%)
    let cpu_data: Vec<f64> = vec![
        12.0, 15.0, 22.0, 35.0, 42.0, 55.0, 68.0, 72.0, 80.0, 95.0, 88.0, 70.0, 60.0, 45.0, 38.0,
        30.0, 25.0, 18.0, 20.0, 28.0, 35.0, 50.0, 62.0, 75.0, 85.0, 78.0, 65.0, 55.0, 40.0, 32.0,
        22.0, 15.0, 10.0, 18.0, 30.0, 45.0, 58.0, 70.0, 82.0, 90.0,
    ];
    let spark = Sparkline::new(&cpu_data)
        .with_width(70)
        .with_style(Style::parse("bold green"));
    console.print(&Text::new("  CPU usage over time:", Style::parse("bold")));
    console.print(&spark);

    // Memory pressure — shorter data, no resample
    let mem_data: Vec<f64> = vec![
        30.0, 32.0, 35.0, 40.0, 55.0, 70.0, 85.0, 92.0, 95.0, 88.0, 75.0, 60.0,
    ];
    let mem_spark = Sparkline::new(&mem_data).with_style(Style::parse("bold yellow"));
    console.print(&Text::new("  Memory pressure:", Style::parse("bold")));
    console.print(&mem_spark);
    pause();

    // =========================================================================
    // 42. Canvas (Braille Dot-Matrix Graphics)
    // =========================================================================
    console.rule(Some("Canvas (Braille Dot-Matrix)"));

    // 30 cols x 8 rows => 60x32 pixel grid
    let mut canvas = Canvas::new(30, 8).with_style(Style::parse("cyan"));

    // Draw a rectangle border
    canvas.rect(0, 0, 59, 31);

    // Draw diagonal lines forming an X
    canvas.line(2, 2, 56, 28);
    canvas.line(56, 2, 2, 28);

    // Draw a circle in the center
    canvas.circle(30, 16, 12);

    console.print(&canvas);
    pause();

    // =========================================================================
    // 43. Diff (Text Diff)
    // =========================================================================
    console.rule(Some("Text Diff"));

    let old_code = r#"fn greet(name: &str) {
    println!("Hello, {}!", name);
}

fn main() {
    greet("world");
}"#;

    let new_code = r#"fn greet(name: &str, excited: bool) {
    if excited {
        println!("Hello, {}!!", name);
    } else {
        println!("Hello, {}.", name);
    }
}

fn main() {
    greet("world", true);
}"#;

    let diff = Diff::new(old_code, new_code)
        .with_labels("a/greet.rs", "b/greet.rs")
        .with_context(2);
    console.print(&diff);
    pause();

    // =========================================================================
    // 44. Figlet (ASCII Art)
    // =========================================================================
    console.rule(Some("Figlet (ASCII Art)"));

    let banner = Figlet::new("GILT").with_style(Style::parse("bold bright_magenta"));
    console.print(&banner);
    console.line(1);

    let sub_banner = Figlet::new("v0.5")
        .with_style(Style::parse("dim cyan"))
        .with_width(90);
    console.print(&sub_banner);
    pause();

    // =========================================================================
    // 45. CSV Table
    // =========================================================================
    console.rule(Some("CSV Table"));

    let csv_data = "\
City,Country,Population,Area (km2)
Tokyo,Japan,13960000,2194
Delhi,India,11030000,1484
Shanghai,China,24870000,6341
Sao Paulo,Brazil,12330000,1521
Mumbai,India,12440000,603";

    let csv = CsvTable::from_csv_str(csv_data)
        .unwrap()
        .with_title("World Cities")
        .with_header_style(Style::parse("bold magenta"));
    console.print(&csv);
    pause();

    // =========================================================================
    // 46. Iterator .progress() (non-animated summary)
    // =========================================================================
    console.rule(Some("Iterator Progress (.progress())"));

    console.print(&Text::new(
        "  The ProgressIteratorExt trait adds .progress() to any iterator:",
        Style::null(),
    ));
    console.print(&Text::new(
        "    for item in (0..100).progress(\"Processing\") { ... }",
        Style::parse("bold green"),
    ));
    console.print(&Text::new(
        "    for item in data.iter().progress_with_total(\"Loading\", 500.0) { ... }",
        Style::parse("bold green"),
    ));
    console.print(&Text::new(
        "  Total is inferred from size_hint() or set explicitly.",
        Style::parse("dim"),
    ));
    pause();

    // =========================================================================
    // 47. Derive Macros (feature-gated)
    // =========================================================================
    #[cfg(feature = "derive")]
    {
        console.rule(Some("Derive Macros"));

        console.print(&Text::new(
            "  gilt-derive provides: #[derive(Table)], #[derive(Panel)],",
            Style::null(),
        ));
        console.print(&Text::new(
            "  #[derive(Tree)], #[derive(Columns)], #[derive(Rule)],",
            Style::null(),
        ));
        console.print(&Text::new(
            "  #[derive(Inspect)], and #[derive(Renderable)]",
            Style::null(),
        ));
        console.line(1);

        // Demonstrate #[derive(Panel)]
        use gilt::Panel as PanelDerive;

        #[derive(PanelDerive)]
        #[panel(
            title = "Server Status",
            box_style = "ROUNDED",
            border_style = "bright_green",
            title_style = "bold white"
        )]
        struct ServerStatus {
            #[field(label = "Host", style = "bold cyan")]
            host: String,
            #[field(label = "Port")]
            port: u16,
            #[field(label = "Status", style = "bold green")]
            status: String,
            #[field(label = "Uptime")]
            uptime: String,
        }

        let server = ServerStatus {
            host: "prod-web-01.example.com".into(),
            port: 443,
            status: "HEALTHY".into(),
            uptime: "47 days, 13:22:09".into(),
        };
        console.print(&server.to_panel());

        // Demonstrate #[derive(Tree)]
        use gilt::Tree as TreeDerive;

        #[derive(TreeDerive)]
        #[tree(style = "bold blue", guide_style = "dim")]
        struct MenuItem {
            #[tree(label)]
            name: String,
            #[tree(children)]
            items: Vec<MenuItem>,
        }

        let menu = MenuItem {
            name: "Application".into(),
            items: vec![
                MenuItem {
                    name: "File".into(),
                    items: vec![
                        MenuItem {
                            name: "New".into(),
                            items: vec![],
                        },
                        MenuItem {
                            name: "Open".into(),
                            items: vec![],
                        },
                    ],
                },
                MenuItem {
                    name: "Edit".into(),
                    items: vec![
                        MenuItem {
                            name: "Undo".into(),
                            items: vec![],
                        },
                        MenuItem {
                            name: "Redo".into(),
                            items: vec![],
                        },
                    ],
                },
            ],
        };
        console.print(&menu.to_tree());

        // Demonstrate #[derive(Columns)]
        use gilt::derives::Columns;

        #[derive(Columns)]
        #[columns(equal, padding = 1)]
        struct Framework {
            #[field(label = "Name", style = "bold")]
            name: String,
            #[field(label = "Language", style = "cyan")]
            language: String,
            #[field(label = "Stars")]
            stars: String,
        }

        let frameworks = vec![
            Framework {
                name: "Axum".into(),
                language: "Rust".into(),
                stars: "19k".into(),
            },
            Framework {
                name: "Actix".into(),
                language: "Rust".into(),
                stars: "22k".into(),
            },
            Framework {
                name: "Rocket".into(),
                language: "Rust".into(),
                stars: "24k".into(),
            },
        ];
        console.print(&Framework::to_columns(&frameworks));
        pause();
    }

    // =========================================================================
    // gilt 2.0 — Parity Additions (new APIs in the 2.0 rich-parity release)
    // =========================================================================
    console.line(1);
    let v2 = Gradient::rainbow("  ✦ gilt 2.0 — rich-parity additions ✦  ")
        .with_style(Style::parse("bold"));
    console.print(&v2);

    // -- Pretty-print any Debug value (Console::pprint / pretty_repr) ----------
    console.rule(Some("2.0: Pretty-Printing Rust Values"));
    {
        #[derive(Debug)]
        #[allow(dead_code)]
        struct Server {
            host: String,
            port: u16,
            tags: Vec<&'static str>,
        }
        let srv = Server {
            host: "localhost".into(),
            port: 8080,
            tags: vec!["web", "tls"],
        };
        console.pprint(&srv);
        let repr = gilt::pretty::pretty_repr(&vec![1, 2, 3], 80);
        console.print_text(&format!("[dim]pretty_repr(&vec![1,2,3]) ->[/dim] {repr}"));
    }
    pause();

    // -- Scoped theme guard (use_theme returns a RAII ThemeGuard) --------------
    console.rule(Some("2.0: Scoped Theme Guard (use_theme)"));
    {
        let mut styles = HashMap::new();
        styles.insert("info".to_string(), Style::parse("bold cyan"));
        let theme = Theme::new(Some(styles), true);
        let mut guard = console.use_theme(theme, true);
        guard.print_text(
            "[info]Inside the guard:[/info] info is bold cyan (rendered through the guard)",
        );
        drop(guard); // theme auto-pops here
        console.print_text("[info]After drop:[/info] info reverted to the default theme");
    }
    pause();

    // -- Variadic console.log (log multiple renderables at once) ---------------
    console.rule(Some("2.0: Variadic console.log_objects"));
    {
        let first = Text::new("first object", Style::parse("green"));
        let second = Text::new("second object", Style::parse("cyan"));
        console.log_objects(&[&first as &dyn gilt::console::Renderable, &second], false);
    }
    pause();

    // -- Low-level Segments / SegmentLines renderables -------------------------
    console.rule(Some("2.0: Low-Level Segments"));
    {
        use gilt::segment::{Segment, SegmentLines, Segments};
        console.print(&Segments(vec![
            Segment::new("red ", Some(Style::parse("red")), None),
            Segment::new("green ", Some(Style::parse("green")), None),
            Segment::new("blue", Some(Style::parse("blue")), None),
        ]));
        console.print(&SegmentLines(vec![
            vec![Segment::new(
                "line one (bold)",
                Some(Style::parse("bold")),
                None,
            )],
            vec![Segment::new(
                "line two (dim)",
                Some(Style::parse("dim")),
                None,
            )],
        ]));
    }
    pause();

    // -- Vertical centering (vertical_center convenience) ----------------------
    console.rule(Some("2.0: Vertical Centering"));
    {
        // vertical_center sets vertical=Middle; give the Align an explicit
        // height so it actually centers (a bare print has no height to center within).
        let mut centered = vertical_center(Text::new(
            "centered vertically",
            Style::parse("bold yellow"),
        ));
        centered.height = Some(5);
        console.print(&Panel::new(centered).with_title("vertical_center (h=5)"));
    }
    pause();

    // -- Unicode-aware splitting (cells::split_graphemes / split_text) ---------
    console.rule(Some("2.0: Unicode-Aware Splitting"));
    {
        let text = "日本語ab🇺🇸";
        console.print_text(&format!("[bold]split_graphemes[/bold]({text:?}):"));
        for (start, end, width) in gilt::utils::split_graphemes(text) {
            console.print_text(&format!(
                "  [cyan]{:?}[/cyan] -> cell width [yellow]{width}[/yellow]",
                &text[start..end]
            ));
        }
        let (left, right) = gilt::utils::split_text(text, 4);
        console.print_text(&format!(
            "[bold]split_text[/bold](_, 4) -> ([green]{left:?}[/green], [green]{right:?}[/green])"
        ));
    }
    pause();

    // -- ANSI color name <-> number accessors ----------------------------------
    console.rule(Some("2.0: ANSI Color Name Accessors"));
    {
        let name = gilt::ansi_color_name(1).unwrap_or("?");
        let num = gilt::get_ansi_color_number("green").unwrap_or(255);
        console.print_text(&format!(
            "ansi_color_name(1) = [red]{name}[/red]    get_ansi_color_number(\"green\") = [green]{num}[/green]"
        ));
    }
    pause();

    // -- Color downgrade across color systems (the v2.0 parity fix) ------------
    console.rule(Some("2.0: Color Downgrade Across Systems"));
    {
        use gilt::color::ColorSystem;
        console.print_text(
            "[bold]#1e90ff[/bold] (DodgerBlue) [on #1e90ff]        [/on #1e90ff] downgraded:",
        );
        let c = Color::parse("#1e90ff").unwrap();
        for sys in [
            ColorSystem::TrueColor,
            ColorSystem::EightBit,
            ColorSystem::Standard,
            ColorSystem::Windows,
        ] {
            console.print_text(&format!(
                "  [dim]{:<10}[/dim] -> {:?}",
                format!("{sys:?}"),
                c.downgrade(sys)
            ));
        }
    }
    pause();

    // -- Export the same content to HTML and SVG (record mode) -----------------
    console.rule(Some("2.0: Export to HTML & SVG"));
    {
        let mut rec = Console::builder()
            .width(40)
            .force_terminal(true)
            .record(true)
            .build();
        rec.print_text("[bold red]Recorded[/bold red] for export");
        let html = rec.export_html(None, false, true);
        let svg = rec.export_svg("Demo", None, false, None, 0.61);
        console.print_text(&format!(
            "[green]export_html[/green] -> {} bytes (contains `<span`: {})",
            html.len(),
            html.contains("<span")
        ));
        console.print_text(&format!(
            "[green]export_svg[/green]  -> {} bytes (contains `<svg`: {})",
            svg.len(),
            svg.contains("<svg")
        ));
    }
    pause();

    // -- Live region: real-time content updates (lock-free ArcSwap) ------------
    console.rule(Some("2.0: Live Region (real-time updates)"));
    {
        let live_console = Console::builder().width(60).force_terminal(true).build();
        let mut live = Live::new(Text::new("", Style::null()))
            .with_console(live_console)
            .with_auto_refresh(false);
        live.start();
        for i in 0..=10u32 {
            let pct = i * 10;
            let filled: String = std::iter::repeat_n('', i as usize * 3).collect();
            let style = if pct < 100 { "yellow" } else { "bold green" };
            let body = Text::new(&format!("Loading {pct:>3}%\n{filled}"), Style::parse(style));
            live.set(Panel::new(body).with_title("Live"));
            live.refresh();
            thread::sleep(Duration::from_millis(80));
        }
        live.stop();
    }
    pause();

    // -- Live pause/resume: the v1.11 headline feature (sticky hand-off) -------
    console.rule(Some("2.0: Live Pause / Resume"));
    {
        let footer_console = Console::builder().width(70).force_terminal(true).build();
        let mut footer = Live::new(Panel::new(Text::new(
            "● status: starting",
            Style::parse("bold green"),
        )))
        .with_console(footer_console)
        .with_auto_refresh(false);
        footer.start();
        for i in 1..=3u32 {
            footer.set(Panel::new(Text::new(
                &format!("● status: working ({i}/3)"),
                Style::parse("bold yellow"),
            )));
            footer.refresh();
            thread::sleep(Duration::from_millis(120));
        }
        // pause() erases the live region but PRESERVES its state for resume.
        footer.pause();
        console.print_text("[dim](footer paused — its state is preserved; printing below)[/dim]");
        let mut t = Tree::new(Text::new("results/", Style::parse("bold blue")));
        t.add(Text::new("passed: 42", Style::parse("green")));
        t.add(Text::new("failed:  0", Style::parse("dim")));
        console.print(&t);
        // resume() re-renders the live region in place — no rebuild needed.
        footer.resume();
        footer.set(Panel::new(Text::new(
            "● status: done ✓",
            Style::parse("bold green"),
        )));
        footer.refresh();
        thread::sleep(Duration::from_millis(200));
        footer.stop();
    }
    pause();

    // =========================================================================
    // Grand Finale — Full-Screen "Coding Agent" TUI
    // =========================================================================
    // Everything integrated in a live, full-screen (alternate-screen) app:
    // a Layout with a header bar, a file Tree sidebar, a Markdown task list +
    // a live code panel, and a footer progress Bar — all redrawn each frame
    // like a CLI coding agent working through a task. On a real terminal this
    // clears the screen, runs full-screen, then restores your scrollback.
    #[cfg(feature = "markdown")]
    {
        use gilt::console::into_renderable_arc;
        use gilt::group::Group;
        use gilt::markdown::Markdown;

        let agent_console = Console::builder()
            .width(100)
            .height(30)
            .force_terminal(true)
            .no_color(false)
            .build();
        // with_screen(true) => alternate-screen buffer (full screen), restored on stop().
        let mut live = Live::new(Text::new("booting agent…", Style::null()))
            .with_console(agent_console)
            .with_screen(true)
            .with_auto_refresh(false);

        let spinner = ['', '', '', '', '', '', '', '', '', ''];
        let steps = [
            "scan repository",
            "read color/mod.rs",
            "patch EightBit downgrade",
            "run test suite",
            "commit & push",
        ];
        let code_lines = [
            "fn downgrade(c: Color, sys: ColorSystem) -> Color {",
            "    match sys {",
            "        ColorSystem::Standard => {",
            "            let t = c.get_truecolor(None, true);",
            "            let i = STANDARD_PALETTE.match_color(&t);",
            "            Color::Standard(i as u8)",
            "        }",
            "        _ => c,",
            "    }",
            "}",
        ];
        let total = 32u32;

        live.start();
        for frame in 0..total {
            let progress = frame as f64 / (total - 1) as f64; // 0.0 ..= 1.0
            let step_idx = ((progress * steps.len() as f64) as usize).min(steps.len() - 1);
            let spin = spinner[frame as usize % spinner.len()];
            let pct = (progress * 100.0) as u32;
            let passed = (progress * 3073.0) as u32;

            // Header bar.
            let header = Layout::new(None, Some("header".into()), Some(3), None, None, None)
                .with_renderable(
                    Panel::new(Text::new(
                        &format!("{spin}  gilt coding-agent   ·   {}", steps[step_idx]),
                        Style::parse("bold cyan"),
                    ))
                    .with_border_style(Style::parse("cyan")),
                );

            // Sidebar: a file tree (current file marked while editing).
            let mut tree = Tree::new(Text::new("gilt/", Style::parse("bold blue")));
            {
                let src = tree.add(Text::new("src/", Style::parse("bold blue")));
                let colordir = src.add(Text::new("color/", Style::parse("bold blue")));
                let (mark, st) = if step_idx >= 2 {
                    ("mod.rs  ✎", "bold yellow")
                } else {
                    ("mod.rs", "green")
                };
                colordir.add(Text::new(mark, Style::parse(st)));
                src.add(Text::new("live/mod.rs", Style::parse("green")));
                src.add(Text::new("markdown.rs", Style::parse("green")));
            }
            tree.add(Text::new("tests/", Style::parse("bold blue")));
            tree.add(Text::new("Cargo.toml", Style::parse("dim")));
            let sidebar = Layout::new(None, Some("sidebar".into()), Some(30), None, None, None)
                .with_renderable(
                    Panel::new(tree).with_title(Text::new("files", Style::parse("dim"))),
                );

            // Main top: a Markdown task checklist that checks off over time.
            let mut plan = String::from("## Plan\n\n");
            for (i, s) in steps.iter().enumerate() {
                if i < step_idx {
                    plan.push_str(&format!("- [x] {s}\n"));
                } else if i == step_idx {
                    plan.push_str(&format!("- [ ] **{s}**\n"));
                } else {
                    plan.push_str(&format!("- [ ] {s}\n"));
                }
            }
            let tasks = Layout::new(None, Some("tasks".into()), Some(9), None, None, None)
                .with_renderable(
                    Panel::new(Markdown::new(&plan))
                        .with_title(Text::new("plan", Style::parse("dim"))),
                );

            // Main bottom: a live code panel (Markdown fenced block) revealed line by line.
            let revealed =
                ((progress * code_lines.len() as f64).ceil() as usize).clamp(1, code_lines.len());
            let mut code = String::from("```rust\n");
            for line in &code_lines[..revealed] {
                code.push_str(line);
                code.push('\n');
            }
            code.push_str("```\n");
            let code_panel = Layout::new(None, Some("code".into()), None, None, Some(1), None)
                .with_renderable(
                    Panel::new(Markdown::new(&code))
                        .with_title(Text::new("color/mod.rs", Style::parse("dim"))),
                );

            let mut main = Layout::new(None, Some("main".into()), None, None, Some(1), None);
            main.split_column(vec![tasks, code_panel]);

            let mut body = Layout::new(None, Some("body".into()), None, None, Some(1), None);
            body.split_row(vec![sidebar, main]);

            // Footer: a live progress bar + status line.
            let bar = Bar::new(100.0, 0.0, pct as f64).with_width(44);
            let stats = Text::new(
                &format!(
                    "  {pct:>3}%   tests {passed}/3073   elapsed 0:{:02}",
                    frame / 4
                ),
                Style::parse("green"),
            );
            let footer = Layout::new(None, Some("footer".into()), Some(4), None, None, None)
                .with_renderable(
                    Panel::new(Group::new(vec![
                        into_renderable_arc(bar),
                        into_renderable_arc(stats),
                    ]))
                    .with_border_style(Style::parse(if pct >= 100 {
                        "bold green"
                    } else {
                        "green"
                    })),
                );

            let mut root = Layout::new(None, Some("root".into()), None, None, None, None);
            root.split_column(vec![header, body, footer]);

            live.set(root);
            live.refresh();
            thread::sleep(Duration::from_millis(110));
        }
        live.stop();
    }

    // =========================================================================
    // Farewell
    // =========================================================================
    console.line(1);
    let farewell =
        Gradient::rainbow("  Thank you for exploring gilt!  ").with_style(Style::parse("bold"));
    console.print(&farewell);
    console.rule(None);
}