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
406
407
408
409
410
411
412
use std::time::Duration;

use crate::event::{Key, KeyEvent};
use crate::render::Buffer;
use crate::testing::{Action, KeyAction, MouseAction, TestApp, TestConfig};

/// Pilot controller for automated testing
pub struct Pilot<'a, V: crate::widget::View> {
    /// The test app being controlled
    app: &'a mut TestApp<V>,
    /// Test configuration
    config: TestConfig,
    /// Action history
    history: Vec<Action>,
}

impl<'a, V: crate::widget::View> Pilot<'a, V> {
    /// Create a new pilot for a test app
    pub fn new(app: &'a mut TestApp<V>) -> Self {
        Self {
            app,
            config: TestConfig::default(),
            history: Vec::new(),
        }
    }

    /// Create with custom config
    pub fn with_config(app: &'a mut TestApp<V>, config: TestConfig) -> Self {
        Self {
            app,
            config,
            history: Vec::new(),
        }
    }

    // =========================================================================
    // Key Actions
    // =========================================================================

    /// Press a key
    pub fn press_key(&mut self, key: Key) -> &mut Self {
        let event = KeyEvent::new(key);
        self.app.send_key(event);
        self.history.push(Action::Key(KeyAction::Press(key)));
        self
    }

    /// Press a key with ctrl modifier
    pub fn press_ctrl(&mut self, key: Key) -> &mut Self {
        let event = KeyEvent::ctrl(key);
        self.app.send_key(event);
        self.history.push(Action::Key(KeyAction::PressCtrl(key)));
        self
    }

    /// Press a key with alt modifier
    pub fn press_alt(&mut self, key: Key) -> &mut Self {
        let event = KeyEvent::alt(key);
        self.app.send_key(event);
        self.history.push(Action::Key(KeyAction::PressAlt(key)));
        self
    }

    /// Press Enter
    pub fn press_enter(&mut self) -> &mut Self {
        self.press_key(Key::Enter)
    }

    /// Press Escape
    pub fn press_escape(&mut self) -> &mut Self {
        self.press_key(Key::Escape)
    }

    /// Press Tab
    pub fn press_tab(&mut self) -> &mut Self {
        self.press_key(Key::Tab)
    }

    /// Press Shift+Tab (back tab)
    pub fn press_backtab(&mut self) -> &mut Self {
        self.press_key(Key::BackTab)
    }

    /// Press arrow up
    pub fn press_up(&mut self) -> &mut Self {
        self.press_key(Key::Up)
    }

    /// Press arrow down
    pub fn press_down(&mut self) -> &mut Self {
        self.press_key(Key::Down)
    }

    /// Press arrow left
    pub fn press_left(&mut self) -> &mut Self {
        self.press_key(Key::Left)
    }

    /// Press arrow right
    pub fn press_right(&mut self) -> &mut Self {
        self.press_key(Key::Right)
    }

    /// Type a string (sends each character as a key press)
    pub fn type_text(&mut self, text: &str) -> &mut Self {
        for ch in text.chars() {
            self.press_key(Key::Char(ch));
        }
        self.history
            .push(Action::Key(KeyAction::Type(text.to_string())));
        self
    }

    /// Press Ctrl+C
    pub fn press_ctrl_c(&mut self) -> &mut Self {
        self.press_ctrl(Key::Char('c'))
    }

    // =========================================================================
    // Mouse Actions
    // =========================================================================

    /// Click at position
    pub fn click(&mut self, x: u16, y: u16) -> &mut Self {
        self.app.send_click(x, y);
        self.history.push(Action::Mouse(MouseAction::Click(x, y)));
        self
    }

    /// Double click at position
    pub fn double_click(&mut self, x: u16, y: u16) -> &mut Self {
        self.click(x, y);
        self.click(x, y);
        self.history
            .push(Action::Mouse(MouseAction::DoubleClick(x, y)));
        self
    }

    /// Scroll up at position
    pub fn scroll_up(&mut self, x: u16, y: u16, amount: u16) -> &mut Self {
        self.app.send_scroll(x, y, -(amount as i16));
        self.history
            .push(Action::Mouse(MouseAction::ScrollUp(x, y, amount)));
        self
    }

    /// Scroll down at position
    pub fn scroll_down(&mut self, x: u16, y: u16, amount: u16) -> &mut Self {
        self.app.send_scroll(x, y, amount as i16);
        self.history
            .push(Action::Mouse(MouseAction::ScrollDown(x, y, amount)));
        self
    }

    // =========================================================================
    // Timing
    // =========================================================================

    /// Wait for a duration
    pub fn wait(&mut self, duration: Duration) -> &mut Self {
        std::thread::sleep(duration);
        self.history.push(Action::Wait(duration));
        self
    }

    /// Wait for milliseconds
    pub fn wait_ms(&mut self, ms: u64) -> &mut Self {
        self.wait(Duration::from_millis(ms))
    }

    /// Wait for a condition to be true
    pub fn wait_until<F>(&mut self, condition: F) -> &mut Self
    where
        F: Fn(&Buffer) -> bool,
    {
        let start = std::time::Instant::now();
        let timeout = Duration::from_millis(self.config.timeout_ms);

        while !condition(self.app.buffer()) {
            if start.elapsed() >= timeout {
                panic!("wait_until timed out after {:?}", timeout);
            }
            std::thread::sleep(Duration::from_millis(10));
            self.app.render();
        }

        self
    }

    // =========================================================================
    // Assertions
    // =========================================================================

    /// Check if screen contains text
    pub fn screen_contains(&self, text: &str) -> bool {
        self.app.screen_text().contains(text)
    }

