rusty-rich 0.3.0

Rich text and beautiful formatting in the terminal — a Rust port of Python's Rich library
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
# Prompts

Interactive prompts let you ask the user for input with styled prompt text, choice
validation, and password masking. They are inspired by the Python Rich `rich.prompt`
module.

## Overview

rusty-rich provides five prompt types:

| Type         | Return value | Description                           |
|--------------|--------------|---------------------------------------|
| `Prompt`     | `String`     | Free-form string input                |
| `IntPrompt`  | `i64`        | Integer input (loops until valid)     |
| `FloatPrompt`| `f64`        | Floating-point input (loops until valid) |
| `Confirm`    | `bool`       | Yes/no answer with a default          |
| `Select<T>`  | `T`          | Numbered selection from a list        |

All prompts share a common base configuration via `PromptBase` and support:
- Styled prompt text using theme styles (`prompt`, `prompt.choices`, `prompt.default`)
- Optional `Console` for output (falls back to raw stdout)
- Password mode (characters masked with `*`)
- Choice validation with optional case sensitivity
- Display of default values and choices

---

## PromptBase

`PromptBase` holds the common configuration for every prompt type. You rarely
use it directly -- each concrete prompt wraps its own `PromptBase` instance and
exposes builder methods that delegate to it.

### Fields

```rust
pub struct PromptBase {
    pub prompt: String,
    pub console: Option<Console>,
    pub password: bool,
    pub choices: Option<Vec<String>>,
    pub case_sensitive: bool,
    pub show_default: bool,
    pub show_choices: bool,
}
```

### Builder Methods

All builder methods consume and return `self`, enabling a fluent chain:

| Method | Signature | Description |
|--------|-----------|-------------|
| `new(prompt)` | `(impl Into<String>) -> Self` | Create with the given prompt text |
| `console(console)` | `(Console) -> Self` | Attach a `Console` for styled output |
| `password(yes)` | `(bool) -> Self` | Enable or disable password masking |
| `choices(choices)` | `(Vec<String>) -> Self` | Set valid response choices |
| `case_sensitive(yes)` | `(bool) -> Self` | Require exact case matching for choices |
| `show_default(yes)` | `(bool) -> Self` | Show or hide the default value in the prompt |
| `show_choices(yes)` | `(bool) -> Self` | Show or hide the choices list in the prompt |

### Helper Methods

- **`render_default(&self, default: &str) -> String`** -- Formats the default
  value for display (e.g. `" (default: Alice)"`). Returns an empty string if
  `show_default` is `false` or the default is empty.

- **`make_prompt(&self) -> String`** -- Builds the full prompt string including
  choices and trailing `": "`. Example output:
  `"Enter choice [a/b/c]: "` (styled with theme styles).

- **`check_choice(&self, value: &str) -> bool`** -- Validates `value` against
  the configured choices. When `choices` is `None`, every value is accepted.
  When `case_sensitive` is `false` (the default), comparison is
  case-insensitive.

---

## Prompt (string input)

`Prompt` reads a free-form string from the user.

```rust
pub struct Prompt {
    base: PromptBase,
}
```

### Builder Methods

`Prompt` exposes all `PromptBase` builder methods directly:
`new`, `console`, `password`, `choices`, `case_sensitive`, `show_default`,
`show_choices`.

### Methods

| Method | Signature | Description |
|--------|-----------|-------------|
| `render()` | `() -> String` | Returns the styled prompt string |
| `ask()` | `() -> Result<String, PromptError>` | Show prompt, read input, validate, return trimmed string |
| `ask_with(prompt)` | `(impl Into<String>) -> Result<String, PromptError>` | Convenience: `Prompt::new(prompt).ask()` |

### Behaviour

1. The prompt string (styled via `make_prompt()`) is written to stdout or the
   attached `Console`.
2. A line is read from stdin. In normal mode, this uses `io::stdin().lock()`.
3. If `password` is `true`, input is read character-by-character in raw mode
   with `*` masking.
4. If choices are configured, the response is validated. On mismatch,
   `Err(PromptError::InvalidResponse(...))` is returned.
5. The trimmed response is returned as `String`.

---

## IntPrompt (integer input)

`IntPrompt` reads an integer (`i64`) from the user. Unlike `Prompt`, it
**loops** on invalid input, printing an error message and re-prompting until a
valid integer (or choice match) is entered.

```rust
pub struct IntPrompt {
    base: PromptBase,
}
```

### Builder Methods

`new`, `console`, `password`, `choices`, `case_sensitive`.

Note: `IntPrompt` does not expose `show_default` or `show_choices` builders.

### Methods

| Method | Signature | Description |
|--------|-----------|-------------|
| `ask()` | `() -> Result<i64, PromptError>` | Show prompt, loop until valid integer |
| `ask_with(prompt)` | `(impl Into<String>) -> Result<i64, PromptError>` | Convenience: `IntPrompt::new(prompt).ask()` |

