rnk 0.17.3

A React-like declarative terminal UI framework for Rust, inspired by Ink
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
//! Unified command type for side effects and typed messages.
//!
//! `Cmd<M>` is the single command representation in rnk. Use `Cmd<()>`
//! for side-effect-only flows, and `Cmd<MyMsg>` when you want commands to
//! produce typed messages.

use std::any::Any;
use std::future::Future;
use std::pin::Pin;
use std::time::{Duration, Instant};

use super::{ExecConfig, ExecResult};

/// Application-level messages handled by the framework.
#[derive(Debug, Clone, Default)]
pub enum AppMsg {
    /// Window/terminal resize event.
    WindowResize { width: u16, height: u16 },
    /// Keyboard input (raw key string).
    KeyInput(String),
    /// Timer tick with timestamp.
    Tick(Instant),
    /// Focus changed to a new element.
    FocusChanged(Option<String>),
    /// Blur event (element lost focus).
    Blur,
    /// No-op message.
    #[default]
    None,
}

/// A boxed message that can hold any type.
pub struct BoxedMsg(Box<dyn Any + Send + 'static>);

impl BoxedMsg {
    /// Create a new boxed message.
    pub fn new<M: Any + Send + 'static>(msg: M) -> Self {
        BoxedMsg(Box::new(msg))
    }

    /// Try to downcast to a specific message type.
    pub fn downcast<M: Any + 'static>(self) -> Result<M, Self> {
        match self.0.downcast::<M>() {
            Ok(msg) => Ok(*msg),
            Err(boxed) => Err(BoxedMsg(boxed)),
        }
    }

    /// Try to get a reference to the inner message.
    pub fn downcast_ref<M: Any + 'static>(&self) -> Option<&M> {
        self.0.downcast_ref::<M>()
    }

    /// Check if this message is of a specific type.
    pub fn is<M: Any + 'static>(&self) -> bool {
        self.0.is::<M>()
    }
}

impl std::fmt::Debug for BoxedMsg {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "BoxedMsg(...)")
    }
}

/// Unified command type.
///
/// - `Cmd<()>`: side-effect commands used by runtime/hooks.
/// - `Cmd<M>`: typed commands that produce messages of type `M`.
#[derive(Default)]
pub enum Cmd<M = ()>
where
    M: Send + 'static,
{
    /// No-op command.
    #[default]
    None,

    /// Execute multiple commands concurrently.
    Batch(Vec<Cmd<M>>),

    /// Execute multiple commands sequentially.
    Sequence(Vec<Cmd<M>>),

    /// Execute an async task that produces a message.
    Perform {
        future: Pin<Box<dyn Future<Output = M> + Send + 'static>>,
    },

    /// Sleep for a duration, then execute another command.
    Sleep {
        duration: Duration,
        then: Box<Cmd<M>>,
    },

    /// Produce a message after waiting for a duration.
    Tick {
        duration: Duration,
        msg_fn: Box<dyn FnOnce(Instant) -> M + Send + 'static>,
    },

    /// Produce a message aligned to system clock boundaries.
    Every {
        duration: Duration,
        msg_fn: Box<dyn FnOnce(Instant) -> M + Send + 'static>,
    },

    /// Execute an external interactive process.
    Exec {
        config: ExecConfig,
        msg_fn: Box<dyn FnOnce(ExecResult) -> M + Send + 'static>,
    },

    /// Clear the terminal screen.
    ClearScreen,

    /// Hide the terminal cursor.
    HideCursor,

    /// Show the terminal cursor.
    ShowCursor,

    /// Set the terminal window title.
    SetWindowTitle(String),

    /// Request the current window size.
    WindowSize,

    /// Enter alternate screen buffer.
    EnterAltScreen,

    /// Exit alternate screen buffer.
    ExitAltScreen,

    /// Enable mouse support.
    EnableMouse,

    /// Disable mouse support.
    DisableMouse,

    /// Enable bracketed paste mode.
    EnableBracketedPaste,

    /// Disable bracketed paste mode.
    DisableBracketedPaste,
}

