charmed-harmonica 0.1.0

Physics-based animation tools: spring oscillator and projectile motion
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
# charmed_rust

<div align="center">
  <img src="charmed_rust_illustration.webp" alt="charmed_rust - Charm's TUI libraries ported to idiomatic Rust" width="600">
</div>

<div align="center">

[![CI](https://github.com/Dicklesworthstone/charmed_rust/actions/workflows/ci.yml/badge.svg)](https://github.com/Dicklesworthstone/charmed_rust/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Rust](https://img.shields.io/badge/rust-1.85%2B-orange.svg)](https://www.rust-lang.org/)
[![Edition](https://img.shields.io/badge/edition-2024-blue.svg)](https://doc.rust-lang.org/edition-guide/)
[![unsafe forbidden](https://img.shields.io/badge/unsafe-forbidden-success.svg)](https://github.com/rust-secure-code/safety-dance/)

**Build beautiful terminal UIs in Rust with Charm's elegance.**

[Quick Start](#quick-start) • [Components](#bubbles-components) • [Styling](#lipgloss-styling-examples) • [SSH Apps](#wish-ssh-framework) • [FAQ](#faq)

</div>

---

```toml
# Add to Cargo.toml
[dependencies]
bubbletea = { package = "charmed-bubbletea", version = "0.1.0" }
lipgloss = { package = "charmed-lipgloss", version = "0.1.0" }
bubbles = { package = "charmed-bubbles", version = "0.1.0" }
```

Crates are published under the `charmed-*` package names on crates.io, while the Rust
crate names remain `bubbletea`, `lipgloss`, `bubbles`, etc. Use `package = "charmed-…"`
to keep the idiomatic crate names in your code.

---

## TL;DR

**The Problem:** Building terminal UIs in Rust means fighting raw ANSI codes, wrestling with complex ncurses bindings, or cobbling together half-finished abstractions. Go developers get [Charm's](https://charm.sh) elegant ecosystem—beautiful styles, functional architecture, polished components—while Rust developers suffer.

**The Solution:** `charmed_rust` ports the entire Charm ecosystem to Rust. Same elegant APIs. Same beautiful output. Rust's type safety, zero-cost abstractions, and fearless concurrency.

### Why charmed_rust?

| Feature | What You Get |
|---------|--------------|
| **Elm Architecture** | Pure `update` and `view` functions. Testable. Predictable. No spaghetti. |
| **CSS-like Styling** | Borders, colors, padding, margins, alignment—`lipgloss` feels like CSS for terminals |
| **16 Components** | Text inputs, lists, tables, spinners, viewports, file pickers—all ready to use |
| **Spring Animations** | `harmonica` gives you physics-based motion: springs, projectiles, smooth easing |
| **Markdown in Terminal** | `glamour` renders beautiful Markdown with syntax highlighting and themes |
| **SSH App Framework** | `wish` serves TUI apps over SSH with middleware patterns—build BBS-style apps |
| **100% Safe Rust** | `#![forbid(unsafe_code)]` everywhere. No segfaults. No data races. Ever. |

---

## Quick Example

```rust
use bubbletea::{Program, Model, Message, Cmd, KeyMsg, KeyCode};
use lipgloss::Style;

struct Counter { count: i32 }

impl Model for Counter {
    fn update(&mut self, msg: Message) -> Cmd {
        if let Some(key) = msg.downcast_ref::<KeyMsg>() {
            match key.code {
                KeyCode::Char('+') => self.count += 1,
                KeyCode::Char('-') => self.count -= 1,
                KeyCode::Char('q') => return Cmd::quit(),
                _ => {}
            }
        }
        Cmd::none()
    }

    fn view(&self) -> String {
        Style::new()
            .bold(true)
            .foreground("#FF69B4")
            .padding(1, 4)
            .render(&format!("Count: {}", self.count))
    }
}

fn main() {
    Program::new(Counter { count: 0 }).run().unwrap();
}
```

**Output:**
```
╭────────────────╮
│  Count: 42     │
╰────────────────╯
```

Press `+` to increment, `-` to decrement, `q` to quit. That's it.

---

## Architecture

```
┌────────────────────────────────────────────────────────────┐
│                       Applications                         │
│  glow (Markdown Reader)    huh (Interactive Forms)         │
└────────────────────────────────────────────────────────────┘
                             │
         ┌───────────────────┼───────────────────┐
         ▼                   ▼                   ▼
┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐
│     bubbles      │ │     glamour      │ │      wish        │
│ (TUI Components) │ │   (Markdown)     │ │ (SSH Framework)  │
│  - textinput     │ │   - themes       │ │  - middleware    │
│  - list, table   │ │   - word wrap    │ │  - sessions      │
│  - viewport      │ │   - syntax       │ │  - PTY support   │
│  - spinner       │ │                  │ │                  │
│  - filepicker    │ │                  │ │                  │
└──────────────────┘ └──────────────────┘ └──────────────────┘
         │                   │                   │
         └───────────────────┼───────────────────┘
                             ▼
┌────────────────────────────────────────────────────────────┐
│                       bubbletea                            │
│           (Elm Architecture TUI Framework)                 │
│  Model trait • Message passing • Commands • Event loop     │
└────────────────────────────────────────────────────────────┘
                             │
         ┌───────────────────┼───────────────────┐
         ▼                   ▼                   ▼
┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐
│     lipgloss     │ │    harmonica     │ │   charmed_log    │
│  (Terminal CSS)  │ │   (Animations)   │ │    (Logging)     │
│   - colors       │ │ - spring physics │ │   - text/json    │
│   - borders      │ │ - projectile     │ │ - styled output  │
│   - layout       │ │ - frame timing   │ │   - levels       │
└──────────────────┘ └──────────────────┘ └──────────────────┘
                             │
                             ▼
                    ┌──────────────────┐
                    │    crossterm     │
                    │  (Terminal I/O)  │
                    └──────────────────┘
```

### Crate Reference

| Crate | Purpose | LOC |
|-------|---------|-----|
| **bubbletea** | Elm Architecture TUI framework | ~2,300 |
| **lipgloss** | Terminal styling (colors, borders, padding, alignment) | ~3,000 |
| **bubbles** | 16 pre-built TUI components | ~8,200 |
| **glamour** | Markdown rendering with themes | ~1,600 |
| **harmonica** | Spring physics animations, projectile motion | ~1,100 |
| **wish** | SSH application framework | ~1,700 |
| **huh** | Interactive forms and prompts | ~2,700 |
| **charmed_log** | Structured logging with styled output | ~1,000 |
| **glow** | Markdown reader CLI | ~160 |

### Crates.io Package Names

Crates are published with a `charmed-` prefix on crates.io to avoid name
collisions, while the Rust crate names remain the same:

| Rust Crate | crates.io Package |
|------------|-------------------|
| `bubbletea` | `charmed-bubbletea` |
| `bubbletea_macros` | `charmed-bubbletea-macros` |
| `lipgloss` | `charmed-lipgloss` |
| `harmonica` | `charmed-harmonica` |
| `glamour` | `charmed-glamour` |
| `bubbles` | `charmed-bubbles` |
| `huh` | `charmed-huh` |
| `wish` | `charmed-wish` |
| `charmed_log` | `charmed-log` |
| `glow` | `charmed-glow` |
| `demo_showcase` | `charmed-demo-showcase` |
| `charmed_wasm` | `charmed-wasm` |

---

## Design Philosophy

### 1. Functional Core, Imperative Shell

The Elm Architecture keeps your logic pure:

```rust
// Pure: state + message → new state + effects
fn update(&mut self, msg: Message) -> Cmd {
    match msg.downcast_ref::<KeyMsg>() {
        Some(key) if key.code == KeyCode::Enter => {
            self.submitted = true;
            Cmd::quit()  // Effect described, not executed
        }
        _ => Cmd::none()
    }
}

// Pure: state → string
fn view(&self) -> String {
    format!("Value: {}", self.value)  // No I/O, just render
}
```

Side effects happen through `Cmd` values. Your business logic stays testable.

### 2. Composition Over Inheritance

Components are Models. Nest them freely:

```rust
struct App {
    input: TextInput,     // Handles text entry
    suggestions: List,    // Shows autocomplete
    spinner: Spinner,     // Loading indicator
}

impl Model for App {
    fn update(&mut self, msg: Message) -> Cmd {
        // Delegate to children, compose results
        let cmd1 = self.input.update(msg.clone());
        let cmd2 = self.suggestions.update(msg);
        Cmd::batch(vec![cmd1, cmd2])
    }
}
```

### 3. CSS-like Styling

If you know CSS, you know `lipgloss`:

```rust
let card = Style::new()
    .border(Border::rounded())     // border-radius
    .border_foreground("#7D56F4")  // border-color
    .padding(1, 2)                 // padding: 1em 2em
    .margin(1)                     // margin: 1em
    .width(40)                     // width: 40ch
    .align(Position::Center);      // text-align: center
```

### 4. Zero Unsafe Code

Every crate: `#![forbid(unsafe_code)]`. Memory safety isn't optional.

### 5. Go Conformance

Same inputs → same outputs as Go Charm. Migration is seamless. Conformance tests verify compatibility.

---

## Comparison

| Feature | charmed_rust | Go Charm | ratatui | ncurses-rs |
|---------|--------------|----------|---------|------------|
| **Architecture** | Elm (functional) | Elm (functional) | Immediate mode | Imperative |
| **Styling** | CSS-like | CSS-like | Widget props | Raw attrs |
| **Type Safety** | Compile-time | Runtime | Compile-time | Minimal |
| **Async** | Native tokio | Goroutines | Manual | None |
| **Memory Safety** | Guaranteed | GC | Depends | Unsafe |
| **Components** | 16 included | 16 included | 20+ | Manual |
| **SSH Framework** | ✅ | ✅ | ❌ | ❌ |
| **Markdown** | ✅ | ✅ | ❌ | ❌ |
| **Learning Curve** | Moderate | Moderate | Steep | Steep |

**Choose charmed_rust when:**
- You want Go Charm's elegance with Rust's performance and safety
- You're porting a Go Charm app to Rust
- You prefer functional/Elm-style over immediate mode
- You need SSH-served TUIs

**Consider alternatives when:**
- You need maximum widget variety (ratatui has more)
- You prefer immediate-mode rendering
- You need ncurses compatibility for legacy systems

---

## Installation

### From crates.io (Recommended)

```toml
# Cargo.toml
[dependencies]
bubbletea = { package = "charmed-bubbletea", version = "0.1.0" }
lipgloss = { package = "charmed-lipgloss", version = "0.1.0" }
bubbles = { package = "charmed-bubbles", version = "0.1.0" }
glamour = { package = "charmed-glamour", version = "0.1.0" }
harmonica = { package = "charmed-harmonica", version = "0.1.0" }
wish = { package = "charmed-wish", version = "0.1.0" }
huh = { package = "charmed-huh", version = "0.1.0" }
charmed_log = { package = "charmed-log", version = "0.1.0" }
```

### From Git (Bleeding Edge)

```toml
# Cargo.toml
[dependencies]
bubbletea = { package = "charmed-bubbletea", git = "https://github.com/Dicklesworthstone/charmed_rust" }
lipgloss = { package = "charmed-lipgloss", git = "https://github.com/Dicklesworthstone/charmed_rust" }
bubbles = { package = "charmed-bubbles", git = "https://github.com/Dicklesworthstone/charmed_rust" }
glamour = { package = "charmed-glamour", git = "https://github.com/Dicklesworthstone/charmed_rust" }
harmonica = { package = "charmed-harmonica", git = "https://github.com/Dicklesworthstone/charmed_rust" }
wish = { package = "charmed-wish", git = "https://github.com/Dicklesworthstone/charmed_rust" }
huh = { package = "charmed-huh", git = "https://github.com/Dicklesworthstone/charmed_rust" }
charmed_log = { package = "charmed-log", git = "https://github.com/Dicklesworthstone/charmed_rust" }
```

### With Async Support

```toml
bubbletea = { package = "charmed-bubbletea", version = "0.1.0", features = ["async"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros"] }
```

### From Source

```bash
git clone https://github.com/Dicklesworthstone/charmed_rust.git
cd charmed_rust
cargo build --release

# Run the Markdown reader
cargo run -p charmed-glow -- README.md
```

### Requirements

- **Rust 1.85+** (nightly required for Edition 2024)
- **Platforms:** Linux, macOS, Windows

---

## Quick Start

### 1. Create Project

```bash
cargo new my-tui && cd my-tui
```

### 2. Add Dependencies

```toml
[dependencies]
bubbletea = { package = "charmed-bubbletea", version = "0.1.0" }
lipgloss = { package = "charmed-lipgloss", version = "0.1.0" }
```

### 3. Implement Model

```rust
use bubbletea::{Program, Model, Message, Cmd, KeyMsg, KeyCode};
use lipgloss::Style;

#[derive(Default)]
struct App {
    choice: usize,
    items: Vec<&'static str>,
}

impl Model for App {
    fn init(&mut self) -> Cmd {
        self.items = vec!["Start Game", "Options", "Quit"];
        Cmd::none()
    }

    fn update(&mut self, msg: Message) -> Cmd {
        if let Some(key) = msg.downcast_ref::<KeyMsg>() {
            match key.code {
                KeyCode::Up | KeyCode::Char('k') => {
                    self.choice = self.choice.saturating_sub(1);
                }
                KeyCode::Down | KeyCode::Char('j') => {
                    if self.choice < self.items.len() - 1 {
                        self.choice += 1;
                    }
                }
                KeyCode::Enter | KeyCode::Char('q') => return Cmd::quit(),
                _ => {}
            }
        }
        Cmd::none()
    }

    fn view(&self) -> String {
        let title = Style::new().bold(true).render("Main Menu\n\n");
        let items: String = self.items.iter().enumerate()
            .map(|(i, item)| {
                if i == self.choice {
                    Style::new().foreground("#FF69B4").render(&format!("> {item}\n"))
                } else {
                    format!("  {item}\n")
                }
            })
            .collect();
        format!("{title}{items}\n↑/↓ to move • enter to select • q to quit")
    }
}

fn main() {
    Program::new(App::default()).run().unwrap();
}
```

### 4. Run

```bash
cargo run
```

---

## lipgloss Styling Examples

### Text Styling

```rust
use lipgloss::{Style, Color};

// Bold pink text
let heading = Style::new().bold(true).foreground("#FF69B4");
println!("{}", heading.render("Hello, Terminal!"));

// Underlined with background
let highlight = Style::new()
    .underline(true)
    .background("#333333")
    .foreground("#FFFFFF");
```

### Boxes and Borders

```rust
use lipgloss::{Style, Border};

let card = Style::new()
    .border(Border::rounded())
    .border_foreground("#7D56F4")
    .padding(1, 4)
    .margin(1);

println!("{}", card.render("Content in a card"));
```

**Output:**
```
 ╭────────────────────╮
 │                    │
 │  Content in a card │
 │                    │
 ╰────────────────────╯
```

### Adaptive Colors

```rust
// Automatically picks color based on terminal background
let adaptive = Style::new()
    .foreground(Color::adaptive("#000000", "#FFFFFF"));  // dark bg, light bg
```

### Layout

```rust
use lipgloss::{Style, Position, join_horizontal, join_vertical, place};

// Side-by-side columns
let left = Style::new().width(30).render("Left Panel");
let right = Style::new().width(30).render("Right Panel");
let row = join_horizontal(Position::Top, &[&left, &right]);

// Stacked sections
let header = Style::new().bold(true).render("Header");
let body = "Body content";
let layout = join_vertical(Position::Left, &[&header, body]);

// Center content in a box
let centered = place(80, 24, Position::Center, Position::Center, "Centered!");
```

### Theming

lipgloss includes a theming system for consistent colors across your application:

```rust
use lipgloss::{ThemePreset, ThemedStyle, ColorSlot, ThemeContext};
use std::sync::Arc;

// Use a built-in preset
let ctx = Arc::new(ThemeContext::from_preset(ThemePreset::Dracula));

// Create styles that use semantic color slots
let title = ThemedStyle::new(ctx.clone())
    .foreground(ColorSlot::Primary)
    .bold();

let error = ThemedStyle::new(ctx.clone())
    .foreground(ColorSlot::Error);

println!("{}", title.render("Welcome!"));
println!("{}", error.render("Something went wrong"));

// Switch themes at runtime - styles update automatically
ctx.set_preset(ThemePreset::Nord);
```

**Built-in Themes:**
- `Dark` / `Light` - Default themes
- `Dracula` - Popular purple-tinted dark theme
- `Nord` - Arctic-inspired palette
- `Catppuccin` - Pastel themes (Latte, Frappe, Macchiato, Mocha)

**Semantic Color Slots:**

| Slot | Purpose |
|------|---------|
| `Background` | Main background |
| `Foreground` | Default text |
| `Primary` | Buttons, links, headings |
| `Error` | Error messages |
| `Success` | Confirmations |
| `Warning` | Alerts |
| `Muted` | Disabled/placeholder text |
| `Border` | UI borders |

Load custom themes from files:

```rust
use lipgloss::Theme;

// From TOML, JSON, or YAML
let theme = Theme::from_file("~/.config/myapp/theme.toml")?;

// Validate accessibility
if !theme.check_contrast_aa(ColorSlot::Foreground, ColorSlot::Background) {
    eprintln!("Warning: Poor contrast ratio");
}
```

See [Theming Tutorial](docs/theming-tutorial.md) for complete documentation.

---

## bubbles Components

### TextInput

```rust
use bubbles::textinput::TextInput;

let mut input = TextInput::new();
input.set_placeholder("Enter your name...");
input.set_char_limit(50);
input.set_width(40);
input.focus();

// In update():
input.update(msg);

// In view():
input.view()
```

### List with Filtering

```rust
use bubbles::list::{List, Item};

let items = vec![
    Item::new("Rust", "Systems programming language"),
    Item::new("Go", "Simple, reliable, efficient"),
    Item::new("Python", "Readable and versatile"),
];

let mut list = List::new(items, 10, 40);
list.set_show_filter(true);  // Enable fuzzy search
```

### Table

```rust
use bubbles::table::{Table, Column};

let table = Table::new()
    .columns(vec![
        Column::new("Name", 20),
        Column::new("Status", 10),
        Column::new("CPU", 8),
    ])
    .rows(vec![
        vec!["web-server", "Running", "12%"],
        vec!["database", "Running", "45%"],
        vec!["cache", "Stopped", "0%"],
    ])
    .focused(true);
```

### Spinner

```rust
use bubbles::spinner::{Spinner, SpinnerType};
use lipgloss::Style;

let spinner = Spinner::new()
    .spinner_type(SpinnerType::Dots)
    .style(Style::new().foreground("#FF69B4"));

// Tick it in update() with a timer message
```

### Progress Bar

```rust
use bubbles::progress::Progress;

let progress = Progress::new()
    .width(40)
    .show_percentage(true);

progress.view_as(0.75)  // 75% complete
```

### Viewport (Scrollable)

```rust
use bubbles::viewport::Viewport;

let mut viewport = Viewport::new(80, 24);
viewport.set_content(long_markdown_text);

// Scroll with:
viewport.line_down(1);
viewport.line_up(1);
viewport.half_page_down();
viewport.goto_top();
```

### File Picker

```rust
use bubbles::filepicker::FilePicker;

let mut picker = FilePicker::new();
picker.set_current_directory("/home/user");
picker.set_show_hidden(false);
picker.set_allowed_types(vec!["rs", "toml", "md"]);
```

### Stopwatch & Timer

```rust
use bubbles::stopwatch::Stopwatch;
use bubbles::timer::Timer;
use std::time::Duration;

let stopwatch = Stopwatch::new();  // Counts up
let timer = Timer::new(Duration::from_secs(300));  // 5-minute countdown
```

### Paginator

```rust
use bubbles::paginator::Paginator;

let mut paginator = Paginator::new();
paginator.set_total_pages(10);
paginator.set_per_page(25);
```

---

## glamour Markdown Rendering

```rust
use glamour::{render, Theme};

let markdown = r#"
# Hello World

This is **bold** and *italic* text.

```rust
fn main() {
    println!("Code blocks work too!");
}
```

- Lists
- Are
- Supported
"#;

// Render with default theme
let output = render(markdown)?;
println!("{}", output);

// Or with a specific theme
let themed = glamour::render_with_theme(markdown, Theme::dark())?;
```

### Available Themes

- `Theme::dark()` - For dark terminal backgrounds
- `Theme::light()` - For light terminal backgrounds
- `Theme::dracula()` - Dracula color scheme
- `Theme::ascii()` - Plain ASCII, no colors
- `Theme::notty()` - No formatting (for piping)

---

## wish SSH Framework

Build SSH-accessible TUI applications:

```rust
use wish::{Server, Session, Handler};
use bubbletea::{Program, Model};

struct MyApp { /* ... */ }
impl Model for MyApp { /* ... */ }

struct MyHandler;

impl Handler for MyHandler {
    fn handle(&self, session: Session) {
        // Each SSH connection gets its own TUI instance
        let app = MyApp::new();
        Program::new(app)
            .with_input(session.stdin())
            .with_output(session.stdout())
            .run()
            .unwrap();
    }
}

fn main() {
    Server::new()
        .address("0.0.0.0:2222")
        .host_key_path("./host_key")
        .handler(MyHandler)
        .run()
        .unwrap();
}
```

Users connect with: `ssh -p 2222 localhost`

---

## Async Support

Enable tokio-based async for non-blocking I/O:

```toml
[dependencies]
bubbletea = { package = "charmed-bubbletea", version = "0.1.0", features = ["async"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros"] }
```

```rust
use bubbletea::{Program, Model, Message, AsyncCmd, tick_async};
use std::time::Duration;

struct App {
    data: Option<String>,
    loading: bool,
}

// Async command for HTTP fetch
fn fetch_data() -> AsyncCmd {
    AsyncCmd::new(|| async {
        let resp = reqwest::get("https://api.example.com/data")
            .await.unwrap()
            .text()
            .await.unwrap();
        Message::new(DataLoaded(resp))
    })
}

// Async timer (non-blocking)
fn tick() -> AsyncCmd {
    tick_async(Duration::from_millis(100), |_| Message::new(Tick))
}

impl Model for App {
    fn init(&mut self) -> Cmd {
        self.loading = true;
        fetch_data().into()  // Start fetch on init
    }

    fn update(&mut self, msg: Message) -> Cmd {
        if let Some(DataLoaded(data)) = msg.downcast_ref() {
            self.data = Some(data.clone());
            self.loading = false;
        }
        Cmd::none()
    }
}

#[tokio::main]
async fn main() {
    Program::new(App::default()).run_async().await.unwrap();
}
```

---

## Demo Showcase

The flagship demo shows off all functionality in charmed_rust:

```bash
cargo run -p charmed-demo-showcase
```

### Options

| Flag | Description |
|------|-------------|
| `--theme <name>` | Color theme: `dark`, `light`, `dracula`, `nord`, `catppuccin-*` |
| `--seed <n>` | Seed for reproducible randomness |
| `--no-alt-screen` | Stay in main terminal buffer |
| `--no-mouse` | Disable mouse support |
| `--help` | Show all available options |

### Examples

```bash
# Run with Nord theme
cargo run -p charmed-demo-showcase -- --theme nord

# Run with Dracula theme
cargo run -p charmed-demo-showcase -- --theme dracula

# Reproducible demo state
cargo run -p charmed-demo-showcase -- --seed 42
```

### What It Demonstrates

- **Multi-page navigation** - Dashboard, Services, Jobs, Logs, Docs, Files, Wizard, Settings
- **Theme switching** - Switch themes at runtime with keyboard shortcuts
- **All bubbles components** - Lists, tables, spinners, progress bars, text inputs, viewports
- **Markdown rendering** - glamour with syntax highlighting
- **Form interactions** - Interactive forms via huh
- **Spring animations** - Smooth physics-based animations via harmonica
- **File browser** - Navigate the filesystem
- **Full keyboard & mouse support**

---

## glow CLI Reference

`glow` is a terminal Markdown reader built on `glamour`:

```bash
# Read a file
cargo run -p charmed-glow -- README.md

# Read from stdin
cat README.md | cargo run -p charmed-glow

# With specific theme
cargo run -p charmed-glow -- --theme dracula README.md

# Pager mode (for long documents)
cargo run -p charmed-glow -- --pager README.md
```

### Options

| Flag | Description |
|------|-------------|
| `--theme <name>` | Color theme: `dark`, `light`, `dracula`, `ascii` |
| `--pager` | Enable scrollable pager mode |
| `--width <n>` | Set render width (default: terminal width) |
| `--style <path>` | Load custom style JSON |

---

## Configuration

### Environment Variables

| Variable | Description | Default |
|----------|-------------|---------|
| `COLORTERM` | Color support (`truecolor`, `256`) | auto-detect |
| `NO_COLOR` | Disable all colors if set | unset |
| `GLAMOUR_STYLE` | Default glamour theme | `dark` |
| `TERM` | Terminal type | auto-detect |

### Programmatic Configuration

```rust
use lipgloss::renderer::{Renderer, ColorProfile};

// Force 256-color mode
let renderer = Renderer::new()
    .color_profile(ColorProfile::ANSI256);

// Disable colors entirely
let renderer = Renderer::new()
    .color_profile(ColorProfile::Ascii);
```

---

## Troubleshooting

### "failed to select a version for `bubbletea`"

Use the published package name and alias it to the `bubbletea` crate:

```toml
# ❌ Wrong
bubbletea = "0.1"

# ✅ Correct
bubbletea = { package = "charmed-bubbletea", version = "0.1.0" }
```

### Terminal not restoring after crash

`bubbletea` uses alternate screen mode. Reset with:

```bash
reset
# or
stty sane
```

### Colors not showing

Check true color support:

```bash
echo $COLORTERM  # Should be "truecolor" or "24bit"
```

Fallback to 256 colors:

```rust
let color = Color::ansi256(205);  // Pink in 256-color palette
```

### "cannot find trait `Model`"

Add the import:

```rust
use bubbletea::Model;
```

### Windows: garbled output

Use Windows Terminal, not cmd.exe. Or enable virtual terminal:

```rust
// crossterm handles this, but needs a modern terminal
```

### Viewport not scrolling

Ensure you're forwarding key messages:

```rust
fn update(&mut self, msg: Message) -> Cmd {
    self.viewport.update(msg);  // Don't forget this!
    Cmd::none()
}
```

### SSH connections rejected

Check host key permissions:

```bash
chmod 600 ./host_key
chmod 644 ./host_key.pub
```

---

## Limitations

### Current State

| Capability | Status | Notes |
|------------|--------|-------|
| **crates.io** | ✅ Published | Install via `charmed-*` packages |
| **Nightly Rust** | Required | Edition 2024 |
| **SSH (wish)** | ⚠️ Beta | Framework ready, deps maturing |
| **Mouse drag** | ⚠️ Limited | Click/scroll work, selection needs terminal support |
| **Complex Unicode** | ⚠️ Basic | `unicode-width` handles most cases |
| **Windows SSH** | ⚠️ Untested | Linux/macOS verified |

### Not Planned

- **Built-in syntax highlighting**: `glamour` detects code blocks but delegates highlighting to `syntect`
- **GUI rendering**: Terminal only—use `egui` or `iced` for GUI
- **ncurses compatibility**: Clean break from legacy

---

## FAQ

### Why "charmed_rust"?

Charm + Rust = charmed_rust. The TUIs are pretty charming too.

### Can I use lipgloss without bubbletea?

Yes. It's completely standalone:

```rust
use lipgloss::Style;
println!("{}", Style::new().bold(true).render("No TUI needed"));
```

### Is this API-compatible with Go Charm?

Semantically yes. Method names follow Rust conventions (`set_width` vs `Width`), but the patterns are identical.

### How do I test TUI apps?

Use headless mode:

```rust
let model = Program::new(app).without_renderer().run()?;
assert_eq!(model.some_state, expected);
```

Or test update/view directly:

```rust
let mut app = MyApp::default();
app.update(Message::new(KeyMsg { code: KeyCode::Enter, .. }));
assert!(app.view().contains("Expected text"));
```

### Does it work in Docker/CI?

Yes. Use `without_renderer()` or set `TERM=dumb` for non-interactive environments.

### How do I handle window resize?

Subscribe to resize events:

```rust
fn update(&mut self, msg: Message) -> Cmd {
    if let Some(size) = msg.downcast_ref::<WindowSizeMsg>() {
        self.width = size.width;
        self.height = size.height;
    }
    Cmd::none()
}
```

### Can I use custom fonts/icons?

The terminal controls fonts. Use Nerd Fonts for icons:

```rust
let icon = "";  // Nerd Font: nf-fa-folder
```

### How do I debug render issues?

Log the view output:

```rust
fn view(&self) -> String {
    let output = self.render_internal();
    eprintln!("VIEW: {:?}", output);  // Goes to stderr, not screen
    output
}
```

Or use `charmed_log` to file:

```rust
charmed_log::init_file("debug.log")?;
log::debug!("State: {:?}", self);
```

---

## Conformance Testing

Verify behavior matches Go Charm:

```bash
# All conformance tests
cargo test -p charmed_conformance

# Specific crates
cargo test -p charmed_conformance test_harmonica
cargo test -p charmed_conformance test_lipgloss
cargo test -p charmed_conformance test_bubbletea
```

Fixtures captured from Go reference implementations live in `tests/conformance/go_reference/`.

---

## Performance

Benchmarks run on Apple M2:

| Operation | Time |
|-----------|------|
| Style creation | ~50ns |
| Simple render | ~200ns |
| Complex layout (10 boxes) | ~2μs |
| Markdown page render | ~500μs |
| Message dispatch | ~100ns |

Memory: Typical TUI app uses 2-5MB RSS.

Run benchmarks:

```bash
cargo bench -p charmed-bubbletea
cargo bench -p charmed-lipgloss
```

---

## About Contributions

Please don't take this the wrong way, but I do not accept outside contributions for any of my projects. I simply don't have the mental bandwidth to review anything, and it's my name on the thing, so I'm responsible for any problems it causes; thus, the risk-reward is highly asymmetric from my perspective. I'd also have to worry about other "stakeholders," which seems unwise for tools I mostly make for myself for free. Feel free to submit issues, and even PRs if you want to illustrate a proposed fix, but know I won't merge them directly. Instead, I'll have Claude or Codex review submissions via `gh` and independently decide whether and how to address them. Bug reports in particular are welcome. Sorry if this offends, but I want to avoid wasted time and hurt feelings. I understand this isn't in sync with the prevailing open-source ethos that seeks community contributions, but it's the only way I can move at this velocity and keep my sanity.

---

## License

MIT License - see [LICENSE](LICENSE) for details.

---

<div align="center">

**Built with Rust. Inspired by [Charm](https://charm.sh).**

</div>