deckhand 0.1.0

Present markdown slide decks as a TUI — live embedded terminals, a 2-D slide grid, presenter notes, and a wasm presenter for the browser
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
//! Theming: layout, borders, and colors.
//!
//! Sources, lowest to highest precedence, merged field by field:
//!   1. built-in defaults (matches deckhand's out-of-the-box look)
//!   2. `~/.config/deckhand/theme.json` (or `$XDG_CONFIG_HOME/deckhand/theme.json`)
//!   3. the `"theme"` section of a JSON deck manifest
//!
//! Colors are names ("cyan", "light-blue"), hex ("#rrggbb"), or a 0-255
//! palette index (as a JSON number or string).

use std::path::PathBuf;
use std::str::FromStr;

use anyhow::{Context, Result, bail};
use ratatui::style::Color;
use ratatui::widgets::BorderType;
use serde::{Deserialize, Serialize};

/// A color as authored in configuration: a 0-255 palette index, or a
/// string holding a name ("cyan", "light-blue") or hex ("#rrggbb").
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum ColorSpec {
    /// A 256-color palette index.
    Index(u8),
    /// A color name or `#rrggbb` hex value.
    Name(String),
}

impl ColorSpec {
    fn to_color(&self) -> Result<Color> {
        match self {
            ColorSpec::Index(n) => Ok(Color::Indexed(*n)),
            ColorSpec::Name(raw) => {
                let raw = raw.trim();
                if let Ok(c) = Color::from_str(raw) {
                    return Ok(c);
                }
                // "light blue" / "light_blue" → "lightblue"
                let squashed: String = raw
                    .to_lowercase()
                    .chars()
                    .filter(|c| !matches!(c, ' ' | '-' | '_'))
                    .collect();
                Color::from_str(&squashed).map_err(|_| {
                    anyhow::anyhow!(
                        "unrecognized color {raw:?} (use a name like \"light-blue\", \
                         \"#rrggbb\" hex, or a 0-255 palette index)"
                    )
                })
            }
        }
    }
}

/// All-optional theme as it appears in JSON manifests or markdown
/// frontmatter. Missing fields fall through to the next source in the
/// precedence chain.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ThemeConfig {
    /// Max content width in columns (default 96).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_width: Option<u16>,
    /// Max content height in rows (default unlimited). Caps everything
    /// drawn — fill terminals and a pinned title included.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_height: Option<u16>,
    /// Minimum air on all four sides, in cells: shorthand that sets
    /// both axes. The per-axis keys win where both are given.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub margin: Option<u16>,
    /// Minimum horizontal margin per side, in columns (default 2).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub margin_x: Option<u16>,
    /// Minimum vertical margin per side, in rows (default 0).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub margin_y: Option<u16>,
    /// Where leftover width goes: "left", "center" (default), "right".
    #[serde(skip_serializing_if = "Option::is_none")]
    pub align_x: Option<String>,
    /// Where leftover height goes: "top", "center" (default), "bottom".
    #[serde(skip_serializing_if = "Option::is_none")]
    pub align_y: Option<String>,
    /// Anchor a slide-leading heading to the top of the content area;
    /// the body below it still follows `align_y`. Default false.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pin_title: Option<bool>,
    /// Blank rows between a pinned title and the body (default 1).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title_gap: Option<u16>,
    /// "plain" (default), "rounded", "double", or "thick".
    #[serde(skip_serializing_if = "Option::is_none")]
    pub border_type: Option<String>,
    /// Focused borders, overview selection, help border, key hints.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub accent: Option<ColorSpec>,
    /// Rules, hints, separators, unfocused chrome.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub muted: Option<ColorSpec>,
    /// Unfocused terminal borders.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub term_border: Option<ColorSpec>,
    /// Borders of terminals showing a baked-in snapshot; supersedes
    /// `term_border` for those (unset = inherit `term_border`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub snapshot_border: Option<ColorSpec>,
    /// Status bar background.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status_bg: Option<ColorSpec>,
    /// Status bar text.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status_fg: Option<ColorSpec>,
    /// "normal" (default) or "banner": banner draws H1s as large
    /// block glyphs (three rows tall), falling back to normal for
    /// headings with unsupported characters or too little width.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub h1_style: Option<String>,
    /// Level-1 headings.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub h1: Option<ColorSpec>,
    /// Level-2 headings.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub h2: Option<ColorSpec>,
    /// List bullets and numbers.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bullet: Option<ColorSpec>,
    /// Blockquote markers.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub quote: Option<ColorSpec>,
    /// Link text.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub link: Option<ColorSpec>,
    /// Inline code spans.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub inline_code: Option<ColorSpec>,
    /// Code block background.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub code_bg: Option<ColorSpec>,
    /// Code block text.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub code_fg: Option<ColorSpec>,
    /// Syntax highlighting: keywords.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub code_keyword: Option<ColorSpec>,
    /// Syntax highlighting: strings.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub code_string: Option<ColorSpec>,
    /// Syntax highlighting: comments.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub code_comment: Option<ColorSpec>,
    /// Syntax highlighting: numbers and named constants.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub code_literal: Option<ColorSpec>,
    /// Syntax highlighting: called functions.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub code_function: Option<ColorSpec>,
    /// Syntax highlighting: types, classes, constructors.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub code_type: Option<ColorSpec>,
    /// QR code modules (default true black). Keep it darker than
    /// `qr_light` and high-contrast, or scanners will give up; light
    /// codes on dark backgrounds fail on many readers.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub qr_dark: Option<ColorSpec>,
    /// QR code background, quiet zone included (default true white).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub qr_light: Option<ColorSpec>,
}