### Behaviour

1. Displays the prompt and reads input.
2. Empty lines are silently retried.
3. If choices are configured, the response is validated first; invalid choices
   print `"Invalid choice: '...'. Please try again.\n"` and loop.
4. Parses the input as `i64`. On parse failure, prints `"Please enter a valid integer.\n"`
   and loops.
5. Returns `Ok(i64)` on success, or `Err(PromptError::Cancelled)` on EOF/Ctrl+C.

---

## FloatPrompt (float input)

`FloatPrompt` reads a floating-point number (`f64`) from the user. Like
`IntPrompt`, it loops on invalid input.

```rust
pub struct FloatPrompt {
    base: PromptBase,
}
```

### Builder Methods

`new`, `console`, `password`, `choices`, `case_sensitive`.

Note: `FloatPrompt` does not expose `show_default` or `show_choices` builders.

### Methods

| Method | Signature | Description |
|--------|-----------|-------------|
| `ask()` | `() -> Result<f64, PromptError>` | Show prompt, loop until valid float |
| `ask_with(prompt)` | `(impl Into<String>) -> Result<f64, PromptError>` | Convenience: `FloatPrompt::new(prompt).ask()` |

### Behaviour

Same loop semantics as `IntPrompt` but parses as `f64` and prints
`"Please enter a valid number.\n"` on parse failure.

---

## Confirm (yes/no)

`Confirm` asks for a yes/no answer and returns `bool`. It carries a `default`
value used when the user presses Enter without typing.

```rust
pub struct Confirm {
    base: PromptBase,
    pub default: bool,
}
```

### Builder Methods

`new(prompt, default)`, `console`.

`Confirm` does not expose general `PromptBase` builders (`password`, `choices`,
`case_sensitive`, `show_default`, `show_choices`).

### Methods

| Method | Signature | Description |
|--------|-----------|-------------|
| `ask()` | `() -> Result<bool, PromptError>` | Show `[y/N]` or `[Y/n]` prompt, return bool |
| `ask_with(prompt, default)` | `(impl Into<String>, bool) -> Result<bool, PromptError>` | Convenience: `Confirm::new(prompt, default).ask()` |

### Accepted Inputs

| Input | Interpretation |
|-------|---------------|
| (empty) | Returns the configured default |
| `y`, `yes`, `true`, `1` | `true` (affirmative) |
| `n`, `no`, `false`, `0` | `false` (negative) |

On unrecognised input, `"Please answer y or n.\n"` is printed and the prompt
repeats.

### Prompt Display

The confirmation prompt shows `[Y/n]` when the default is `true` and `[y/N]`
when the default is `false` (the capital letter indicates the default).

---

## Select\<T\> (numbered menu)

`Select<T>` presents a numbered list of choices and returns the value
associated with the chosen entry.

```rust
pub struct Select<T> {
    base: PromptBase,
    choices: Vec<(String, T)>,
}
```

### Builder Methods

`new(prompt)`, `console`, `choice(label, value)`.

The `choice` method adds a `(label, T)` pair to the internal list. Each label
is displayed as a numbered item.

### Methods

| Method | Requirements | Description |
|--------|-------------|-------------|
| `render()` | `T: Display` | Render the numbered list + prompt as a `String` |
| `ask()` | `T: Display + Clone` | Show menu, read numbered choice, return the selected value |

### Behaviour

1. If no choices have been added, `ask()` returns
   `Err(PromptError::InvalidResponse("no choices available"))`.
2. The prompt is rendered as a multi-line string:
   ```text
   Pick a color:
     1) Red
     2) Green
     3) Blue
   Enter number [1-3]:
   ```
3. Input is parsed as a `usize`. Numbers outside the valid range (or
   non-numeric input) print `"Please enter a number between 1 and N.\n"` and
   loop.
4. On valid input, the `T` value at `choices[n - 1]` is cloned and returned.

---

## Password Masking

When `password(true)` is set on `Prompt`, `IntPrompt`, or `FloatPrompt`, input
is read with echoing disabled via crossterm raw mode. Each typed character
is echoed as `*`. Backspace erases the last character and removes one `*` from
the display. Escape or Delete cancels the prompt (`PromptError::Cancelled`).
Enter accepts the input and writes a newline.

The password reader is implemented directly in `read_password()` and does not
depend on the `rpassword` crate.

Note: `Confirm` and `Select<T>` do not support password mode.

---

## Choice Validation

When `choices` is set on `Prompt`, `IntPrompt`, or `FloatPrompt`, the user's
response is validated against the list.

- With `case_sensitive(false)` (the default), comparison is case-insensitive:
  `"YES"` matches `"yes"`.
- With `case_sensitive(true)`, comparison is exact, including case.
- When no choices are configured, every value is accepted.

