revue 2.71.1

A Vue-style TUI framework for Rust with CSS styling
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
//! Application builder

use super::App;
use crate::constants::MAX_CSS_FILE_SIZE;
use crate::plugin::{Plugin, PluginRegistry};
use crate::style::{parse_css, StyleSheet};
use std::fs;
use std::path::PathBuf;

#[cfg(feature = "hot-reload")]
use super::HotReload;

/// Builder for configuring and creating an App
pub struct AppBuilder {
    stylesheet: StyleSheet,
    // To keep track of file paths for hot reload
    style_paths: Vec<PathBuf>,
    hot_reload: bool,
    devtools: bool,
    mouse_capture: bool,
    plugins: PluginRegistry,
}

impl AppBuilder {
    /// Create a new application builder
    pub fn new() -> Self {
        Self {
            stylesheet: StyleSheet::new(),
            style_paths: Vec::new(),
            hot_reload: false,
            devtools: cfg!(feature = "devtools"),
            mouse_capture: true,
            plugins: PluginRegistry::new(),
        }
    }

    /// Register a plugin
    ///
    /// Plugins are initialized when the app is built and can hook into
    /// the application lifecycle.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use revue::plugin::LoggerPlugin;
    ///
    /// let app = App::builder()
    ///     .plugin(LoggerPlugin::new())
    ///     .build();
    /// ```
    pub fn plugin<P: Plugin + 'static>(mut self, plugin: P) -> Self {
        self.plugins.register(plugin);
        self
    }

    /// Add a CSS stylesheet from file
    pub fn style(mut self, path: impl Into<PathBuf>) -> Self {
        let path = path.into();
        self.style_paths.push(path.clone());

        // Check file size to prevent DoS
        match fs::metadata(&path) {
            Ok(metadata) => {
                if metadata.len() > MAX_CSS_FILE_SIZE {
                    log_warn!(
                        "CSS file too large ({} bytes, max {}): {:?}",
                        metadata.len(),
                        MAX_CSS_FILE_SIZE,
                        path
                    );
                    return self;
                }
            }
            Err(e) => {
                log_warn!("Failed to read CSS file metadata {:?}: {}", path, e);
                return self;
            }
        }

        // Read and parse CSS file
        let content = match fs::read_to_string(&path) {
            Ok(c) => c,
            Err(e) => {
                log_warn!("Failed to read CSS file {:?}: {}", path, e);
                return self;
            }
        };

        match parse_css(&content) {
            Ok(sheet) => self.stylesheet.merge(sheet),
            Err(e) => log_warn!("Failed to parse CSS from {:?}: {}", path, e),
        }

        self
    }

    /// Add inline CSS styles
    pub fn css(mut self, css: impl Into<String>) -> Self {
        let css = css.into();
        match parse_css(&css) {
            Ok(sheet) => self.stylesheet.merge(sheet),
            Err(e) => log_warn!("Failed to parse inline CSS: {}", e),
        }
        self
    }

    /// Enable hot reload for CSS files
    pub fn hot_reload(mut self, enabled: bool) -> Self {
        self.hot_reload = enabled;
        self
    }

    /// Enable devtools
    pub fn devtools(mut self, enabled: bool) -> Self {
        self.devtools = enabled;
        self
    }

    /// Enable/disable mouse capture
    pub fn mouse_capture(mut self, enabled: bool) -> Self {
        self.mouse_capture = enabled;
        self
    }

    /// Build the application
    pub fn build(mut self) -> App {
        let initial_size = {
            let (w, h) = crossterm::terminal::size().unwrap_or((80, 24));
            // Clamp to a sane minimum to avoid 0x0 buffers on some environments
            (w.max(1), h.max(1))
        };

        // Collect and merge plugin styles
        let plugin_css = self.plugins.collect_styles();
        if !plugin_css.is_empty() {
            if let Ok(sheet) = parse_css(&plugin_css) {
                self.stylesheet.merge(sheet);
            }
        }

        // Initialize plugins
        if let Err(e) = self.plugins.init() {
            log_warn!("Plugin initialization failed: {}", e);
        }

        // Set up hot reload if enabled and there are style paths
        #[cfg(feature = "hot-reload")]
        let hot_reload = if self.hot_reload && !self.style_paths.is_empty() {
            match HotReload::new() {
                Ok(mut hr) => {
                    for path in &self.style_paths {
                        if let Err(e) = hr.watch(path) {
                            log_warn!("Failed to watch {:?} for hot reload: {}", path, e);
                        }
                    }
                    Some(hr)
                }
                Err(e) => {
                    log_warn!("Failed to initialize hot reload: {}", e);
                    None
                }
            }
        } else {
            None
        };

        #[cfg(feature = "hot-reload")]
        return App::new_with_hot_reload(
            initial_size,
            self.stylesheet,
            self.mouse_capture,
            self.plugins,
            self.devtools,
            hot_reload,
            self.style_paths,
        );

        #[cfg(not(feature = "hot-reload"))]
        App::new_with_plugins(
            initial_size,
            self.stylesheet,
            self.mouse_capture,
            self.plugins,
            self.devtools,
        )
    }
}

impl Default for AppBuilder {
    fn default() -> Self {
        Self::new()
    }
}