impl<M> Cmd<M>
where
    M: Send + 'static,
{
    /// Create a no-op command.
    pub fn none() -> Self {
        Cmd::None
    }

    /// Create a batch command that executes multiple commands concurrently.
    pub fn batch(cmds: impl IntoIterator<Item = Cmd<M>>) -> Self {
        let mut cmds: Vec<Cmd<M>> = cmds
            .into_iter()
            .filter(|cmd| !matches!(cmd, Cmd::None))
            .collect();

        match cmds.len() {
            0 => Cmd::None,
            1 => cmds.pop().unwrap(),
            _ => Cmd::Batch(cmds),
        }
    }

    /// Create a sequence command that executes multiple commands in order.
    pub fn sequence(cmds: impl IntoIterator<Item = Cmd<M>>) -> Self {
        let mut cmds: Vec<Cmd<M>> = cmds
            .into_iter()
            .filter(|cmd| !matches!(cmd, Cmd::None))
            .collect();

        match cmds.len() {
            0 => Cmd::None,
            1 => cmds.pop().unwrap(),
            _ => Cmd::Sequence(cmds),
        }
    }

    /// Create a command that executes an async function and produces a message.
    pub fn perform<F, Fut>(f: F) -> Self
    where
        F: FnOnce() -> Fut + Send + 'static,
        Fut: Future<Output = M> + Send + 'static,
    {
        Cmd::Perform {
            future: Box::pin(async move { f().await }),
        }
    }

    /// Create a command that sleeps for a duration.
    pub fn sleep(duration: Duration) -> Self {
        Cmd::Sleep {
            duration,
            then: Box::new(Cmd::None),
        }
    }

    /// Create a tick command that produces a message after a duration.
    pub fn tick<F>(duration: Duration, msg_fn: F) -> Self
    where
        F: FnOnce(Instant) -> M + Send + 'static,
    {
        Cmd::Tick {
            duration,
            msg_fn: Box::new(msg_fn),
        }
    }

    /// Create a command that ticks in sync with the system clock.
    pub fn every<F>(duration: Duration, msg_fn: F) -> Self
    where
        F: FnOnce(Instant) -> M + Send + 'static,
    {
        Cmd::Every {
            duration,
            msg_fn: Box::new(msg_fn),
        }
    }

    /// Execute an external interactive process.
    pub fn exec<F>(config: ExecConfig, msg_fn: F) -> Self
    where
        F: FnOnce(ExecResult) -> M + Send + 'static,
    {
        Cmd::Exec {
            config,
            msg_fn: Box::new(msg_fn),
        }
    }

    /// Execute an external command with simple arguments.
    pub fn exec_cmd<F>(program: &str, args: &[&str], msg_fn: F) -> Self
    where
        F: FnOnce(ExecResult) -> M + Send + 'static,
    {
        let config = ExecConfig::new(program).args(args.iter().map(|s| s.to_string()));
        Cmd::exec(config, msg_fn)
    }

    /// Clear the terminal screen.
    pub fn clear_screen() -> Self {
        Cmd::ClearScreen
    }

    /// Hide the terminal cursor.
    pub fn hide_cursor() -> Self {
        Cmd::HideCursor
    }

    /// Show the terminal cursor.
    pub fn show_cursor() -> Self {
        Cmd::ShowCursor
    }

    /// Set the terminal window title.
    pub fn set_window_title(title: impl Into<String>) -> Self {
        Cmd::SetWindowTitle(title.into())
    }

    /// Request the current window size.
    pub fn window_size() -> Self {
        Cmd::WindowSize
    }

    /// Enter alternate screen buffer.
    pub fn enter_alt_screen() -> Self {
        Cmd::EnterAltScreen
    }

    /// Exit alternate screen buffer.
    pub fn exit_alt_screen() -> Self {
        Cmd::ExitAltScreen
    }

    /// Enable mouse support.
    pub fn enable_mouse() -> Self {
        Cmd::EnableMouse
    }

    /// Disable mouse support.
    pub fn disable_mouse() -> Self {
        Cmd::DisableMouse
    }

    /// Enable bracketed paste mode.
    pub fn enable_bracketed_paste() -> Self {
        Cmd::EnableBracketedPaste
    }

    /// Disable bracketed paste mode.
    pub fn disable_bracketed_paste() -> Self {
        Cmd::DisableBracketedPaste
    }

    /// Chain this command with another command.
    pub fn and_then(self, next: Cmd<M>) -> Self {
        match self {
            Cmd::None => next,
            Cmd::Sleep { duration, then } => {
                let chained = then.and_then(next);
                Cmd::Sleep {
                    duration,
                    then: Box::new(chained),
                }
            }
            other => Cmd::batch(vec![other, next]),
        }
    }

    /// Check if this command is a no-op.
    pub fn is_none(&self) -> bool {
        matches!(self, Cmd::None)
    }

    /// Map command messages to a different type.
    pub fn map<N, F>(self, f: F) -> Cmd<N>
    where
        N: Send + 'static,
        F: FnOnce(M) -> N + Send + 'static + Clone,
    {
        match self {
            Cmd::None => Cmd::None,
            Cmd::Batch(cmds) => Cmd::Batch(cmds.into_iter().map(|c| c.map(f.clone())).collect()),
            Cmd::Sequence(cmds) => {
                Cmd::Sequence(cmds.into_iter().map(|c| c.map(f.clone())).collect())
            }
            Cmd::Perform { future } => Cmd::Perform {
                future: Box::pin(async move {
                    let msg = future.await;
                    f(msg)
                }),
            },
            Cmd::Sleep { duration, then } => Cmd::Sleep {
                duration,
                then: Box::new(then.map(f)),
            },
            Cmd::Tick { duration, msg_fn } => Cmd::Tick {
                duration,
                msg_fn: Box::new(move |t| f(msg_fn(t))),
            },
            Cmd::Every { duration, msg_fn } => Cmd::Every {
                duration,
                msg_fn: Box::new(move |t| f(msg_fn(t))),
            },
            Cmd::Exec { config, msg_fn } => Cmd::Exec {
                config,
                msg_fn: Box::new(move |r| f(msg_fn(r))),
            },
            Cmd::ClearScreen => Cmd::ClearScreen,
            Cmd::HideCursor => Cmd::HideCursor,
            Cmd::ShowCursor => Cmd::ShowCursor,
            Cmd::SetWindowTitle(title) => Cmd::SetWindowTitle(title),
            Cmd::WindowSize => Cmd::WindowSize,
            Cmd::EnterAltScreen => Cmd::EnterAltScreen,
            Cmd::ExitAltScreen => Cmd::ExitAltScreen,
            Cmd::EnableMouse => Cmd::EnableMouse,
            Cmd::DisableMouse => Cmd::DisableMouse,
            Cmd::EnableBracketedPaste => Cmd::EnableBracketedPaste,
            Cmd::DisableBracketedPaste => Cmd::DisableBracketedPaste,
        }
    }
}

