standout-render 12.0.0

Styled terminal rendering with templates, themes, and adaptive color support
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
# The Styling System

`standout-render` uses a theme-based styling system where named styles are applied to content through bracket notation tags. Instead of embedding ANSI codes in your templates, you define semantic style names (`error`, `title`, `muted`) and let the theme decide the visual representation.

This separation provides several benefits:

- **Readability**: Templates use meaningful names, not escape codes
- **Maintainability**: Change colors in one place, update everywhere
- **Adaptability**: Themes can respond to light/dark mode automatically
- **Consistency**: Enforce visual hierarchy across your application

---

## Themes

A `Theme` is a named collection of styles. Each style maps a name (like `title` or `error`) to visual attributes (bold cyan, dim red, etc.).

### CSS Themes

Define styles in standard CSS syntax — a subset of CSS Level 3 tailored for terminals:

```css
/* theme.css */
.title {
    color: cyan;
    font-weight: bold;
}

.error {
    color: red;
    font-weight: bold;
}

.muted {
    opacity: 0.5;  /* maps to dim */
}

.success {
    color: green;
}

/* Shorthand works too */
.warning { color: yellow; }
```

Load CSS themes:

```rust
use standout_render::Theme;

let theme = Theme::from_css(css_content)?;
```

`Theme` parses a CSS string; reading the file is the caller's job:

```rust
let css = std::fs::read_to_string("styles/theme.css")?;
let theme = Theme::from_css(&css)?;
```

For a whole directory of themes with hot reload in debug builds, use
`AppBuilder::styles_dir` (see [App Configuration](../../../topics/app-configuration.md))
rather than reading a single file.

CSS gives you syntax highlighting in editors, linting tools, and familiarity for web developers.

### Programmatic Themes

Build themes in code using the builder pattern:

```rust
use standout_render::Theme;
use console::Style;

let theme = Theme::new()
    .add("title", Style::new().bold().cyan())
    .add("error", Style::new().red().bold())
    .add("muted", Style::new().dim())
    .add("success", Style::new().green());
```

> **Legacy format:** YAML themes are still supported via `Theme::from_yaml()`. CSS is the recommended format for all new projects.

---

## Supported Attributes

### Colors

| Attribute | CSS Property | Description             |
| --------- | ------------ | ----------------------- |
| `fg`      | `color`      | Foreground (text) color |
| `bg`      | `background` | Background color        |

### Color Formats

```css
/* Named colors (16 ANSI colors) */
.example { color: red; }
.example { color: green; }
.example { color: cyan; }
.example { color: magenta; }
.example { color: yellow; }
.example { color: white; }
.example { color: black; }

/* Bright variants */
.example { color: bright_red; }
.example { color: bright_green; }

/* 256-color palette (0-255) */
.example { color: 208; }

/* RGB hex */
.example { color: #ff6b35; }
.example { color: #f63; }     /* shorthand */

/* Theme-relative cube colors */
.example { color: cube(60%, 20%, 0%); }
```

Cube colors express a position in a color cube whose 8 corners are the base ANSI
colors of the user's terminal theme. The same `cube(60%, 20%, 0%)` produces earthy
tones in Gruvbox, pastels in Catppuccin, and muted shades in Solarized.
Interpolation is done in CIE LAB space for perceptually uniform gradients.
Attach a palette to a theme with `Theme::with_palette()`.

### Text Attributes

| CSS Property                    | Effect            |
| ------------------------------- | ----------------- |
| `font-weight: bold`             | Bold text         |
| `opacity: 0.5`                  | Dimmed/faint text |
| `font-style: italic`            | Italic text       |
| `text-decoration: underline`    | Underlined text   |
| `text-decoration: blink`        | Blinking text     |
| `text-decoration: line-through` | Strikethrough     |
| `visibility: hidden`            | Hidden text       |

---

## Adaptive Styles (Light/Dark Mode)

Terminal applications run in both light and dark environments. A color that looks great on a dark background may be illegible on a light one. `standout-render` solves this with adaptive styles.

### How It Works

Instead of defining separate "light theme" and "dark theme" files, you define mode-specific overrides at the style level:

```css
.panel {
    font-weight: bold;
    color: gray;        /* Default/fallback */
}

@media (prefers-color-scheme: light) {
    .panel { color: black; }   /* Override for light mode */
}

@media (prefers-color-scheme: dark) {
    .panel { color: white; }   /* Override for dark mode */
}
```

When resolving `panel` in dark mode:

1. Start with base attributes (`bold`, `gray`)
2. Merge dark overrides (`white` replaces `gray`)
3. Result: bold white text

This is efficient: most styles (bold, italic, semantic colors like green/red) look fine in both modes. Only a handful need adjustment—typically foreground colors for contrast.

