cactui 0.1.0

Terminal-based interactive prompts and key menus for CLI applications
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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
// TUI Inline Demo - Interactive frame description collection using unified key menu system
// This demonstrates the same playback workflow as playback-demo but using a reusable key menu framework

use anyhow::Result;
use cactui::inline_prompt::{InlineInputOpts, InlinePrompt};
use crossterm::{event::KeyCode, style::Color};

use std::collections::HashMap;

/// Simulated frame data with content and timing
#[derive(Debug, Clone)]
struct DemoFrame {
    content: String,
}

/// Channel state for frame display
#[derive(Debug, Clone)]
struct ChannelState {
    fg_red: bool,
    fg_green: bool,
    fg_blue: bool,
    bg_red: bool,
    bg_green: bool,
    bg_blue: bool,
    modifiers: bool,
}

impl ChannelState {
    fn new() -> Self {
        Self {
            fg_red: false,
            fg_green: false,
            fg_blue: false,
            bg_red: false,
            bg_green: false,
            bg_blue: false,
            modifiers: false,
        }
    }

    fn format_channels(&self) -> String {
        if !self.fg_red
            && !self.fg_green
            && !self.fg_blue
            && !self.bg_red
            && !self.bg_green
            && !self.bg_blue
            && !self.modifiers
        {
            return "(none)".to_string();
        }

        let mut result = String::new();

        // Foreground RGB
        let mut fg_parts = Vec::new();
        if self.fg_red {
            fg_parts.push("R");
        }
        if self.fg_green {
            fg_parts.push("G");
        }
        if self.fg_blue {
            fg_parts.push("B");
        }
        result.push_str(&fg_parts.join(""));

        // Background RGB (only if any background colors are set)
        if self.bg_red || self.bg_green || self.bg_blue {
            result.push('/');
            let mut bg_parts = Vec::new();
            if self.bg_red {
                bg_parts.push("R");
            }
            if self.bg_green {
                bg_parts.push("G");
            }
            if self.bg_blue {
                bg_parts.push("B");
            }
            result.push_str(&bg_parts.join(""));
        }

        // Modifiers
        if self.modifiers {
            result.push('+');
        }

        if result.is_empty() {
            "(none)".to_string()
        } else {
            result
        }
    }
}

/// Collected descriptions for the demo
#[derive(Debug, Clone)]
struct PlaybackSession {
    recording_description: Option<String>,
    frame_descriptions: HashMap<usize, String>, // frame num -> desc
    frame_channels: HashMap<usize, ChannelState>, // frame num -> channel state
    frames: Vec<DemoFrame>,
    current_frame_num: usize,
}

impl PlaybackSession {
    fn new() -> Self {
        Self {
            recording_description: None,
            frame_descriptions: HashMap::new(),
            frame_channels: HashMap::new(),
            frames: create_demo_frames(),
            current_frame_num: 0,
        }
    }

    fn get_current_channels(&self) -> &ChannelState {
        static DEFAULT_CHANNELS: ChannelState = ChannelState {
            fg_red: false,
            fg_green: false,
            fg_blue: false,
            bg_red: false,
            bg_green: false,
            bg_blue: false,
            modifiers: false,
        };
        self.frame_channels
            .get(&self.current_frame_num)
            .unwrap_or(&DEFAULT_CHANNELS)
    }

    fn get_current_channels_mut(&mut self) -> &mut ChannelState {
        self.frame_channels
            .entry(self.current_frame_num)
            .or_insert_with(ChannelState::new)
    }

    /// Collect overall recording description
    fn collect_recording_description(&mut self) -> Result<()> {
        println!("Interactive Recording Playback");
        println!("═══════════════════════════════════");
        println!();

        let description = InlinePrompt::input("Recording description:", None)?;
        if !description.is_empty() {
            self.recording_description = Some(description);
        }

        Ok(())
    }

    /// Run the interactive playback with frame descriptions
    fn run_interactive_playback(&mut self) -> Result<()> {
        let collect_descriptions =
            InlinePrompt::confirm("Collect descriptions for each frame?", true)?;

        if !collect_descriptions {
            println!("⏭️  Skipping frame descriptions");
            return Ok(());
        }

        println!();
        println!("🎥 Starting frame-by-frame playback...");
        println!("Use keys to navigate, Enter to continue");
        println!();
        println!();

        let inline_menu = create_inline_frame_menu();

        for frame_num in 0..self.frames.len() {
            // Set current frame number in session
            self.current_frame_num = frame_num;

            inline_menu.run_menu(self)?;

            println!();
            println!();
        }

        println!("✅ Playback complete!");
        Ok(())
    }
}

/// Calculate how many lines a description will take when displayed
fn calculate_description_lines(description: &str) -> Result<usize> {
    let full_text = format!("Description: {}", description);
    cactui::text_wrapping::calculate_text_lines(&full_text)
}