impl ThemeConfig {
    /// Field-wise overlay: values set in `over` win.
    pub fn merged(self, over: ThemeConfig) -> ThemeConfig {
        ThemeConfig {
            max_width: over.max_width.or(self.max_width),
            max_height: over.max_height.or(self.max_height),
            margin: over.margin.or(self.margin),
            margin_x: over.margin_x.or(self.margin_x),
            margin_y: over.margin_y.or(self.margin_y),
            align_x: over.align_x.or(self.align_x),
            align_y: over.align_y.or(self.align_y),
            pin_title: over.pin_title.or(self.pin_title),
            title_gap: over.title_gap.or(self.title_gap),
            border_type: over.border_type.or(self.border_type),
            accent: over.accent.or(self.accent),
            muted: over.muted.or(self.muted),
            term_border: over.term_border.or(self.term_border),
            snapshot_border: over.snapshot_border.or(self.snapshot_border),
            status_bg: over.status_bg.or(self.status_bg),
            status_fg: over.status_fg.or(self.status_fg),
            h1_style: over.h1_style.or(self.h1_style),
            h1: over.h1.or(self.h1),
            h2: over.h2.or(self.h2),
            bullet: over.bullet.or(self.bullet),
            quote: over.quote.or(self.quote),
            link: over.link.or(self.link),
            inline_code: over.inline_code.or(self.inline_code),
            code_bg: over.code_bg.or(self.code_bg),
            code_fg: over.code_fg.or(self.code_fg),
            code_keyword: over.code_keyword.or(self.code_keyword),
            code_string: over.code_string.or(self.code_string),
            code_comment: over.code_comment.or(self.code_comment),
            code_literal: over.code_literal.or(self.code_literal),
            code_function: over.code_function.or(self.code_function),
            code_type: over.code_type.or(self.code_type),
            qr_dark: over.qr_dark.or(self.qr_dark),
            qr_light: over.qr_light.or(self.qr_light),
        }
    }
}

/// Where leftover height goes when the content box is shorter than
/// the space inside the margins.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum VAlign {
    /// Vertically centered (the default).
    Center,
    /// Anchored to the top.
    Top,
    /// Anchored to the bottom.
    Bottom,
}

/// Where leftover width goes when the content box is narrower than
/// the space inside the margins.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum HAlign {
    /// Horizontally centered (the default).
    Center,
    /// Anchored to the left edge.
    Left,
    /// Anchored to the right edge.
    Right,
}