### Programmatic API

```rust
use standout_render::Theme;
use console::{Style, Color};

let theme = Theme::new()
    .add_adaptive(
        "panel",
        Style::new().bold(),                     // Base (shared)
        Some(Style::new().fg(Color::Black)),     // Light mode
        Some(Style::new().fg(Color::White)),     // Dark mode
    );
```

### Color Mode Detection

`standout-render` auto-detects the OS color scheme when the caller probes the process:

```rust
use standout_render::{ColorMode, TargetProperties};

let properties = TargetProperties::detect();
match properties.color_scheme {
    ColorMode::Light => println!("Light mode"),
    ColorMode::Dark => println!("Dark mode"),
}
```

`TargetProperties::detect()` is the one process probe, at the crate edge. Convenience wrappers call it then pass the result into `render_request`. Tests construct `TargetProperties` with an explicit `color_scheme` rather than installing a detector; `set_theme_detector` and the other detector override APIs are removed.

---

## Style Aliasing

Aliases let semantic names resolve to visual styles. This is useful when multiple concepts share the same appearance:

```rust
let theme = Theme::new()
    // Define the visual style once
    .add("title", Style::new().bold().cyan())
    // Aliases — pass a string to reference another style by name
    .add("commit-message", "title")
    .add("section-header", "title")
    .add("heading", "title");
```

Now `[commit-message]`, `[section-header]`, and `[heading]` all render identically to `[title]`.

Benefits:

- Templates use meaningful, context-specific names
- Visual changes propagate automatically
- Refactoring visual design doesn't touch templates

Aliases can chain: `a` → `b` → `c` → concrete style. Cycles are detected and rejected at load time.

---

## Unknown Style Tags

When a template references a style tag not defined in the active theme,
`standout-render` degrades it to unstyled text instead of failing the render.
`Ansi` and `Plain` style modes treat unknown tags identically; the difference
between them is only whether *known* tags render as ANSI (`Ansi`) or as plain
text (`Plain`). What happens to an unknown tag depends on whether its open and
close markers are balanced:

- A **balanced pair**, `[unknown]x[/unknown]`, has its markers removed; the
  inner text `x` is kept as unstyled text.
- An **unbalanced** tag, `[unknown]` with no matching close, is emitted verbatim
  as literal text — the brackets survive, so the output contains `[unknown]`.
  This is why a stray `[compute]` appears verbatim in a plain render.

The `Debug` style mode, which `Representation::TermDebug` renders as, keeps
every tag — known or unknown — as literal text for inspection.