/// Get frame header lines with current state
fn get_frame_header_lines(session: &PlaybackSession) -> Vec<String> {
    let mut lines = Vec::new();

    // Add the frame content (split on newlines)
    if let Some(current_frame) = session.frames.get(session.current_frame_num) {
        for line in current_frame.content.lines() {
            lines.push(line.to_string());
        }

        let channels = session.get_current_channels();

        // Add channel debug grids if any channels are active
        if channels.fg_red
            || channels.fg_green
            || channels.fg_blue
            || channels.bg_red
            || channels.bg_green
            || channels.bg_blue
            || channels.modifiers
        {
            lines.push("=== FRAME CHANNELS ===".to_string());

            if channels.fg_red {
                lines.push("--- Foreground Red ---".to_string());
                lines.push("1│255..............".to_string());
                lines.push("2│255,128............,255".to_string());
                lines.push("3│255,128............,255".to_string());
                lines.push("4│255,128............,255".to_string());
                lines.push("5│255,128............,255".to_string());
                lines.push("6│255,128............,255".to_string());
                lines.push("7│255..............".to_string());
                lines.push("8│128..............".to_string());
            }

            if channels.fg_green {
                lines.push("--- Foreground Green ---".to_string());
                lines.push("1│0,255,0..............".to_string());
                lines.push("2│0,255,0..............".to_string());
                lines.push("3│0,255,0..............".to_string());
                lines.push("4│0,255,0..............".to_string());
                lines.push("5│0,255,0..............".to_string());
                lines.push("6│0,255,0..............".to_string());
                lines.push("7│0,255,0..............".to_string());
                lines.push("8│0,255,0..............".to_string());
            }

            if channels.fg_blue {
                lines.push("--- Foreground Blue ---".to_string());
                lines.push("1│0,0,255..............".to_string());
                lines.push("2│0,0,255..............".to_string());
                lines.push("3│0,0,255..............".to_string());
                lines.push("4│0,0,255..............".to_string());
                lines.push("5│0,0,255..............".to_string());
                lines.push("6│0,0,255..............".to_string());
                lines.push("7│0,0,255..............".to_string());
                lines.push("8│0,0,255..............".to_string());
            }

            if channels.bg_red {
                lines.push("--- Background Red ---".to_string());
                lines.push("1│255,0,0..............".to_string());
                lines.push("2│255,0,0..............".to_string());
                lines.push("3│255,0,0..............".to_string());
                lines.push("4│255,0,0..............".to_string());
                lines.push("5│255,0,0..............".to_string());
                lines.push("6│255,0,0..............".to_string());
                lines.push("7│255,0,0..............".to_string());
                lines.push("8│255,0,0..............".to_string());
            }

            if channels.bg_green {
                lines.push("--- Background Green ---".to_string());
                lines.push("1│0,255,0..............".to_string());
                lines.push("2│0,255,0..............".to_string());
                lines.push("3│0,255,0..............".to_string());
                lines.push("4│0,255,0..............".to_string());
                lines.push("5│0,255,0..............".to_string());
                lines.push("6│0,255,0..............".to_string());
                lines.push("7│0,255,0..............".to_string());
                lines.push("8│0,255,0..............".to_string());
            }

            if channels.bg_blue {
                lines.push("--- Background Blue ---".to_string());
                lines.push("1│0..............".to_string());
                lines.push("2│0..............".to_string());
                lines.push("3│0..............".to_string());
                lines.push("4│0..............".to_string());
                lines.push("5│0..............".to_string());
                lines.push("6│0..............".to_string());
                lines.push("7│0..............".to_string());
                lines.push("8│0..............".to_string());
            }

            lines.push("=== END FRAME 0 ===".to_string());
        }
    }

    // Show current state - Channels FIRST, then Description LAST
    lines.push(format!(
        "Channels: {}",
        session.get_current_channels().format_channels()
    ));

    let desc = session
        .frame_descriptions
        .get(&session.current_frame_num)
        .map(|s| s.clone())
        .unwrap_or_else(|| "(none)".to_string());

    lines.push(format!("Description: {}", desc));

    lines
}