/// A fully-resolved theme, ready to render with. Produced by
/// [`Theme::resolve`] from layered [`ThemeConfig`]s.
#[derive(Debug, Clone, Copy)]
pub struct Theme {
    /// Max content width in columns.
    pub max_width: u16,
    /// Max content height in rows (`u16::MAX` = unlimited).
    pub max_height: u16,
    /// Minimum horizontal margin per side, in columns.
    pub margin_x: u16,
    /// Minimum vertical margin per side, in rows.
    pub margin_y: u16,
    /// Horizontal placement of the content box within the margins.
    pub align_x: HAlign,
    /// Vertical placement of the content box within the margins.
    pub align_y: VAlign,
    /// Slide-leading headings stick to the top of the content area;
    /// the body follows `align_y`.
    pub pin_title: bool,
    /// Blank rows between a pinned title and the body.
    pub title_gap: u16,
    /// Border style for terminals, overview boxes, and overlays.
    pub border_type: BorderType,
    /// Focused borders, overview selection, help chrome, key hints.
    pub accent: Color,
    /// Rules, hints, separators, unfocused chrome.
    pub muted: Color,
    /// Unfocused live-terminal borders.
    pub term_border: Color,
    /// `None` inherits `term_border`; presenters resolve via
    /// [`Theme::snapshot_border`].
    pub snapshot_border: Option<Color>,
    /// Status bar background.
    pub status_bg: Color,
    /// Status bar text.
    pub status_fg: Color,
    /// Draw H1s as large block glyphs ([`crate::banner`]).
    pub h1_banner: bool,
    /// Level-1 headings.
    pub h1: Color,
    /// Level-2 headings.
    pub h2: Color,
    /// List bullets and numbers.
    pub bullet: Color,
    /// Blockquote markers.
    pub quote: Color,
    /// Link text.
    pub link: Color,
    /// Inline code spans.
    pub inline_code: Color,
    /// Code block background.
    pub code_bg: Color,
    /// Code block text.
    pub code_fg: Color,
    /// Syntax highlighting: keywords.
    pub code_keyword: Color,
    /// Syntax highlighting: strings.
    pub code_string: Color,
    /// Syntax highlighting: comments (also italicized).
    pub code_comment: Color,
    /// Syntax highlighting: numbers and named constants.
    pub code_literal: Color,
    /// Syntax highlighting: called functions.
    pub code_function: Color,
    /// Syntax highlighting: types, classes, constructors.
    pub code_type: Color,
    /// QR code modules.
    pub qr_dark: Color,
    /// QR code background, quiet zone included.
    pub qr_light: Color,
}

impl Default for Theme {
    fn default() -> Self {
        Theme {
            max_width: 96,
            max_height: u16::MAX,
            margin_x: 2,
            margin_y: 0,
            align_x: HAlign::Center,
            align_y: VAlign::Center,
            pin_title: false,
            title_gap: 1,
            border_type: BorderType::Plain,
            accent: Color::Cyan,
            // Mid-gray from the 256-color palette rather than ANSI
            // DarkGray: schemes like solarized remap ANSI 0-15, turning
            // DarkGray into near-background (invisible borders).
            muted: Color::Indexed(244),
            term_border: Color::Indexed(244),
            snapshot_border: None,
            status_bg: Color::Indexed(236),
            status_fg: Color::Indexed(250),
            h1_banner: false,
            h1: Color::Cyan,
            h2: Color::LightBlue,
            bullet: Color::Cyan,
            quote: Color::Green,
            link: Color::Blue,
            inline_code: Color::Yellow,
            code_bg: Color::Indexed(235),
            code_fg: Color::Indexed(252),
            // One Dark-flavored truecolor: RGB bypasses terminal
            // palettes entirely (the same reasoning as the indexed
            // grays above, taken further), and xterm.js renders it
            // faithfully on the web.
            code_keyword: Color::Rgb(0xc6, 0x78, 0xdd),
            code_string: Color::Rgb(0x98, 0xc3, 0x79),
            code_comment: Color::Rgb(0x7f, 0x84, 0x90),
            code_literal: Color::Rgb(0xd1, 0x9a, 0x66),
            code_function: Color::Rgb(0x61, 0xaf, 0xef),
            code_type: Color::Rgb(0xe5, 0xc0, 0x7b),
            // True black-on-white from the 256-color cube — scanners
            // want dark-on-light, and ANSI black/white are remappable.
            qr_dark: Color::Indexed(16),
            qr_light: Color::Indexed(231),
        }
    }
}

impl Theme {
    /// Border color for a snapshot-rendered terminal: its own setting,
    /// or the live-terminal default.
    pub fn snapshot_border(&self) -> Color {
        self.snapshot_border.unwrap_or(self.term_border)
    }