impl<M> std::fmt::Debug for Cmd<M>
where
    M: Send + 'static,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Cmd::None => write!(f, "Cmd::None"),
            Cmd::Batch(cmds) => f.debug_tuple("Cmd::Batch").field(cmds).finish(),
            Cmd::Sequence(cmds) => f.debug_tuple("Cmd::Sequence").field(cmds).finish(),
            Cmd::Perform { .. } => write!(f, "Cmd::Perform {{ ... }}"),
            Cmd::Sleep { duration, then } => f
                .debug_struct("Cmd::Sleep")
                .field("duration", duration)
                .field("then", then)
                .finish(),
            Cmd::Tick { duration, .. } => f
                .debug_struct("Cmd::Tick")
                .field("duration", duration)
                .finish(),
            Cmd::Every { duration, .. } => f
                .debug_struct("Cmd::Every")
                .field("duration", duration)
                .finish(),
            Cmd::Exec { config, .. } => {
                f.debug_struct("Cmd::Exec").field("config", config).finish()
            }
            Cmd::ClearScreen => write!(f, "Cmd::ClearScreen"),
            Cmd::HideCursor => write!(f, "Cmd::HideCursor"),
            Cmd::ShowCursor => write!(f, "Cmd::ShowCursor"),
            Cmd::SetWindowTitle(title) => {
                f.debug_tuple("Cmd::SetWindowTitle").field(title).finish()
            }
            Cmd::WindowSize => write!(f, "Cmd::WindowSize"),
            Cmd::EnterAltScreen => write!(f, "Cmd::EnterAltScreen"),
            Cmd::ExitAltScreen => write!(f, "Cmd::ExitAltScreen"),
            Cmd::EnableMouse => write!(f, "Cmd::EnableMouse"),
            Cmd::DisableMouse => write!(f, "Cmd::DisableMouse"),
            Cmd::EnableBracketedPaste => write!(f, "Cmd::EnableBracketedPaste"),
            Cmd::DisableBracketedPaste => write!(f, "Cmd::DisableBracketedPaste"),
        }
    }
}

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

    #[derive(Debug, PartialEq)]
    enum TestMsg {
        Loaded(String),
        Tick(u64),
    }

    #[test]
    fn test_cmd_none_default() {
        let cmd: Cmd<TestMsg> = Cmd::none();
        assert!(cmd.is_none());

        let default_cmd: Cmd<TestMsg> = Cmd::default();
        assert!(default_cmd.is_none());
    }

    #[test]
    fn test_cmd_batch_and_sequence() {
        let batch: Cmd<TestMsg> = Cmd::batch(vec![
            Cmd::sleep(Duration::from_millis(10)),
            Cmd::sleep(Duration::from_millis(20)),
        ]);
        assert!(matches!(batch, Cmd::Batch(_)));

        let seq: Cmd<TestMsg> = Cmd::sequence(vec![
            Cmd::sleep(Duration::from_millis(10)),
            Cmd::sleep(Duration::from_millis(20)),
        ]);
        assert!(matches!(seq, Cmd::Sequence(_)));
    }

    #[test]
    fn test_cmd_perform_tick_every_exec() {
        let perform: Cmd<TestMsg> = Cmd::perform(|| async { TestMsg::Loaded("ok".into()) });
        assert!(matches!(perform, Cmd::Perform { .. }));

        let tick: Cmd<TestMsg> = Cmd::tick(Duration::from_secs(1), |_| TestMsg::Tick(1));
        assert!(matches!(tick, Cmd::Tick { .. }));

        let every: Cmd<TestMsg> = Cmd::every(Duration::from_secs(1), |_| TestMsg::Tick(2));
        assert!(matches!(every, Cmd::Every { .. }));

        let exec: Cmd<TestMsg> = Cmd::exec(ExecConfig::new("echo").arg("hi"), |_| {
            TestMsg::Loaded("done".into())
        });
        assert!(matches!(exec, Cmd::Exec { .. }));
    }

    #[test]
    fn test_cmd_and_then_chains_sleep() {
        let cmd: Cmd<TestMsg> = Cmd::sleep(Duration::from_secs(1))
            .and_then(Cmd::sleep(Duration::from_secs(2)))
            .and_then(Cmd::sleep(Duration::from_secs(3)));

        assert!(matches!(cmd, Cmd::Sleep { .. }));
    }

    #[test]
    fn test_cmd_map_message_type() {
        #[derive(Debug, PartialEq)]
        enum ParentMsg {
            Child(TestMsg),
        }

        let child_cmd: Cmd<TestMsg> = Cmd::batch(vec![
            Cmd::sleep(Duration::from_secs(1)),
            Cmd::perform(|| async { TestMsg::Loaded("data".into()) }),
        ]);

        let parent_cmd: Cmd<ParentMsg> = child_cmd.map(ParentMsg::Child);
        assert!(matches!(parent_cmd, Cmd::Batch(_)));
    }

    #[test]
    fn test_terminal_cmd_variants_exist() {
        assert!(matches!(Cmd::<()>::clear_screen(), Cmd::ClearScreen));
        assert!(matches!(Cmd::<()>::hide_cursor(), Cmd::HideCursor));
        assert!(matches!(Cmd::<()>::show_cursor(), Cmd::ShowCursor));
        assert!(matches!(Cmd::<()>::window_size(), Cmd::WindowSize));
        assert!(matches!(Cmd::<()>::enter_alt_screen(), Cmd::EnterAltScreen));
        assert!(matches!(Cmd::<()>::exit_alt_screen(), Cmd::ExitAltScreen));
        assert!(matches!(Cmd::<()>::enable_mouse(), Cmd::EnableMouse));
        assert!(matches!(Cmd::<()>::disable_mouse(), Cmd::DisableMouse));
        assert!(matches!(
            Cmd::<()>::enable_bracketed_paste(),
            Cmd::EnableBracketedPaste
        ));
        assert!(matches!(
            Cmd::<()>::disable_bracketed_paste(),
            Cmd::DisableBracketedPaste
        ));
    }

    #[test]
    fn test_app_msg_default() {
        assert!(matches!(AppMsg::default(), AppMsg::None));
    }

    #[test]
    fn test_boxed_msg_downcast() {
        let msg = BoxedMsg::new(TestMsg::Tick(42));
        assert!(msg.is::<TestMsg>());

        let downcasted = msg.downcast::<TestMsg>();
        assert!(downcasted.is_ok());
        assert_eq!(downcasted.unwrap(), TestMsg::Tick(42));
    }
}