/// Create the main frame menu configuration
fn create_inline_frame_menu() -> cactui::KeyMenuConfig<PlaybackSession> {
    cactui::KeyMenuConfig {
        header_lines: Some(Box::new(|session: &PlaybackSession| {
            get_frame_header_lines(session)
        })),
        items: vec![
            cactui::KeyMenuItem {
                key: KeyCode::Char('e'),
                description: "edit description".to_string(),
                color: Some(Color::Cyan),
                action: cactui::MenuAction::Callback {
                    callback: Box::new(|session, line_counts| {
                        // Get current description for placeholder
                        let current_desc = session
                            .frame_descriptions
                            .get(&session.current_frame_num)
                            .map(|s| s.as_str());

                        // Calculate how many lines the current description takes up
                        let current_description = session
                            .frame_descriptions
                            .get(&session.current_frame_num)
                            .map(|s| s.as_str())
                            .unwrap_or("(none)");
                        let current_lines_to_clear =
                            calculate_description_lines(current_description)?;

                        // Clear the description lines so we can draw over them with our InlinePrompt
                        cactui::inline_keymenu::clear_lines(current_lines_to_clear)?;
                        // Call the inline input with escape-to-exit mode for multi-line descriptions
                        let mut opts = InlineInputOpts::new().escape_to_exit();
                        if current_desc.is_some() {
                            opts = opts.placeholder(current_desc.unwrap());
                        };
                        let new_desc = InlinePrompt::input("Description:", Some(opts))?;
                        // Update line_counts.header to reflect the new header size
                        let new_lines_to_clear = calculate_description_lines(&new_desc)?;
                        if new_lines_to_clear > current_lines_to_clear {
                            line_counts.header += new_lines_to_clear - current_lines_to_clear
                        } else if new_lines_to_clear < current_lines_to_clear {
                            line_counts.header = line_counts
                                .header
                                .saturating_sub(current_lines_to_clear - new_lines_to_clear)
                        }

                        // Update description in session
                        if !new_desc.is_empty() {
                            session
                                .frame_descriptions
                                .insert(session.current_frame_num, new_desc);
                        } else {
                            session
                                .frame_descriptions
                                .remove(&session.current_frame_num);
                        }

                        Ok(cactui::MenuResult::Stay)
                    }),
                    clear_menu: true,
                },
            },
            cactui::KeyMenuItem {
                key: KeyCode::Char('c'),
                description: "channels".to_string(),
                color: Some(Color::Cyan),
                action: cactui::MenuAction::Submenu(cactui::KeyMenuConfig {
                    header_lines: Some(Box::new(|session: &PlaybackSession| {
                        get_frame_header_lines(session)
                    })),
                    items: vec![
                        cactui::KeyMenuItem {
                            key: KeyCode::Char('1'),
                            description: "fg red".to_string(),
                            color: Some(Color::Red),
                            action: cactui::MenuAction::Callback {
                                callback: Box::new(|session, _| {
                                    session.get_current_channels_mut().fg_red =
                                        !session.get_current_channels().fg_red;
                                    Ok(cactui::MenuResult::Stay)
                                }),
                                clear_menu: false,
                            },
                        },
                        cactui::KeyMenuItem {
                            key: KeyCode::Char('2'),
                            description: "fg green".to_string(),
                            color: Some(Color::Green),
                            action: cactui::MenuAction::Callback {
                                callback: Box::new(|session, _| {
                                    session.get_current_channels_mut().fg_green =
                                        !session.get_current_channels().fg_green;
                                    Ok(cactui::MenuResult::Stay)
                                }),
                                clear_menu: false,
                            },
                        },
                        cactui::KeyMenuItem {
                            key: KeyCode::Char('3'),
                            description: "fg blue".to_string(),
                            color: Some(Color::Blue),
                            action: cactui::MenuAction::Callback {
                                callback: Box::new(|session, _| {
                                    session.get_current_channels_mut().fg_blue =
                                        !session.get_current_channels().fg_blue;
                                    Ok(cactui::MenuResult::Stay)
                                }),
                                clear_menu: false,
                            },
                        },
                        cactui::KeyMenuItem {
                            key: KeyCode::Char('4'),
                            description: "bg red".to_string(),
                            color: Some(Color::Red),
                            action: cactui::MenuAction::Callback {
                                callback: Box::new(|session, _| {
                                    session.get_current_channels_mut().bg_red =
                                        !session.get_current_channels().bg_red;
                                    Ok(cactui::MenuResult::Stay)
                                }),
                                clear_menu: false,
                            },
                        },
                        cactui::KeyMenuItem {
                            key: KeyCode::Char('5'),
                            description: "bg green".to_string(),
                            color: Some(Color::Green),
                            action: cactui::MenuAction::Callback {
                                callback: Box::new(|session, _| {
                                    session.get_current_channels_mut().bg_green =
                                        !session.get_current_channels().bg_green;
                                    Ok(cactui::MenuResult::Stay)
                                }),
                                clear_menu: false,
                            },
                        },
                        cactui::KeyMenuItem {
                            key: KeyCode::Char('6'),
                            description: "bg blue".to_string(),
                            color: Some(Color::Blue),
                            action: cactui::MenuAction::Callback {
                                callback: Box::new(|session, _| {
                                    session.get_current_channels_mut().bg_blue =
                                        !session.get_current_channels().bg_blue;
                                    Ok(cactui::MenuResult::Stay)
                                }),
                                clear_menu: false,
                            },
                        },
                        cactui::KeyMenuItem {
                            key: KeyCode::Char('7'),
                            description: "mods".to_string(),
                            color: Some(Color::White),
                            action: cactui::MenuAction::Callback {
                                callback: Box::new(|session, _| {
                                    session.get_current_channels_mut().modifiers =
                                        !session.get_current_channels().modifiers;
                                    Ok(cactui::MenuResult::Stay)
                                }),
                                clear_menu: false,
                            },
                        },
                        cactui::KeyMenuItem {
                            key: KeyCode::Esc,
                            description: "return".to_string(),
                            color: None,
                            action: cactui::MenuAction::Exit,
                        },
                    ],
                    should_loop: true,
                }),
            },
            cactui::KeyMenuItem {
                key: KeyCode::Enter,
                description: "next frame".to_string(),
                color: Some(Color::Cyan),
                action: cactui::MenuAction::ExitKeepHeader,
            },
        ],
        should_loop: true,
    }
}