    /// Merge configs (lowest precedence first) over the defaults.
    ///
    /// ```
    /// use deckhand::theme::{Theme, ThemeConfig};
    /// use ratatui::style::Color;
    ///
    /// let user: ThemeConfig = serde_json::from_str(r#"{ "accent": "magenta" }"#)?;
    /// let deck: ThemeConfig = serde_json::from_str(r#"{ "max_width": 60 }"#)?;
    /// let theme = Theme::resolve(vec![user, deck])?;
    /// assert_eq!(theme.accent, Color::Magenta); // user survives
    /// assert_eq!(theme.max_width, 60);          // deck wins its field
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn resolve(configs: Vec<ThemeConfig>) -> Result<Theme> {
        let cfg = configs
            .into_iter()
            .fold(ThemeConfig::default(), ThemeConfig::merged);
        let mut t = Theme::default();
        if let Some(w) = cfg.max_width {
            t.max_width = w.max(20);
        }
        if let Some(h) = cfg.max_height {
            t.max_height = h.max(5);
        }
        // `margin` is the both-axes shorthand; the per-axis keys win.
        if let Some(m) = cfg.margin {
            t.margin_x = m.min(30);
            t.margin_y = m.min(30);
        }
        if let Some(m) = cfg.margin_x {
            t.margin_x = m.min(30);
        }
        if let Some(m) = cfg.margin_y {
            t.margin_y = m.min(30);
        }
        if let Some(a) = cfg.align_x {
            t.align_x = match a.as_str() {
                "center" => HAlign::Center,
                "left" => HAlign::Left,
                "right" => HAlign::Right,
                other => {
                    bail!(
                        "theme.align_x: expected \"left\", \"center\", or \"right\", got {other:?}"
                    )
                }
            };
        }
        if let Some(a) = cfg.align_y {
            t.align_y = match a.as_str() {
                "center" => VAlign::Center,
                "top" => VAlign::Top,
                "bottom" => VAlign::Bottom,
                other => {
                    bail!(
                        "theme.align_y: expected \"top\", \"center\", or \"bottom\", got {other:?}"
                    )
                }
            };
        }
        if let Some(p) = cfg.pin_title {
            t.pin_title = p;
        }
        if let Some(g) = cfg.title_gap {
            t.title_gap = g.min(20);
        }
        if let Some(s) = cfg.h1_style {
            t.h1_banner = match s.as_str() {
                "normal" => false,
                "banner" => true,
                other => {
                    bail!("theme.h1_style: expected \"normal\" or \"banner\", got {other:?}")
                }
            };
        }
        if let Some(b) = cfg.border_type {
            t.border_type = match b.as_str() {
                "plain" => BorderType::Plain,
                "rounded" => BorderType::Rounded,
                "double" => BorderType::Double,
                "thick" => BorderType::Thick,
                other => bail!(
                    "theme.border_type: expected \"plain\", \"rounded\", \"double\", or \"thick\", got {other:?}"
                ),
            };
        }
        macro_rules! color {
            ($field:ident) => {
                if let Some(c) = &cfg.$field {
                    t.$field = c
                        .to_color()
                        .with_context(|| concat!("theme.", stringify!($field)))?;
                }
            };
        }
        color!(accent);
        color!(muted);
        color!(term_border);
        if let Some(c) = &cfg.snapshot_border {
            t.snapshot_border = Some(c.to_color().context("theme.snapshot_border")?);
        }
        color!(status_bg);
        color!(status_fg);
        color!(h1);
        color!(h2);
        color!(bullet);
        color!(quote);
        color!(link);
        color!(inline_code);
        color!(code_bg);
        color!(code_fg);
        color!(code_keyword);
        color!(code_string);
        color!(code_comment);
        color!(code_literal);
        color!(code_function);
        color!(code_type);
        color!(qr_dark);
        color!(qr_light);
        Ok(t)
    }
}

/// Where the user-level theme lives:
/// `$XDG_CONFIG_HOME/deckhand/theme.json` or `~/.config/deckhand/theme.json`.
pub fn user_config_path() -> Option<PathBuf> {
    if let Ok(xdg) = std::env::var("XDG_CONFIG_HOME")
        && !xdg.is_empty()
    {
        return Some(PathBuf::from(xdg).join("deckhand").join("theme.json"));
    }
    std::env::var("HOME").ok().map(|h| {
        PathBuf::from(h)
            .join(".config")
            .join("deckhand")
            .join("theme.json")
    })
}

