rch-common 1.0.26

Shared types and utilities for Remote Compilation Helper
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
//! RCH brand colors and semantic styles.
//!
//! Provides a unified theme for consistent visual branding across all RCH commands.
//! All color constants are valid hex colors that work with `rich_rust`.

#[cfg(all(feature = "rich-ui", unix))]
use rich_rust::prelude::{Color, Style};

use crate::types::WorkerStatus;

/// RCH brand colors and semantic styles.
///
/// # Design Philosophy
///
/// - **Purple**: Compilation/build theme - sophisticated, technical
/// - **Cyan**: Data transfer theme - clean, digital
/// - **Amber**: Attention/highlights - warm, visible
///
/// # Example (with rich-ui feature)
///
/// ```ignore
/// use rch_common::ui::RchTheme;
///
/// let style = RchTheme::success();
/// // Use style with rich_rust Console
/// ```
pub struct RchTheme;

impl RchTheme {
    // ═══════════════════════════════════════════════════════════════════════
    // BRAND COLORS
    // ═══════════════════════════════════════════════════════════════════════

    /// Primary brand color - Purple (compilation/build theme).
    pub const PRIMARY: &'static str = "#8B5CF6";

    /// Secondary brand color - Cyan (data/transfer theme).
    pub const SECONDARY: &'static str = "#06B6D4";

    /// Accent color - Amber (highlights, attention).
    pub const ACCENT: &'static str = "#F59E0B";

    // ═══════════════════════════════════════════════════════════════════════
    // SEMANTIC COLORS
    // ═══════════════════════════════════════════════════════════════════════

    /// Success state - Green.
    pub const SUCCESS: &'static str = "#10B981";

    /// Warning state - Amber.
    pub const WARNING: &'static str = "#F59E0B";

    /// Error state - Red.
    pub const ERROR: &'static str = "#EF4444";

    /// Informational - Blue.
    pub const INFO: &'static str = "#3B82F6";

    // ═══════════════════════════════════════════════════════════════════════
    // WORKER STATUS COLORS
    // These match the WorkerStatus enum from rch-common/types
    // ═══════════════════════════════════════════════════════════════════════

    /// Worker is healthy and accepting work - Green.
    pub const STATUS_HEALTHY: &'static str = "#10B981";

    /// Worker is degraded (slow, high error rate) - Amber.
    pub const STATUS_DEGRADED: &'static str = "#F59E0B";

    /// Worker is unreachable (connection failed) - Red.
    pub const STATUS_UNREACHABLE: &'static str = "#EF4444";

    /// Worker is draining (no new work) - Purple.
    pub const STATUS_DRAINING: &'static str = "#8B5CF6";

    /// Worker is drained (drain complete, idle) - Indigo.
    pub const STATUS_DRAINED: &'static str = "#6366F1";

    /// Worker is disabled (admin disabled) - Gray.
    pub const STATUS_DISABLED: &'static str = "#737B8A";

    // ═══════════════════════════════════════════════════════════════════════
    // TEXT COLORS
    // ═══════════════════════════════════════════════════════════════════════

    /// Muted text (secondary information) - Gray-400.
    pub const MUTED: &'static str = "#9CA3AF";

    /// Dim text (tertiary information) - Gray-500.
    pub const DIM: &'static str = "#737B8A";

    /// Bright text (emphasis) - Gray-50.
    pub const BRIGHT: &'static str = "#F9FAFB";

    // ═══════════════════════════════════════════════════════════════════════
    // STYLE GENERATORS (require rich-ui feature)
    // ═══════════════════════════════════════════════════════════════════════

    /// Create style for success messages.
    #[cfg(all(feature = "rich-ui", unix))]
    #[must_use]
    pub fn success() -> Style {
        Style::new().color(Color::parse(Self::SUCCESS).unwrap_or_default())
    }

    /// Create style for error messages (bold for emphasis).
    #[cfg(all(feature = "rich-ui", unix))]
    #[must_use]
    pub fn error() -> Style {
        Style::new()
            .bold()
            .color(Color::parse(Self::ERROR).unwrap_or_default())
    }

    /// Create style for warning messages.
    #[cfg(all(feature = "rich-ui", unix))]
    #[must_use]
    pub fn warning() -> Style {
        Style::new().color(Color::parse(Self::WARNING).unwrap_or_default())
    }