/// Create demo frames with placeholder content
fn create_demo_frames() -> Vec<DemoFrame> {
    vec![
        DemoFrame {
            content: format!(
                "{}\n{}",
                "=== DEBUGTERM FRAME 0 (22ms) ===",
                " 1│┌ 2 (FOCUSED)────────────────┐\n \
                  2││>> WIDGET 1 <<              │\n \
                  3││Welcome to i3-style TUI!    │\n \
                  4││                            │\n \
                  5││Keys:                       │\n \
                  6││- Space: New widget         │\n \
                  7││- Alt+h/Alt+v: Split horizon│\n \
                  8││- Alt+e: Toggle layout      │\n \
                  9││- Alt-Arrows: Navigate      │\n\
                 10││- Alt+Shift+Arrows: Move    │\n\
                 11││- Tab: Cycle focus          │\n\
                 12││- s: Seal/unseal container  │\n\
                 13││- u: Update content         │\n\
                 14││- r: Reset content          │\n\
                 15││- x: Remove widget          │\n\
                 16││- q: Quit                   │\n\
                 17││                            │\n\
                 18││                            │\n\
                 19│└────────────────────────────┘\n\
                 20│-- INPUT --\n\
                === END FRAME 0 ==="
            ),
        },
        DemoFrame {
            content: format!(
                "{}\n{}",
                "=== DEBUGTERM FRAME 5 (122ms) ===",
                " 1│┌ 2──────────────────────────┐\n \
                  2││>> WIDGET 1 <<              │\n \
                  3││Welcome to i3-style TUI!    │\n \
                  4││                            │\n \
                  5││Keys:                       │\n \
                  6││- Space: New widget         │\n \
                  7││- Alt+h/Alt+v: Split horizon│\n \
                  8││- Alt+e: Toggle layout      │\n \
                  9││- Alt-Arrows: Navigate      │\n\
                 10│└────────────────────────────┘\n\
                 11│┌ 3 (FOCUSED)────────────────┐\n\
                 12││Widget 3                    │\n\
                 13││                            │\n\
                 14││This is widget number 3     │\n\
                 15││                            │\n\
                 16││                            │\n\
                 17││                            │\n\
                 18││                            │\n\
                 19│└────────────────────────────┘\n\
                 20│-- INPUT --\n\
                === END FRAME 5 ==="
            ),
        },
        DemoFrame {
            content: format!(
                "{}\n{}",
                "=== DEBUGTERM FRAME 10 (324ms) ===",
                " 1│┌ 2─────────────┐┌ 4 (FOCUSED)──┐\n \
                  2││>> WIDGET 1 << ││Widget 4      │\n \
                  3││Welcome to i3- ││              │\n \
                  4││               ││This is widget│\n \
                  5││Keys:          ││number 4      │\n \
                  6││- Space: New w ││              │\n \
                  7││- Alt+h/Alt+v: ││              │\n \
                  8││- Alt+e: Toggl ││              │\n \
                  9││- Alt-Arrows:  ││              │\n\
                 10│└───────────────┘└──────────────┘\n\
                 11│┌ 3──────────────────────────────┐\n\
                 12││Widget 3                        │\n\
                 13││                                │\n\
                 14││This is widget number 3         │\n\
                 15││                                │\n\
                 16││                                │\n\
                 17││                                │\n\
                 18││                                │\n\
                 19│└────────────────────────────────┘\n\
                 20│-- INPUT --\n\
                === END FRAME 10 ==="
            ),
        },
    ]
}

fn main() -> Result<()> {
    let mut session = PlaybackSession::new();

    // Step 1: Collect overall recording description
    session.collect_recording_description()?;

    // Step 2: Run interactive playback with frame descriptions
    session.run_interactive_playback()?;

    Ok(())
}