// KEEP HERE - Private implementation tests (accesses private fields: style_paths, hot_reload, etc.)

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

    #[test]
    fn test_builder_new() {
        let builder = AppBuilder::new();
        assert!(builder.style_paths.is_empty());
        assert!(!builder.hot_reload);
        assert!(builder.mouse_capture);
    }

    #[test]
    fn test_builder_default_trait() {
        let builder = AppBuilder::default();
        assert!(builder.style_paths.is_empty());
        assert!(!builder.hot_reload);
        assert!(builder.mouse_capture);
    }

    #[test]
    fn test_builder_hot_reload_enabled() {
        let builder = AppBuilder::new().hot_reload(true);
        assert!(builder.hot_reload);
    }

    #[test]
    fn test_builder_hot_reload_disabled() {
        let builder = AppBuilder::new().hot_reload(false);
        assert!(!builder.hot_reload);
    }

    #[test]
    fn test_builder_devtools_enabled() {
        let builder = AppBuilder::new().devtools(true);
        assert!(builder.devtools);
    }

    #[test]
    fn test_builder_devtools_disabled() {
        let builder = AppBuilder::new().devtools(false);
        assert!(!builder.devtools);
    }

    #[test]
    fn test_builder_mouse_capture_enabled() {
        let builder = AppBuilder::new().mouse_capture(true);
        assert!(builder.mouse_capture);
    }

    #[test]
    fn test_builder_mouse_capture_disabled() {
        let builder = AppBuilder::new().mouse_capture(false);
        assert!(!builder.mouse_capture);
    }

    #[test]
    fn test_builder_css_valid() {
        let builder = AppBuilder::new().css("div { color: red; }");
        // Should parse without error; stylesheet gets updated
        assert!(!builder.stylesheet.rules.is_empty());
    }

    #[test]
    fn test_builder_css_empty() {
        let builder = AppBuilder::new().css("");
        // Empty CSS is valid, stylesheet remains empty
        assert!(builder.stylesheet.rules.is_empty());
    }

    #[test]
    fn test_builder_css_invalid() {
        // Invalid CSS should log warning but not panic
        let builder = AppBuilder::new().css("not { valid {{{ css");
        // Should still return a builder (with warning logged)
        assert!(builder.style_paths.is_empty());
    }

    #[test]
    fn test_builder_multiple_css() {
        let builder = AppBuilder::new()
            .css("div { color: red; }")
            .css("span { color: blue; }");
        // Both should be merged
        assert!(!builder.stylesheet.rules.is_empty());
    }

    #[test]
    fn test_builder_chaining() {
        let builder = AppBuilder::new()
            .hot_reload(true)
            .devtools(true)
            .mouse_capture(false)
            .css("div { display: flex; }");

        assert!(builder.hot_reload);
        assert!(builder.devtools);
        assert!(!builder.mouse_capture);
        assert!(!builder.stylesheet.rules.is_empty());
    }

    #[test]
    fn test_builder_style_nonexistent_file() {
        // Should handle missing file gracefully with warning
        let builder = AppBuilder::new().style("/nonexistent/path/style.css");
        assert_eq!(builder.style_paths.len(), 1);
        // File doesn't exist but path is tracked
    }

    #[test]
    fn test_builder_build() {
        let app = AppBuilder::new()
            .mouse_capture(false)
            .css("div { color: red; }")
            .build();
        assert!(!app.is_running());
        assert!(!app.mouse_capture);
    }

    #[test]
    fn test_builder_build_with_defaults() {
        let app = AppBuilder::new().build();
        assert!(!app.is_running());
        assert!(app.mouse_capture); // Default is true
    }

    #[test]
    #[ignore = "flaky: crossterm::terminal::size() returns (0,0) in parallel test environment"]
    fn test_builder_build_initializes_buffers() {
        let app = AppBuilder::new().build();
        // Should have initialized buffers
        assert!(app.buffers[0].width() > 0 || app.buffers[0].height() > 0);
    }

    #[test]
    fn test_builder_devtools_actually_enables() {
        // Build with devtools enabled
        let app = AppBuilder::new().devtools(true).build();

        // Verify devtools was enabled by build()
        assert!(
            app.is_devtools_enabled(),
            "devtools should be enabled after build() with devtools(true)"
        );
    }

    #[test]
    fn test_builder_devtools_disabled_by_default_when_feature_off() {
        // Build with devtools explicitly disabled
        let app = AppBuilder::new().devtools(false).build();

        // Verify devtools is disabled
        assert!(
            !app.is_devtools_enabled(),
            "devtools should be disabled when devtools(false)"
        );
    }

    #[test]
    #[cfg(feature = "hot-reload")]
    #[ignore = "HotReload::new() blocks for extended time on Windows CI (24+ minutes)"]
    fn test_builder_hot_reload_with_style_path() {
        use std::io::Write;

        // Create a temporary CSS file
        let temp_dir = match tempfile::tempdir() {
            Ok(dir) => dir,
            Err(_) => return, // Skip test if tempdir creation fails
        };
        let css_path = temp_dir.path().join("test.css");
        let mut file = match std::fs::File::create(&css_path) {
            Ok(f) => f,
            Err(_) => return, // Skip test if file creation fails
        };
        let _ = writeln!(file, "div {{ color: red; }}");

        // Build with hot reload enabled
        let app = AppBuilder::new().hot_reload(true).style(&css_path).build();

        // Verify hot reload is set up (app has hot_reload field)
        assert!(app.hot_reload.is_some(), "hot_reload should be initialized");
    }

    #[test]
    #[cfg(feature = "hot-reload")]
    fn test_builder_hot_reload_disabled_no_watcher() {
        // Build with hot reload disabled
        let app = AppBuilder::new().hot_reload(false).build();

        // Verify hot reload is not set up
        assert!(
            app.hot_reload.is_none(),
            "hot_reload should be None when disabled"
        );
    }

    #[test]
    #[cfg(feature = "hot-reload")]
    fn test_builder_hot_reload_no_style_paths() {
        // Build with hot reload enabled but no style paths
        let app = AppBuilder::new().hot_reload(true).build();

        // hot_reload should be None because there are no style paths to watch
        assert!(
            app.hot_reload.is_none(),
            "hot_reload should be None when no style paths"
        );
    }
}