    /// Assert screen contains text
    pub fn assert_contains(&self, text: &str) {
        assert!(
            self.screen_contains(text),
            "Expected screen to contain '{}', but got:\n{}",
            text,
            self.app.screen_text()
        );
    }

    /// Assert screen does not contain text
    pub fn assert_not_contains(&self, text: &str) {
        assert!(
            !self.screen_contains(text),
            "Expected screen NOT to contain '{}', but it did:\n{}",
            text,
            self.app.screen_text()
        );
    }

    /// Get text at specific line
    pub fn line(&self, row: u16) -> String {
        self.app.get_line(row)
    }

    /// Assert line contains text
    pub fn assert_line_contains(&self, row: u16, text: &str) {
        let line = self.line(row);
        assert!(
            line.contains(text),
            "Expected line {} to contain '{}', but got: '{}'",
            row,
            text,
            line
        );
    }

    /// Get cell at position
    pub fn cell(&self, x: u16, y: u16) -> Option<char> {
        self.app.get_cell(x, y)
    }

    /// Assert cell equals
    pub fn assert_cell(&self, x: u16, y: u16, expected: char) {
        let actual = self.cell(x, y);
        assert_eq!(
            actual,
            Some(expected),
            "Expected cell ({}, {}) to be '{}', but got {:?}",
            x,
            y,
            expected,
            actual
        );
    }

    // =========================================================================
    // Snapshots
    // =========================================================================

    /// Get current screen as string
    pub fn screen(&self) -> String {
        self.app.screen_text()
    }

    /// Assert screen matches expected string
    pub fn assert_screen(&self, expected: &str) {
        let actual = self.screen();
        let expected_trimmed = expected.trim();
        let actual_trimmed = actual.trim();

        assert_eq!(
            actual_trimmed, expected_trimmed,
            "Screen does not match expected.\nExpected:\n{}\n\nActual:\n{}",
            expected_trimmed, actual_trimmed
        );
    }

    /// Capture snapshot or compare against existing snapshot
    ///
    /// Snapshots are stored in `tests/snapshots/` directory.
    /// Set `REVUE_UPDATE_SNAPSHOTS=1` environment variable to update snapshots.
    ///
    /// # Example
    ///
    /// ```ignore
    /// pilot.press_up()
    ///     .snapshot("counter_at_1")
    ///     .press_up()
    ///     .snapshot("counter_at_2");
    /// ```
    pub fn snapshot(&mut self, name: &str) -> &mut Self {
        let manager = crate::testing::snapshot::SnapshotManager::new();
        manager.assert_buffer_snapshot(name, self.app.buffer());
        self
    }

    // =========================================================================
    // Query
    // =========================================================================

    /// Find position of text on screen
    pub fn find_text(&self, text: &str) -> Option<(u16, u16)> {
        self.app.find_text(text)
    }

    /// Click on text (finds and clicks)
    pub fn click_text(&mut self, text: &str) -> &mut Self {
        if let Some((x, y)) = self.find_text(text) {
            self.click(x, y);
        } else {
            panic!("Text '{}' not found on screen", text);
        }
        self
    }

    // =========================================================================
    // State
    // =========================================================================

    /// Get action history
    pub fn history(&self) -> &[Action] {
        &self.history
    }

    /// Clear action history
    pub fn clear_history(&mut self) {
        self.history.clear();
    }

    /// Get screen size
    pub fn size(&self) -> (u16, u16) {
        (self.config.width, self.config.height)
    }

    /// Resize screen
    pub fn resize(&mut self, width: u16, height: u16) {
        self.config.width = width;
        self.config.height = height;
        self.app.resize(width, height);
    }

    // =========================================================================
    // Async Support
    // =========================================================================

    /// Wait for a duration (async version)
    pub async fn wait_async(&mut self, duration: Duration) -> &mut Self {
        #[cfg(feature = "async")]
        {
            tokio::time::sleep(duration).await;
        }
        #[cfg(not(feature = "async"))]
        {
            // Fallback to sync sleep if tokio not available
            std::thread::sleep(duration);
        }
        self.history.push(Action::Wait(duration));
        self
    }

    /// Wait for milliseconds (async version)
    pub async fn wait_ms_async(&mut self, ms: u64) -> &mut Self {
        self.wait_async(Duration::from_millis(ms)).await
    }

    /// Wait for a condition to be true (async version)
    pub async fn wait_until_async<F>(&mut self, condition: F) -> &mut Self
    where
        F: Fn(&Buffer) -> bool,
    {
        let start = std::time::Instant::now();
        let timeout = Duration::from_millis(self.config.timeout_ms);

        while !condition(self.app.buffer()) {
            if start.elapsed() >= timeout {
                panic!("wait_until_async timed out after {:?}", timeout);
            }
            #[cfg(feature = "async")]
            {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
            #[cfg(not(feature = "async"))]
            {
                std::thread::sleep(Duration::from_millis(10));
            }
            self.app.render();
        }

        self
    }

    /// Run an async test with the pilot
    pub fn run_async<F, Fut>(&mut self, f: F)
    where
        F: FnOnce(&mut Self) -> Fut,
        Fut: std::future::Future<Output = ()>,
    {
        #[cfg(feature = "async")]
        {
            match tokio::runtime::Runtime::new() {
                Ok(rt) => rt.block_on(f(self)),
                Err(e) => panic!("Failed to create async runtime: {}", e),
            }
        }
        #[cfg(not(feature = "async"))]
        {
            // Without async feature, just call the future in a blocking way
            // This is a simplified approach - the user should enable async feature
            let _ = f;
            panic!("Async support requires the 'async' feature to be enabled");
        }
    }
}