    /// Create style for informational messages.
    #[cfg(all(feature = "rich-ui", unix))]
    #[must_use]
    pub fn info() -> Style {
        Style::new().color(Color::parse(Self::INFO).unwrap_or_default())
    }

    /// Create style for muted/secondary text.
    #[cfg(all(feature = "rich-ui", unix))]
    #[must_use]
    pub fn muted() -> Style {
        Style::new().color(Color::parse(Self::MUTED).unwrap_or_default())
    }

    /// Create style for dim/tertiary text.
    #[cfg(all(feature = "rich-ui", unix))]
    #[must_use]
    pub fn dim() -> Style {
        Style::new()
            .dim()
            .color(Color::parse(Self::DIM).unwrap_or_default())
    }

    /// Create style for primary brand elements.
    #[cfg(all(feature = "rich-ui", unix))]
    #[must_use]
    pub fn primary() -> Style {
        Style::new().color(Color::parse(Self::PRIMARY).unwrap_or_default())
    }

    /// Create style for secondary brand elements.
    #[cfg(all(feature = "rich-ui", unix))]
    #[must_use]
    pub fn secondary() -> Style {
        Style::new().color(Color::parse(Self::SECONDARY).unwrap_or_default())
    }

    /// Create style for accent/highlight elements.
    #[cfg(all(feature = "rich-ui", unix))]
    #[must_use]
    pub fn accent() -> Style {
        Style::new().color(Color::parse(Self::ACCENT).unwrap_or_default())
    }

    /// Create style for worker status based on string.
    #[cfg(all(feature = "rich-ui", unix))]
    #[must_use]
    pub fn worker_status_str(status: &str) -> Style {
        let color = match status.to_lowercase().as_str() {
            "healthy" => Self::STATUS_HEALTHY,
            "degraded" => Self::STATUS_DEGRADED,
            "unreachable" => Self::STATUS_UNREACHABLE,
            "draining" => Self::STATUS_DRAINING,
            "disabled" => Self::STATUS_DISABLED,
            _ => Self::MUTED,
        };
        Style::new().color(Color::parse(color).unwrap_or_default())
    }

    /// Create style for worker status enum.
    #[cfg(all(feature = "rich-ui", unix))]
    #[must_use]
    pub fn for_worker_status(status: WorkerStatus) -> Style {
        let color = match status {
            WorkerStatus::Healthy => Self::STATUS_HEALTHY,
            WorkerStatus::Degraded => Self::STATUS_DEGRADED,
            WorkerStatus::Unreachable => Self::STATUS_UNREACHABLE,
            WorkerStatus::Draining => Self::STATUS_DRAINING,
            WorkerStatus::Drained => Self::STATUS_DRAINED,
            WorkerStatus::Disabled => Self::STATUS_DISABLED,
        };
        Style::new().color(Color::parse(color).unwrap_or_default())
    }

    // ═══════════════════════════════════════════════════════════════════════
    // COMPOSITE STYLES (require rich-ui feature)
    // ═══════════════════════════════════════════════════════════════════════

    /// Style for table headers.
    #[cfg(all(feature = "rich-ui", unix))]
    #[must_use]
    pub fn table_header() -> Style {
        Style::new()
            .bold()
            .color(Color::parse(Self::BRIGHT).unwrap_or_default())
    }

    /// Style for table borders.
    #[cfg(all(feature = "rich-ui", unix))]
    #[must_use]
    pub fn table_border() -> Style {
        Style::new().color(Color::parse(Self::PRIMARY).unwrap_or_default())
    }

    /// Style for panel titles.
    #[cfg(all(feature = "rich-ui", unix))]
    #[must_use]
    pub fn panel_title() -> Style {
        Style::new()
            .bold()
            .color(Color::parse(Self::SECONDARY).unwrap_or_default())
    }

    /// Style for command/code text.
    #[cfg(all(feature = "rich-ui", unix))]
    #[must_use]
    pub fn code() -> Style {
        Style::new().color(Color::parse(Self::SECONDARY).unwrap_or_default())
    }

    /// Style for paths/filenames.
    #[cfg(all(feature = "rich-ui", unix))]
    #[must_use]
    pub fn path() -> Style {
        Style::new()
            .italic()
            .color(Color::parse(Self::INFO).unwrap_or_default())
    }