For `Prompt`, an invalid choice returns `Err(PromptError::InvalidResponse(...))`.
For `IntPrompt` and `FloatPrompt`, an invalid choice prints an error message and
re-prompts.

---

## PromptError

Errors during prompting are represented by the `PromptError` enum.

```rust
pub enum PromptError {
    InvalidResponse(String),   // User input failed validation
    IOError(io::Error),        // Underlying I/O failure
    Cancelled,                 // EOF, Ctrl+C, or Ctrl+D
}
```

`PromptError` implements `std::error::Error` (with `source()` returning the
inner `io::Error` for the `IOError` variant), `Display`, `From<io::Error>`,
and `Debug`.

---

## Error Handling Patterns

Handle errors at the prompt site to distinguish cancellation from validation
failures:

```rust
use rusty_rich::{Prompt, PromptError};

fn get_username() -> Option<String> {
    match Prompt::ask_with("Enter username") {
        Ok(name) => Some(name),
        Err(PromptError::Cancelled) => {
            eprintln!("Input cancelled.");
            None
        }
        Err(PromptError::InvalidResponse(msg)) => {
            eprintln!("Invalid: {msg}");
            None
        }
        Err(PromptError::IOError(e)) => {
            eprintln!("I/O error: {e}");
            None
        }
    }
}
```

---

## Examples

### Login form (string prompt with password)

```rust
use rusty_rich::{Prompt, Confirm};

fn login() -> Result<(), Box<dyn std::error::Error>> {
    let username = Prompt::new("Username").ask()?;
    let password = Prompt::new("Password").password(true).ask()?;

    println!("Logged in as: {username}");

    if Confirm::ask_with("Save credentials?", false)? {
        println!("Credentials saved.");
    }

    Ok(())
}
```

This example demonstrates:
- `Prompt` for free-form string input, chained with `.password(true)` for
  masked input.
- `Confirm` with a default of `false` (shown as `[y/N]`).

### Numbered menu selection

```rust
use rusty_rich::Select;

#[derive(Debug, Clone)]
enum Action {
    View,
    Edit,
    Delete,
    Quit,
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let action = Select::new("Choose an action")
        .choice("View entry", Action::View)
        .choice("Edit entry", Action::Edit)
        .choice("Delete entry", Action::Delete)
        .choice("Quit", Action::Quit)
        .ask()?;

    println!("Selected: {:?}", action);
    Ok(())
}
```

This example shows `Select<T>` with a custom `enum` as the value type. Each
`choice()` call adds a labelled entry; the selected entry's value is returned
by `ask()`.

### Confirmation prompt

```rust
use rusty_rich::Confirm;

fn destructive_action() -> Result<(), Box<dyn std::error::Error>> {
    if Confirm::ask_with("Delete all data?", false)? {
        println!("Deleting all data...");
        // ...
    } else {
        println!("Cancelled.");
    }
    Ok(())
}
```

### Integer and float prompts with choices

```rust
use rusty_rich::{IntPrompt, FloatPrompt};

fn get_rating() -> Result<i64, Box<dyn std::error::Error>> {
    let rating = IntPrompt::new("Rating (1-5)")
        .choices(vec!["1".into(), "2".into(), "3".into(), "4".into(), "5".into()])
        .case_sensitive(true)
        .ask()?;
    Ok(rating)
}

fn get_temperature() -> Result<f64, Box<dyn std::error::Error>> {
    let temp = FloatPrompt::ask_with("Enter temperature in Celsius")?;
    Ok(temp)
}
```

### Full prompt with styled console

```rust
use rusty_rich::{Console, Prompt};

fn styled_prompt() -> Result<(), Box<dyn std::error::Error>> {
    let console = Console::new();
    let answer = Prompt::new("Enter your name")
        .console(console)
        .show_default(false)
        .ask()?;
    println!("Hello, {answer}!");
    Ok(())
}
```

---

## Builder Pattern Summary

All prompt types follow the same fluent builder pattern:

```rust
let result = Type::new("prompt text")
    .console(some_console)   // optional
    .password(true)          // optional
    .choices(vec![...])      // optional
    .case_sensitive(true)    // optional
    .show_default(false)     // optional (Prompt only)
    .show_choices(false)     // optional (Prompt only)
    .ask()?;                 // or .ask_with(...) for convenience
```

| Builder | Prompt | IntPrompt | FloatPrompt | Confirm | Select\<T\> |
|---------|--------|-----------|-------------|---------|-------------|
| `console` | Yes | Yes | Yes | Yes | Yes |
| `password` | Yes | Yes | Yes | No | No |
| `choices` | Yes | Yes | Yes | No | Via `choice()` |
| `case_sensitive` | Yes | Yes | Yes | No | No |
| `show_default` | Yes | No | No | No | No |
| `show_choices` | Yes | No | No | No | No |