Skip to main content

sprite/utils/
accessibility.rs

1//! Accessibility utilities for the Sprite multi-agent toolkit.
2//!
3//! This module provides accessibility features to ensure the CLI is usable
4//! by people with disabilities, including screen reader support and WCAG compliance.
5
6#![allow(dead_code)]
7
8use std::env;
9use std::io::{self, Write};
10
11/// Configuration for accessibility features
12#[derive(Debug, Clone)]
13pub struct AccessibilityConfig {
14    /// Whether to use screen reader compatible output
15    pub screen_reader: bool,
16    /// Whether to disable colors (NO_COLOR support)
17    pub no_color: bool,
18    /// Whether to use high contrast mode
19    #[allow(dead_code)]
20    pub high_contrast: bool,
21    /// Whether to use verbose output for better context
22    #[allow(dead_code)]
23    pub verbose: bool,
24}
25
26impl Default for AccessibilityConfig {
27    fn default() -> Self {
28        Self {
29            screen_reader: should_enable_screen_reader(),
30            no_color: should_disable_color(),
31            high_contrast: false,
32            verbose: false,
33        }
34    }
35}
36
37/// Determine if screen reader mode should be enabled
38fn should_enable_screen_reader() -> bool {
39    // Check for common screen reader environment variables
40    env::var("SCREEN_READER").is_ok() ||
41    env::var("SR").is_ok() ||
42    env::var("JAWS").is_ok() ||
43    env::var("NVDA").is_ok() ||
44    env::var("VOICEOVER").is_ok() ||
45    env::var("TALKBACK").is_ok() ||
46    // Check for assistive technology indicators
47    env::var("ACCESSIBILITY").is_ok() ||
48    env::var("A11Y").is_ok()
49}
50
51/// Determine if colors should be disabled
52fn should_disable_color() -> bool {
53    // NO_COLOR specification: https://no-color.org/
54    env::var("NO_COLOR").is_ok() ||
55    // Traditional way to disable colors
56    env::var("TERM").unwrap_or_default().contains("dumb") ||
57    env::var("CLICOLOR").unwrap_or_default() == "0"
58}
59
60/// Print accessible text with proper formatting
61#[allow(dead_code)]
62pub fn print_accessible(text: &str, config: &AccessibilityConfig) {
63    let formatted_text = format_for_accessibility(text, config);
64    println!("{}", formatted_text);
65}
66
67/// Print accessible error message
68pub fn print_error(message: &str, config: &AccessibilityConfig) {
69    let formatted = if config.screen_reader {
70        format!("ERROR: {}. {}", message, get_suggestion_for_error(message))
71    } else {
72        format!("❌ Error: {}", message)
73    };
74
75    writeln!(io::stderr(), "{}", formatted).ok();
76}
77
78/// Print accessible success message
79pub fn print_success(message: &str, config: &AccessibilityConfig) {
80    let formatted = if config.screen_reader {
81        format!("SUCCESS: {}", message)
82    } else if config.no_color {
83        format!("✓ {}", message)
84    } else {
85        format!("✅ {}", message)
86    };
87
88    println!("{}", formatted);
89}
90
91/// Print accessible warning message
92pub fn print_warning(message: &str, config: &AccessibilityConfig) {
93    let formatted = if config.screen_reader {
94        format!("WARNING: {}", message)
95    } else if config.no_color {
96        format!("⚠ {}", message)
97    } else {
98        format!("⚠️  {}", message)
99    };
100
101    println!("{}", formatted);
102}
103
104/// Print accessible info message
105pub fn print_info(message: &str, config: &AccessibilityConfig) {
106    let formatted = if config.screen_reader {
107        format!("INFO: {}", message)
108    } else if config.no_color {
109        format!("ℹ {}", message)
110    } else {
111        format!("ℹ️  {}", message)
112    };
113
114    println!("{}", formatted);
115}
116
117/// Format text for accessibility
118fn format_for_accessibility(text: &str, config: &AccessibilityConfig) -> String {
119    let mut formatted = text.to_string();
120
121    if config.screen_reader {
122        // Add semantic annotations for screen readers
123        formatted = add_semantic_annotations(&formatted);
124    } else if config.no_color || config.high_contrast {
125        // Replace emojis with simple text equivalents for no_color or high contrast
126        formatted = replace_emojis_simple(&formatted);
127    }
128
129    formatted
130}
131
132/// Add semantic annotations for screen readers
133fn add_semantic_annotations(text: &str) -> String {
134    // Replace emojis with descriptive text
135    text.replace("✅", "[SUCCESS]")
136        .replace("❌", "[ERROR]")
137        .replace("⚠️", "[WARNING]")
138        .replace("ℹ️", "[INFO]")
139        .replace("📡", "[BROADCAST]")
140        .replace("🔄", "[SYNC]")
141        .replace("📁", "[DIRECTORY]")
142        .replace("🎬", "[SESSION]")
143        .replace("📋", "[PANE]")
144        .replace("🔍", "[ZOOM]")
145        .replace("💡", "[SUGGESTION]")
146        .replace("🧹", "[CLEANUP]")
147        .replace("✓", "[DONE]")
148        .replace("→", "[ARROW]")
149}
150
151/// Replace emojis with simple text equivalents (for no_color mode)
152fn replace_emojis_simple(text: &str) -> String {
153    text.replace("✅", "✓")
154        .replace("❌", "✗")
155        .replace("⚠️", "⚠")
156        .replace("ℹ️", "ℹ")
157        .replace("📡", "[BROADCAST]")
158        .replace("🔄", "[SYNC]")
159        .replace("📁", "[DIR]")
160        .replace("🎬", "[SESSION]")
161        .replace("📋", "[LIST]")
162        .replace("🔍", "[SEARCH]")
163        .replace("💡", "[INFO]")
164        .replace("🧹", "[CLEAN]")
165        .replace("→", "->")
166}
167
168/// Replace emojis with text equivalents
169#[allow(dead_code)]
170fn replace_emojis_with_text(text: &str) -> String {
171    text.replace("✅", "SUCCESS")
172        .replace("❌", "ERROR")
173        .replace("⚠️", "WARNING")
174        .replace("ℹ️", "INFO")
175        .replace("📡", "BROADCAST")
176        .replace("🔄", "SYNC")
177        .replace("📁", "DIRECTORY")
178        .replace("🎬", "SESSION")
179        .replace("📋", "PANE")
180        .replace("🔍", "ZOOM")
181        .replace("💡", "SUGGESTION")
182        .replace("🧹", "CLEANUP")
183        .replace("✓", "DONE")
184        .replace("→", "ARROW")
185}
186
187/// Get suggestion for common error types
188fn get_suggestion_for_error(error_message: &str) -> String {
189    if error_message.contains("tmux") {
190        "Make sure tmux is installed and running. Use 'brew install tmux' on macOS or 'apt install tmux' on Ubuntu.".to_string()
191    } else if error_message.contains("git") {
192        "Make sure you're in a git repository. Use 'git init' to create one.".to_string()
193    } else if error_message.contains("configuration") || error_message.contains("config") {
194        "Use 'sprite init' to create a default configuration file.".to_string()
195    } else if error_message.contains("permission") {
196        "Check file permissions and try running with appropriate access rights.".to_string()
197    } else if error_message.contains("not found") {
198        "Check if the specified file or directory exists and is accessible.".to_string()
199    } else {
200        "Use 'sprite --help' to see available commands and options.".to_string()
201    }
202}
203
204/// Format a list with accessibility in mind
205pub fn format_list(items: &[&str], config: &AccessibilityConfig) -> String {
206    if config.screen_reader {
207        // For screen readers, use numbered list with semantic markers
208        items
209            .iter()
210            .enumerate()
211            .map(|(i, item)| format!("Item {}: {}", i + 1, item))
212            .collect::<Vec<_>>()
213            .join("\n")
214    } else {
215        // Regular bullet list
216        items
217            .iter()
218            .map(|item| format!("• {}", item))
219            .collect::<Vec<_>>()
220            .join("\n")
221    }
222}
223
224/// Format a table with accessibility in mind
225pub fn format_table(
226    headers: &[&str],
227    rows: &[Vec<String>],
228    config: &AccessibilityConfig,
229) -> String {
230    if config.screen_reader {
231        // For screen readers, format as simple text with column labels
232        let mut result = String::new();
233        result.push_str("Table start:\n");
234
235        for (i, row) in rows.iter().enumerate() {
236            result.push_str(&format!("Row {}:\n", i + 1));
237            for (j, cell) in row.iter().enumerate() {
238                if j < headers.len() {
239                    result.push_str(&format!("  {}: {}\n", headers[j], cell));
240                }
241            }
242        }
243
244        result.push_str("Table end.\n");
245        result
246    } else {
247        // Simple table formatting
248        let mut result = String::new();
249
250        // Header row
251        result.push_str(&headers.join(" | "));
252        result.push('\n');
253        result.push_str(&"-".repeat(headers.join(" | ").len()));
254        result.push('\n');
255
256        // Data rows
257        for row in rows {
258            result.push_str(&row.join(" | "));
259            result.push('\n');
260        }
261
262        result
263    }
264}
265
266/// Format progress with accessibility in mind
267pub fn format_progress(
268    current: usize,
269    total: usize,
270    description: &str,
271    config: &AccessibilityConfig,
272) -> String {
273    if config.screen_reader {
274        format!(
275            "Progress: {} of {} complete. {}",
276            current, total, description
277        )
278    } else {
279        let percentage = if total > 0 {
280            (current * 100) / total
281        } else {
282            0
283        };
284        format!(
285            "({}%){} {}",
286            percentage,
287            if percentage < 100 { " " } else { "" },
288            description
289        )
290    }
291}
292
293/// Validate output for WCAG compliance
294pub fn validate_wcag_compliance(text: &str) -> Vec<String> {
295    let mut issues = Vec::new();
296
297    // Check for sufficient contrast indicators
298    if text.contains("✅") || text.contains("❌") || text.contains("⚠️") {
299        issues.push(
300            "Consider using text alternatives to emojis for better accessibility".to_string(),
301        );
302    }
303
304    // Check for color-only information
305    if text.contains("red") || text.contains("green") || text.contains("blue") {
306        issues.push("Avoid using color as the only way to convey information".to_string());
307    }
308
309    // Check for complex formatting that might be hard for screen readers
310    if text.chars().filter(|c| *c == '|').count() > 5 {
311        issues.push("Complex table formatting may be difficult for screen readers".to_string());
312    }
313
314    // Check for adequate description length
315    let words: Vec<&str> = text.split_whitespace().collect();
316    if words.len() < 3 && !text.is_empty() {
317        issues.push("Very short text may not provide sufficient context".to_string());
318    }
319
320    issues
321}
322
323/// Print help text in an accessible format
324pub fn print_help(
325    command: &str,
326    description: &str,
327    usage: &str,
328    options: &[(&str, &str)],
329    config: &AccessibilityConfig,
330) {
331    if config.screen_reader {
332        println!("Command: {}", command);
333        println!("Description: {}", description);
334        println!("Usage: {}", usage);
335        println!("Options:");
336
337        for (option, desc) in options {
338            println!("  {}: {}", option, desc);
339        }
340    } else {
341        println!("{} - {}", command, description);
342        println!();
343        println!("USAGE:");
344        println!("  {}", usage);
345        println!();
346        println!("OPTIONS:");
347
348        for (option, desc) in options {
349            println!("  {}  {}", option, desc);
350        }
351    }
352}
353
354#[cfg(test)]
355mod tests {
356    use super::*;
357
358    #[test]
359    fn test_accessibility_config_default() {
360        let config = AccessibilityConfig::default();
361        // Verify default values - these depend on environment variables
362        // Just verify the struct is created successfully
363        let _ = config.screen_reader;
364        let _ = config.no_color;
365        assert!(!config.high_contrast);
366        assert!(!config.verbose);
367    }
368
369    #[test]
370    fn test_screen_reader_formatting() {
371        let config = AccessibilityConfig {
372            screen_reader: true,
373            no_color: false,
374            high_contrast: false,
375            verbose: false,
376        };
377
378        let result = format_for_accessibility("✅ Success", &config);
379        assert!(result.contains("[SUCCESS]"));
380        assert!(!result.contains("✅"));
381    }
382
383    #[test]
384    fn test_no_color_formatting() {
385        let config = AccessibilityConfig {
386            screen_reader: false,
387            no_color: true,
388            high_contrast: false,
389            verbose: false,
390        };
391
392        let result = format_for_accessibility("✅ Success", &config);
393        assert!(result.contains("✓"));
394        assert!(!result.contains("✅"));
395    }
396
397    #[test]
398    fn test_wcag_validation() {
399        let issues = validate_wcag_compliance("✅ Success with red text");
400        assert!(!issues.is_empty());
401        assert!(issues.iter().any(|i| i.contains("emoji")));
402    }
403
404    #[test]
405    fn test_list_formatting() {
406        let items = vec!["Item 1", "Item 2"];
407        let config_screen_reader = AccessibilityConfig {
408            screen_reader: true,
409            no_color: false,
410            high_contrast: false,
411            verbose: false,
412        };
413
414        let result = format_list(&items, &config_screen_reader);
415        assert!(result.contains("Item 1:"));
416        assert!(result.contains("Item 2:"));
417    }
418
419    #[test]
420    fn test_error_suggestions() {
421        let suggestion = get_suggestion_for_error("tmux session not found");
422        assert!(suggestion.contains("tmux"));
423        assert!(suggestion.contains("install"));
424    }
425}