    /// Style for numbers/metrics.
    #[cfg(all(feature = "rich-ui", unix))]
    #[must_use]
    pub fn number() -> Style {
        Style::new().color(Color::parse(Self::ACCENT).unwrap_or_default())
    }

    // ═══════════════════════════════════════════════════════════════════════
    // COLOR LOOKUP (always available)
    // ═══════════════════════════════════════════════════════════════════════

    /// Get color hex code for a worker status.
    #[must_use]
    pub const fn color_for_worker_status(status: WorkerStatus) -> &'static str {
        match status {
            WorkerStatus::Healthy => Self::STATUS_HEALTHY,
            WorkerStatus::Degraded => Self::STATUS_DEGRADED,
            WorkerStatus::Unreachable => Self::STATUS_UNREACHABLE,
            WorkerStatus::Draining => Self::STATUS_DRAINING,
            WorkerStatus::Drained => Self::STATUS_DRAINED,
            WorkerStatus::Disabled => Self::STATUS_DISABLED,
        }
    }

    /// Get color hex code for a status string (case-insensitive).
    #[must_use]
    pub fn color_for_status_str(status: &str) -> &'static str {
        match status.to_lowercase().as_str() {
            "healthy" => Self::STATUS_HEALTHY,
            "degraded" => Self::STATUS_DEGRADED,
            "unreachable" => Self::STATUS_UNREACHABLE,
            "draining" => Self::STATUS_DRAINING,
            "drained" => Self::STATUS_DRAINED,
            "disabled" => Self::STATUS_DISABLED,
            "success" | "ok" => Self::SUCCESS,
            "warning" | "warn" => Self::WARNING,
            "error" | "fail" | "failed" => Self::ERROR,
            "info" => Self::INFO,
            _ => Self::MUTED,
        }
    }
}

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

    fn parse_hex_rgb(color: &str) -> (u8, u8, u8) {
        let color = color.strip_prefix('#').unwrap_or(color);
        assert_eq!(color.len(), 6, "Expected RRGGBB hex string, got: {color}");

        let r = u8::from_str_radix(&color[0..2], 16).expect("Invalid hex for R");
        let g = u8::from_str_radix(&color[2..4], 16).expect("Invalid hex for G");
        let b = u8::from_str_radix(&color[4..6], 16).expect("Invalid hex for B");

        (r, g, b)
    }

    fn srgb_channel_to_linear(channel: u8) -> f64 {
        let c = f64::from(channel) / 255.0;
        if c <= 0.04045 {
            c / 12.92
        } else {
            ((c + 0.055) / 1.055).powf(2.4)
        }
    }

    fn relative_luminance(color: &str) -> f64 {
        let (r, g, b) = parse_hex_rgb(color);
        let r = srgb_channel_to_linear(r);
        let g = srgb_channel_to_linear(g);
        let b = srgb_channel_to_linear(b);

        0.2126 * r + 0.7152 * g + 0.0722 * b
    }

    fn contrast_ratio(foreground: &str, background: &str) -> f64 {
        let l1 = relative_luminance(foreground);
        let l2 = relative_luminance(background);
        let (lighter, darker) = if l1 >= l2 { (l1, l2) } else { (l2, l1) };
        (lighter + 0.05) / (darker + 0.05)
    }

    #[test]
    fn test_all_color_constants_are_valid_hex() {
        // All color constants should be 7-character hex strings (#RRGGBB)
        let colors = [
            RchTheme::PRIMARY,
            RchTheme::SECONDARY,
            RchTheme::ACCENT,
            RchTheme::SUCCESS,
            RchTheme::WARNING,
            RchTheme::ERROR,
            RchTheme::INFO,
            RchTheme::STATUS_HEALTHY,
            RchTheme::STATUS_DEGRADED,
            RchTheme::STATUS_UNREACHABLE,
            RchTheme::STATUS_DRAINING,
            RchTheme::STATUS_DISABLED,
            RchTheme::MUTED,
            RchTheme::DIM,
            RchTheme::BRIGHT,
        ];

        for color in colors {
            assert!(color.starts_with('#'), "Color should start with #: {color}");
            assert_eq!(color.len(), 7, "Color should be 7 chars: {color}");
            assert!(
                color[1..].chars().all(|c| c.is_ascii_hexdigit()),
                "Color should be valid hex: {color}"
            );
        }
    }

    #[test]
    fn test_semantic_colors_meet_contrast_on_dark_background() {
        // WCAG 2.1 AA target for normal text is 4.5:1.
        //
        // Terminals vary widely, but a dark background is the most common
        // interactive default. For light terminals (or accessibility tooling),
        // RCH supports `NO_COLOR=1` to disable color entirely.
        const BACKGROUND: &str = "#000000";
        const MIN_RATIO: f64 = 4.5;

        let colors = [
            ("PRIMARY", RchTheme::PRIMARY),
            ("SECONDARY", RchTheme::SECONDARY),
            ("ACCENT", RchTheme::ACCENT),
            ("SUCCESS", RchTheme::SUCCESS),
            ("WARNING", RchTheme::WARNING),
            ("ERROR", RchTheme::ERROR),
            ("INFO", RchTheme::INFO),
            ("STATUS_HEALTHY", RchTheme::STATUS_HEALTHY),
            ("STATUS_DEGRADED", RchTheme::STATUS_DEGRADED),
            ("STATUS_UNREACHABLE", RchTheme::STATUS_UNREACHABLE),
            ("STATUS_DRAINING", RchTheme::STATUS_DRAINING),
            ("STATUS_DISABLED", RchTheme::STATUS_DISABLED),
            ("MUTED", RchTheme::MUTED),
            ("DIM", RchTheme::DIM),
            ("BRIGHT", RchTheme::BRIGHT),
        ];

        for (name, color) in colors {
            let ratio = contrast_ratio(color, BACKGROUND);
            assert!(
                ratio >= MIN_RATIO,
                "{name} ({color}) contrast vs {BACKGROUND} too low: {ratio:.2}"
            );
        }
    }

    #[test]
    fn test_color_for_worker_status() {
        assert_eq!(
            RchTheme::color_for_worker_status(WorkerStatus::Healthy),
            RchTheme::STATUS_HEALTHY
        );
        assert_eq!(
            RchTheme::color_for_worker_status(WorkerStatus::Degraded),
            RchTheme::STATUS_DEGRADED
        );
        assert_eq!(
            RchTheme::color_for_worker_status(WorkerStatus::Unreachable),
            RchTheme::STATUS_UNREACHABLE
        );
        assert_eq!(
            RchTheme::color_for_worker_status(WorkerStatus::Draining),
            RchTheme::STATUS_DRAINING
        );
        assert_eq!(
            RchTheme::color_for_worker_status(WorkerStatus::Drained),
            RchTheme::STATUS_DRAINED
        );
        assert_eq!(
            RchTheme::color_for_worker_status(WorkerStatus::Disabled),
            RchTheme::STATUS_DISABLED
        );
    }

    #[test]
    fn test_color_for_status_str() {
        // Case insensitive
        assert_eq!(
            RchTheme::color_for_status_str("HEALTHY"),
            RchTheme::STATUS_HEALTHY
        );
        assert_eq!(
            RchTheme::color_for_status_str("healthy"),
            RchTheme::STATUS_HEALTHY
        );
        assert_eq!(
            RchTheme::color_for_status_str("Healthy"),
            RchTheme::STATUS_HEALTHY
        );

        // Aliases
        assert_eq!(RchTheme::color_for_status_str("success"), RchTheme::SUCCESS);
        assert_eq!(RchTheme::color_for_status_str("ok"), RchTheme::SUCCESS);
        assert_eq!(RchTheme::color_for_status_str("error"), RchTheme::ERROR);
        assert_eq!(RchTheme::color_for_status_str("fail"), RchTheme::ERROR);
        assert_eq!(RchTheme::color_for_status_str("failed"), RchTheme::ERROR);

        // Unknown -> muted
        assert_eq!(RchTheme::color_for_status_str("unknown"), RchTheme::MUTED);
        assert_eq!(RchTheme::color_for_status_str(""), RchTheme::MUTED);
    }

    #[test]
    fn test_all_status_colors_are_distinct() {
        let colors = [
            RchTheme::STATUS_HEALTHY,
            RchTheme::STATUS_DEGRADED,
            RchTheme::STATUS_UNREACHABLE,
            RchTheme::STATUS_DRAINING,
            RchTheme::STATUS_DRAINED,
            RchTheme::STATUS_DISABLED,
        ];

        // Check all pairs are distinct
        for (i, &c1) in colors.iter().enumerate() {
            for &c2 in &colors[i + 1..] {
                assert_ne!(c1, c2, "Status colors should be distinct");
            }
        }
    }

    // =========================================================================
    // ADDITIONAL WCAG 2.1 AA ACCESSIBILITY TESTS
    // =========================================================================

    /// Verify contrast ratio calculation is correct.
    #[test]
    fn test_contrast_ratio_calculation_accuracy() {
        // Black on white should be 21:1 (maximum)
        let ratio = contrast_ratio("#FFFFFF", "#000000");
        assert!(
            (ratio - 21.0).abs() < 0.1,
            "White/black contrast should be ~21:1, got {ratio:.2}:1"
        );

        // Same color should be 1:1
        let same = contrast_ratio("#FF0000", "#FF0000");
        assert!(
            (same - 1.0).abs() < 0.01,
            "Same color contrast should be 1:1"
        );
    }

    /// Verify colors work on slightly darker terminal backgrounds.
    #[test]
    fn test_colors_on_dark_gray_background() {
        const DARK_GRAY: &str = "#1a1a1a";
        const MIN_RATIO: f64 = 4.5;

        let critical_colors = [
            ("ERROR", RchTheme::ERROR),
            ("SUCCESS", RchTheme::SUCCESS),
            ("WARNING", RchTheme::WARNING),
        ];

        for (name, color) in critical_colors {
            let ratio = contrast_ratio(color, DARK_GRAY);
            assert!(
                ratio >= MIN_RATIO,
                "{name} ({color}) must be readable on dark gray: {ratio:.2}:1 < {MIN_RATIO}:1"
            );
        }
    }

    #[cfg(all(feature = "rich-ui", unix))]
    mod rich_ui_tests {
        use super::*;
        use rich_rust::prelude::Color;

        #[test]
        fn test_all_colors_parse_with_rich_rust() {
            // Ensure no color constant is malformed
            assert!(Color::parse(RchTheme::PRIMARY).is_ok());
            assert!(Color::parse(RchTheme::SECONDARY).is_ok());
            assert!(Color::parse(RchTheme::ACCENT).is_ok());
            assert!(Color::parse(RchTheme::SUCCESS).is_ok());
            assert!(Color::parse(RchTheme::WARNING).is_ok());
            assert!(Color::parse(RchTheme::ERROR).is_ok());
            assert!(Color::parse(RchTheme::INFO).is_ok());
            assert!(Color::parse(RchTheme::STATUS_HEALTHY).is_ok());
            assert!(Color::parse(RchTheme::STATUS_DEGRADED).is_ok());
            assert!(Color::parse(RchTheme::STATUS_UNREACHABLE).is_ok());
            assert!(Color::parse(RchTheme::STATUS_DRAINING).is_ok());
            assert!(Color::parse(RchTheme::STATUS_DRAINED).is_ok());
            assert!(Color::parse(RchTheme::STATUS_DISABLED).is_ok());
            assert!(Color::parse(RchTheme::MUTED).is_ok());
            assert!(Color::parse(RchTheme::DIM).is_ok());
            assert!(Color::parse(RchTheme::BRIGHT).is_ok());
        }

        #[test]
        fn test_styles_dont_panic() {
            // Ensure style generators don't panic
            let _ = RchTheme::success();
            let _ = RchTheme::error();
            let _ = RchTheme::warning();
            let _ = RchTheme::info();
            let _ = RchTheme::muted();
            let _ = RchTheme::dim();
            let _ = RchTheme::primary();
            let _ = RchTheme::secondary();
            let _ = RchTheme::accent();
            let _ = RchTheme::table_header();
            let _ = RchTheme::table_border();
            let _ = RchTheme::panel_title();
            let _ = RchTheme::code();
            let _ = RchTheme::path();
            let _ = RchTheme::number();
        }

        #[test]
        fn test_worker_status_styles() {
            // String-based
            let _ = RchTheme::worker_status_str("healthy");
            let _ = RchTheme::worker_status_str("unknown"); // Should not panic

            // Enum-based
            let _ = RchTheme::for_worker_status(WorkerStatus::Healthy);
            let _ = RchTheme::for_worker_status(WorkerStatus::Degraded);
            let _ = RchTheme::for_worker_status(WorkerStatus::Unreachable);
            let _ = RchTheme::for_worker_status(WorkerStatus::Draining);
            let _ = RchTheme::for_worker_status(WorkerStatus::Drained);
            let _ = RchTheme::for_worker_status(WorkerStatus::Disabled);
        }
    }
}