There is no `?` marker: an unknown tag is never rewritten to `[unknown?]` in
rendered output. Instead, each unresolved tag is recorded as a warning (see
[Unresolved-tag warning](#unresolved-tag-warning) below), whether it was
stripped or emitted verbatim.

A tag counts as unknown when it is absent from the *active theme's* resolved
style map. A tag your app defines in some themes but not the one currently
selected is unresolved in that theme and degrades the same way; the warning
does not distinguish a never-defined tag name from one merely missing in the
active theme.

To emit a literal `[` that must not be read as a tag, escape it as `\[` (and
`\]` for `]`). See [Literal brackets](templating.md#literal-brackets) in the
templating topic.

### Unresolved-tag warning

Each render pass records the tags it left unresolved as one warning line, naming
them all (sorted and de-duplicated):

```text
Unresolved style tag(s) degraded to unstyled text: compute, status
```

Where that warning goes depends on the entry point that drove the render:

- `App::run` writes it to stderr, after the command's own output.
- `App::run_with` and `App::dispatch` collect it into the returned
  `CompletedRun` and write nothing; the caller reads it with `.warnings()` and
  decides. `TestHarness` reads it this way.
- `App::render_with` and the standalone `standout-render` render APIs render
  with warnings disabled, so an unresolved tag degrades to unstyled text without
  recording or emitting anything.

An application whose specification pins its stderr bytes must account for the
`App::run` line. An escaped bracket (`\[`) is not a tag and raises no warning.

### Validation

For strict checking at startup:

```rust
use standout_render::validate_template;

if let Err(error) = validate_template(template, &sample_data, &theme) {
    eprintln!("Unknown style tag: {}", error);
    std::process::exit(1);
}
```

### Strict mode

The graceful degradation above — degrading unresolved tags to unstyled text (per-mode details in [Unknown Style Tags](#unknown-style-tags); no mode ever adds a `?` marker) plus a stderr warning — is the default and stays the default. `AppBuilder::strict_style_tags(true)` opts a whole app into failing instead: after a command renders, if the render left any style tag unresolved, the run ends with a non-zero exit and an error that names the offending tags — no output is emitted. This trades the graceful path for a deterministic failure so a typo'd tag name, or a tag the active theme does not style, is caught every time rather than by chance.

```rust
let app = App::builder()
    // ...
    .strict_style_tags(true)
    .build()?;
```

The `STANDOUT_STRICT_STYLE_TAGS` environment variable (`1`, `true`, `yes`, or `on`) forces strict mode on regardless of the builder setting, and can only turn it on, never off — so a dev shell, CI job, or test run can opt in without a code change.

Strict mode keys on unresolved tags only. A tag that *is* defined in the theme but whose markup is unbalanced (`[header]text` with no close) is malformed markup, not an unresolved tag, and does not trip the gate.

The error names each unresolved tag but does not distinguish a misspelled tag name from a tag the theme simply does not style: resolution is a single lookup against the active theme's styles, so both are "not in the theme," and separating them would need a registry of valid tag names the framework does not keep.

Use it where a wrong tag should stop the line — local development, CI, and tests — and leave it off in production, where the graceful degradation keeps a styling mistake from taking down a running command.

---

## Built-in Styles

`Theme::default()` includes adaptive styles for alternating table row backgrounds. These are used automatically when you pass `row_styles=true` (or a tint name) to the `table()` template function.

| Style name              | Purpose                                 |
| ----------------------- | --------------------------------------- |
| `table_row_even`        | Even rows — no background (transparent) |
| `table_row_odd`         | Odd rows — subtle gray background shift |
| `table_row_even_gray`   | Alias for `table_row_even`              |
| `table_row_odd_gray`    | Alias for `table_row_odd`               |
| `table_row_even_blue`   | Even rows for blue tint                 |
| `table_row_odd_blue`    | Odd rows — dark navy / lavender bg      |
| `table_row_even_red`    | Even rows for red tint                  |
| `table_row_odd_red`     | Odd rows — dark crimson / blush bg      |
| `table_row_even_green`  | Even rows for green tint                |
| `table_row_odd_green`   | Odd rows — dark forest / mint bg        |
| `table_row_even_purple` | Even rows for purple tint               |
| `table_row_odd_purple`  | Odd rows — dark plum / lilac bg         |

All odd-row styles are adaptive: they resolve to a dark variant when the terminal is in dark mode, and a light variant in light mode. You can override any of these by defining the same style name in your theme.

---

## Best Practices

### Semantic, Presentation, and Visual Layers

Organize your styles in three conceptual layers:

**1. Visual primitives** (low-level appearance):

```css
._cyan-bold { color: cyan; font-weight: bold; }
._dim { opacity: 0.5; }
._red-bold { color: red; font-weight: bold; }
```

**2. Presentation roles** (UI concepts — use aliases in code):

```rust
theme.add("heading", "_cyan-bold")
     .add("secondary", "_dim")
     .add("danger", "_red-bold");
```

**3. Semantic names** (domain concepts — aliases to presentation):

```rust
// In templates, use these
theme.add("task-title", "heading")
     .add("task-status-done", "success")
     .add("task-status-pending", "warning")
     .add("error-message", "danger");
```

Templates use semantic names (`task-title`), which resolve to presentation roles (`heading`), which resolve to visual primitives (`_cyan-bold`).

This layering lets you:

- Refactor visuals without touching templates
- Maintain consistency across domains
- Document the purpose of each style

### Naming Conventions

```css
/* Good: descriptive, semantic */
.error-message { ... }
.file-path { ... }
.command-name { ... }

/* Avoid: visual descriptions */
.red-text { ... }
.bold-cyan { ... }
```

### Keep Themes Focused

One theme per "look". Don't mix concerns:

```text
styles/
├── default.css          # your app's default look
├── colorblind.css       # accessibility variant
└── monochrome.css       # for piped output
```

---

## API Reference

### Theme Creation

```rust
// From CSS string
let theme = Theme::from_css(css_str)?;

// Empty theme (for programmatic building)
let theme = Theme::new();

// Legacy: YAML is still supported
let theme = Theme::from_yaml(yaml_str)?;
```

### Adding Styles

```rust
// Static style
theme.add("name", Style::new().bold());

// Adaptive style
theme.add_adaptive("name", base_style, light_override, dark_override);

// Alias
theme.add("alias", "target_style");
```

### Resolving Styles

```rust
// Get the mode-agnostic style
let style: Option<Style> = theme.get_style("title", None);

// Get style resolved for a specific mode
let style = theme.get_style("panel", Some(ColorMode::Dark));
```

### Color Mode

```rust
use standout_render::{ColorMode, TargetProperties};

// Auto-detect at the crate edge
let properties = TargetProperties::detect();
let mode = properties.color_scheme;

// Tests construct TargetProperties instead of installing a detector
let mut target = properties;
target.color_scheme = ColorMode::Light;
```