/// The user-level theme file, if one exists. A malformed file is an error
/// (silently ignoring it would make debugging a typo miserable).
pub fn user_config() -> Result<Option<ThemeConfig>> {
    let Some(path) = user_config_path() else {
        return Ok(None);
    };
    if !path.exists() {
        return Ok(None);
    }
    let src = std::fs::read_to_string(&path)
        .with_context(|| format!("reading theme {}", path.display()))?;
    let cfg =
        serde_json::from_str(&src).with_context(|| format!("parsing theme {}", path.display()))?;
    Ok(Some(cfg))
}

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

    #[test]
    fn defaults_when_empty() {
        let t = Theme::resolve(vec![]).unwrap();
        assert_eq!(t.max_width, 96);
        assert_eq!(t.accent, Color::Cyan);
    }

    #[test]
    fn merge_precedence() {
        let user: ThemeConfig =
            serde_json::from_str(r#"{ "accent": "magenta", "max_width": 80 }"#).unwrap();
        let deck: ThemeConfig =
            serde_json::from_str(r#"{ "max_width": 60, "max_height": 25 }"#).unwrap();
        let t = Theme::resolve(vec![user, deck]).unwrap();
        assert_eq!(t.max_width, 60); // deck wins
        assert_eq!(t.max_height, 25);
        assert_eq!(t.accent, Color::Magenta); // user survives
    }

    #[test]
    fn color_forms() {
        let cfg: ThemeConfig = serde_json::from_str(
            r##"{ "h1": "#ff8800", "code_bg": 17, "bullet": "light-green" }"##,
        )
        .unwrap();
        let t = Theme::resolve(vec![cfg]).unwrap();
        assert_eq!(t.h1, Color::Rgb(255, 136, 0));
        assert_eq!(t.code_bg, Color::Indexed(17));
        assert_eq!(t.bullet, Color::LightGreen);
    }

    #[test]
    fn snapshot_border_supersedes_term_border() {
        // Unset: inherits the live-terminal border.
        let t = Theme::resolve(vec![]).unwrap();
        assert_eq!(t.snapshot_border(), t.term_border);

        let cfg: ThemeConfig =
            serde_json::from_str(r#"{ "term_border": "blue", "snapshot_border": "yellow" }"#)
                .unwrap();
        let t = Theme::resolve(vec![cfg]).unwrap();
        assert_eq!(t.term_border, Color::Blue);
        assert_eq!(t.snapshot_border(), Color::Yellow);
    }

    #[test]
    fn margin_shorthand_and_axis_overrides() {
        let t = Theme::resolve(vec![]).unwrap();
        assert_eq!((t.margin_x, t.margin_y), (2, 0));

        let cfg: ThemeConfig = serde_json::from_str(r#"{ "margin": 4 }"#).unwrap();
        let t = Theme::resolve(vec![cfg]).unwrap();
        assert_eq!((t.margin_x, t.margin_y), (4, 4));

        // Per-axis keys beat the shorthand, whichever layer set it.
        let user: ThemeConfig = serde_json::from_str(r#"{ "margin_y": 3 }"#).unwrap();
        let deck: ThemeConfig = serde_json::from_str(r#"{ "margin": 1 }"#).unwrap();
        let t = Theme::resolve(vec![user, deck]).unwrap();
        assert_eq!((t.margin_x, t.margin_y), (1, 3));
    }

    #[test]
    fn align_axes_resolve() {
        let t = Theme::resolve(vec![]).unwrap();
        assert_eq!(t.align_x, HAlign::Center);
        assert_eq!(t.align_y, VAlign::Center);

        let cfg: ThemeConfig =
            serde_json::from_str(r#"{ "align_x": "right", "align_y": "bottom" }"#).unwrap();
        let t = Theme::resolve(vec![cfg]).unwrap();
        assert_eq!(t.align_x, HAlign::Right);
        assert_eq!(t.align_y, VAlign::Bottom);

        let cfg: ThemeConfig = serde_json::from_str(r#"{ "align_y": "middle" }"#).unwrap();
        assert!(Theme::resolve(vec![cfg]).is_err());
    }

    #[test]
    fn pin_title_resolves_and_merges() {
        let t = Theme::resolve(vec![]).unwrap();
        assert!(!t.pin_title);
        let user: ThemeConfig = serde_json::from_str(r#"{ "pin_title": true }"#).unwrap();
        let deck: ThemeConfig = serde_json::from_str(r#"{ "accent": "red" }"#).unwrap();
        let t = Theme::resolve(vec![user, deck]).unwrap();
        assert!(t.pin_title); // survives an overlay that doesn't set it
    }

    #[test]
    fn qr_colors_default_to_true_black_on_white() {
        let t = Theme::resolve(vec![]).unwrap();
        assert_eq!(t.qr_dark, Color::Indexed(16));
        assert_eq!(t.qr_light, Color::Indexed(231));

        let cfg: ThemeConfig =
            serde_json::from_str(r##"{ "qr_dark": "#102040", "qr_light": "#fdf6e3" }"##).unwrap();
        let t = Theme::resolve(vec![cfg]).unwrap();
        assert_eq!(t.qr_dark, Color::Rgb(0x10, 0x20, 0x40));
        assert_eq!(t.qr_light, Color::Rgb(0xfd, 0xf6, 0xe3));
    }

    #[test]
    fn bad_values_error() {
        let cfg: ThemeConfig = serde_json::from_str(r#"{ "accent": "chartreuse" }"#).unwrap();
        assert!(Theme::resolve(vec![cfg]).is_err());
        let cfg: ThemeConfig = serde_json::from_str(r#"{ "border_type": "wavy" }"#).unwrap();
        assert!(Theme::resolve(vec![cfg]).is_err());
    }
}