presentar-terminal 0.3.5

Terminal backend for Presentar UI framework with zero-allocation rendering
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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
//! `GutterCursor` atomic widget.
//!
//! Tufte-style selection indicator for row-based navigation.
//! Reference: SPEC-024 Appendix I (Atomic Widget Mandate).
//!
//! # Falsification Criteria
//! - F-ATOM-GUT-001: Y-position MUST match selected row exactly.
//! - F-ATOM-GUT-002: Cursor MUST be visible when selection is within viewport.

use presentar_core::{
    Brick, BrickAssertion, BrickBudget, BrickVerification, Canvas, Color, Constraints, Event,
    LayoutResult, Point, Rect, Size, TextStyle, TypeId, Widget,
};
use std::any::Any;
use std::time::Duration;

/// Cursor style variants.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum CursorStyle {
    /// Triangle pointer (▶)
    #[default]
    Triangle,
    /// Line indicator (│)
    Line,
    /// Dot (●)
    Dot,
    /// Arrow (→)
    Arrow,
    /// Bracket ([)
    Bracket,
    /// Double arrow (»)
    DoubleArrow,
}

impl CursorStyle {
    /// Get the character for this cursor style.
    #[must_use]
    pub const fn char(&self) -> char {
        match self {
            Self::Triangle => '',
            Self::Line => '',
            Self::Dot => '',
            Self::Arrow => '',
            Self::Bracket => '[',
            Self::DoubleArrow => '»',
        }
    }

    /// Get the width in characters.
    #[must_use]
    pub const fn width(&self) -> usize {
        1 // All styles are single character
    }
}

/// Selection state for the cursor.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SelectionState {
    /// No selection
    #[default]
    None,
    /// Row is selected
    Selected,
    /// Row is focused (keyboard navigation)
    Focused,
    /// Row is both selected and focused
    FocusedSelected,
}

impl SelectionState {
    /// Check if this state indicates selection.
    #[must_use]
    pub const fn is_selected(&self) -> bool {
        matches!(self, Self::Selected | Self::FocusedSelected)
    }

    /// Check if this state indicates focus.
    #[must_use]
    pub const fn is_focused(&self) -> bool {
        matches!(self, Self::Focused | Self::FocusedSelected)
    }
}

/// `GutterCursor` - selection indicator for row-based lists.
///
/// Renders a visual indicator (▶, │, etc.) in the gutter to show
/// which row is currently selected or focused.
#[derive(Debug, Clone)]
pub struct GutterCursor {
    /// Currently selected row (0-indexed, relative to viewport).
    selected_row: Option<usize>,
    /// Total visible rows in viewport.
    visible_rows: usize,
    /// Cursor style.
    style: CursorStyle,
    /// Cursor color when selected.
    selected_color: Color,
    /// Cursor color when focused.
    focused_color: Color,
    /// Selection state per row (optional, for multi-select).
    row_states: Vec<SelectionState>,
    /// Cached bounds.
    bounds: Rect,
}

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

impl GutterCursor {
    /// Create a new gutter cursor.
    #[must_use]
    pub fn new() -> Self {
        Self {
            selected_row: None,
            visible_rows: 0,
            style: CursorStyle::Triangle,
            selected_color: Color::new(0.3, 0.8, 1.0, 1.0), // Cyan
            focused_color: Color::new(1.0, 0.8, 0.2, 1.0),  // Gold
            row_states: Vec::new(),
            bounds: Rect::default(),
        }
    }

    /// Set the selected row (viewport-relative).
    #[must_use]
    pub fn with_selected(mut self, row: usize) -> Self {
        self.selected_row = Some(row);
        self
    }

    /// Clear selection.
    #[must_use]
    pub fn with_no_selection(mut self) -> Self {
        self.selected_row = None;
        self
    }

    /// Set visible row count.
    #[must_use]
    pub fn with_visible_rows(mut self, count: usize) -> Self {
        self.visible_rows = count;
        self
    }

    /// Set cursor style.
    #[must_use]
    pub fn with_style(mut self, style: CursorStyle) -> Self {
        self.style = style;
        self
    }

    /// Set selected color.
    #[must_use]
    pub fn with_selected_color(mut self, color: Color) -> Self {
        self.selected_color = color;
        self
    }

    /// Set focused color.
    #[must_use]
    pub fn with_focused_color(mut self, color: Color) -> Self {
        self.focused_color = color;
        self
    }

    /// Set row states for multi-select.
    #[must_use]
    pub fn with_row_states(mut self, states: Vec<SelectionState>) -> Self {
        self.row_states = states;
        self
    }

    /// Get selection state for a row.
    fn get_row_state(&self, row: usize) -> SelectionState {
        if let Some(selected) = self.selected_row {
            if row == selected {
                return SelectionState::Focused;
            }
        }
        self.row_states
            .get(row)
            .copied()
            .unwrap_or(SelectionState::None)
    }

    /// Get color for a selection state.
    fn color_for_state(&self, state: SelectionState) -> Color {
        match state {
            SelectionState::None => Color::new(0.2, 0.2, 0.2, 1.0), // Dim
            SelectionState::Selected => self.selected_color,
            // Focus takes priority over selection
            SelectionState::Focused | SelectionState::FocusedSelected => self.focused_color,
        }
    }
}

impl Widget for GutterCursor {
    fn type_id(&self) -> TypeId {
        TypeId::of::<Self>()
    }

    fn measure(&self, constraints: Constraints) -> Size {
        // Width is 1 character for the cursor
        // Height is the number of visible rows
        let width = 1.0f32.min(constraints.max_width);
        let height = (self.visible_rows as f32).min(constraints.max_height);
        constraints.constrain(Size::new(width, height))
    }

    fn layout(&mut self, bounds: Rect) -> LayoutResult {
        self.bounds = bounds;
        // Update visible_rows from bounds if not explicitly set
        if self.visible_rows == 0 {
            self.visible_rows = bounds.height as usize;
        }
        LayoutResult {
            size: Size::new(bounds.width, bounds.height),
        }
    }

    fn paint(&self, canvas: &mut dyn Canvas) {
        if self.bounds.width < 1.0 || self.bounds.height < 1.0 {
            return;
        }

        let cursor_char = self.style.char().to_string();
        let visible = self.bounds.height as usize;

        for row in 0..visible {
            let state = self.get_row_state(row);
            let y = self.bounds.y + row as f32;

            // Only draw cursor for non-None states
            if state != SelectionState::None {
                let style = TextStyle {
                    color: self.color_for_state(state),
                    ..Default::default()
                };
                canvas.draw_text(&cursor_char, Point::new(self.bounds.x, y), &style);
            }
        }
    }

    fn event(&mut self, _event: &Event) -> Option<Box<dyn Any + Send>> {
        None
    }

    fn children(&self) -> &[Box<dyn Widget>] {
        &[]
    }

    fn children_mut(&mut self) -> &mut [Box<dyn Widget>] {
        &mut []
    }
}

impl Brick for GutterCursor {
    fn brick_name(&self) -> &'static str {
        "gutter_cursor"
    }

    fn assertions(&self) -> &[BrickAssertion] {
        static ASSERTIONS: &[BrickAssertion] = &[BrickAssertion::max_latency_ms(1)];
        ASSERTIONS
    }

    fn budget(&self) -> BrickBudget {
        BrickBudget::uniform(1)
    }

    fn verify(&self) -> BrickVerification {
        // F-ATOM-GUT-001: Selected row must be within visible bounds
        let row_in_bounds = self.selected_row.map_or(true, |r| r < self.visible_rows);

        // F-ATOM-GUT-002: If selected, cursor must be drawable
        let drawable = self.bounds.width >= 1.0;

        if row_in_bounds && drawable {
            BrickVerification {
                passed: self.assertions().to_vec(),
                failed: vec![],
                verification_time: Duration::from_micros(1),
            }
        } else {
            BrickVerification {
                passed: vec![],
                failed: self
                    .assertions()
                    .iter()
                    .map(|a| (a.clone(), "Selection out of bounds".to_string()))
                    .collect(),
                verification_time: Duration::from_micros(1),
            }
        }
    }

    fn to_html(&self) -> String {
        format!(
            "<div class=\"gutter-cursor\" data-selected=\"{}\"></div>",
            self.selected_row.map(|r| r.to_string()).unwrap_or_default()
        )
    }

    fn to_css(&self) -> String {
        String::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::direct::{CellBuffer, DirectTerminalCanvas};

    // F-ATOM-GUT-001: Y-position matches selected row
    #[test]
    fn test_cursor_y_position() {
        let mut cursor = GutterCursor::new().with_selected(3).with_visible_rows(10);

        cursor.layout(Rect::new(0.0, 0.0, 1.0, 10.0));

        // The cursor should render at row 3
        let state = cursor.get_row_state(3);
        assert_eq!(state, SelectionState::Focused);

        // Other rows should be None
        let state_other = cursor.get_row_state(5);
        assert_eq!(state_other, SelectionState::None);
    }

    // F-ATOM-GUT-002: Cursor visible when in viewport
    #[test]
    fn test_cursor_visibility() {
        let mut cursor = GutterCursor::new().with_selected(5).with_visible_rows(10);

        cursor.layout(Rect::new(0.0, 0.0, 1.0, 10.0));

        let mut buffer = CellBuffer::new(1, 10);
        let mut canvas = DirectTerminalCanvas::new(&mut buffer);
        cursor.paint(&mut canvas);

        // Should render without panic
        // In a real test we'd verify the buffer contents
    }

    // Cursor style characters
    #[test]
    fn test_cursor_styles() {
        assert_eq!(CursorStyle::Triangle.char(), '');
        assert_eq!(CursorStyle::Line.char(), '');
        assert_eq!(CursorStyle::Dot.char(), '');
        assert_eq!(CursorStyle::Arrow.char(), '');
        assert_eq!(CursorStyle::Bracket.char(), '[');
        assert_eq!(CursorStyle::DoubleArrow.char(), '»');
    }

    // Selection state checks
    #[test]
    fn test_selection_state() {
        assert!(!SelectionState::None.is_selected());
        assert!(SelectionState::Selected.is_selected());
        assert!(!SelectionState::Focused.is_selected());
        assert!(SelectionState::FocusedSelected.is_selected());

        assert!(!SelectionState::None.is_focused());
        assert!(!SelectionState::Selected.is_focused());
        assert!(SelectionState::Focused.is_focused());
        assert!(SelectionState::FocusedSelected.is_focused());
    }

    // Multi-select row states
    #[test]
    fn test_multi_select() {
        let cursor = GutterCursor::new()
            .with_row_states(vec![
                SelectionState::None,
                SelectionState::Selected,
                SelectionState::Selected,
                SelectionState::None,
            ])
            .with_visible_rows(4);

        assert_eq!(cursor.get_row_state(0), SelectionState::None);
        assert_eq!(cursor.get_row_state(1), SelectionState::Selected);
        assert_eq!(cursor.get_row_state(2), SelectionState::Selected);
        assert_eq!(cursor.get_row_state(3), SelectionState::None);
    }

    // Brick verification
    #[test]
    fn test_brick_verification() {
        let mut cursor = GutterCursor::new().with_selected(3).with_visible_rows(10);

        cursor.layout(Rect::new(0.0, 0.0, 1.0, 10.0));
        let v = cursor.verify();
        assert!(v.failed.is_empty());
    }

    // Out of bounds selection should fail verification
    #[test]
    fn test_out_of_bounds_verification() {
        let mut cursor = GutterCursor::new()
            .with_selected(15) // Out of bounds
            .with_visible_rows(10);

        cursor.layout(Rect::new(0.0, 0.0, 1.0, 10.0));
        let v = cursor.verify();
        assert!(!v.failed.is_empty(), "Out of bounds selection should fail");
    }

    // No selection is valid
    #[test]
    fn test_no_selection_valid() {
        let mut cursor = GutterCursor::new()
            .with_no_selection()
            .with_visible_rows(10);

        cursor.layout(Rect::new(0.0, 0.0, 1.0, 10.0));
        let v = cursor.verify();
        assert!(v.failed.is_empty());
    }

    // Additional tests for coverage
    #[test]
    fn test_cursor_style_width() {
        assert_eq!(CursorStyle::Triangle.width(), 1);
        assert_eq!(CursorStyle::Line.width(), 1);
        assert_eq!(CursorStyle::Dot.width(), 1);
        assert_eq!(CursorStyle::Arrow.width(), 1);
        assert_eq!(CursorStyle::Bracket.width(), 1);
        assert_eq!(CursorStyle::DoubleArrow.width(), 1);
    }

    #[test]
    fn test_cursor_style_default() {
        let style = CursorStyle::default();
        assert_eq!(style, CursorStyle::Triangle);
    }

    #[test]
    fn test_cursor_style_debug() {
        let style = CursorStyle::Dot;
        let debug = format!("{:?}", style);
        assert!(debug.contains("Dot"));
    }

    #[test]
    fn test_cursor_style_clone() {
        let style = CursorStyle::Arrow;
        let cloned = style.clone();
        assert_eq!(style, cloned);
    }

    #[test]
    fn test_selection_state_default() {
        let state = SelectionState::default();
        assert_eq!(state, SelectionState::None);
    }

    #[test]
    fn test_selection_state_debug() {
        let state = SelectionState::Focused;
        let debug = format!("{:?}", state);
        assert!(debug.contains("Focused"));
    }

    #[test]
    fn test_selection_state_clone() {
        let state = SelectionState::Selected;
        let cloned = state.clone();
        assert_eq!(state, cloned);
    }

    #[test]
    fn test_gutter_cursor_default() {
        let cursor = GutterCursor::default();
        assert!(cursor.selected_row.is_none());
        assert_eq!(cursor.visible_rows, 0);
    }

    #[test]
    fn test_gutter_cursor_debug() {
        let cursor = GutterCursor::new();
        let debug = format!("{:?}", cursor);
        assert!(debug.contains("GutterCursor"));
    }

    #[test]
    fn test_gutter_cursor_clone() {
        let cursor = GutterCursor::new().with_selected(5).with_visible_rows(10);
        let cloned = cursor.clone();
        assert_eq!(cloned.selected_row, Some(5));
        assert_eq!(cloned.visible_rows, 10);
    }

    #[test]
    fn test_with_style() {
        let cursor = GutterCursor::new().with_style(CursorStyle::Dot);
        assert_eq!(cursor.style, CursorStyle::Dot);
    }

    #[test]
    fn test_with_selected_color() {
        let color = Color::RED;
        let cursor = GutterCursor::new().with_selected_color(color);
        assert_eq!(cursor.selected_color, color);
    }

    #[test]
    fn test_with_focused_color() {
        let color = Color::GREEN;
        let cursor = GutterCursor::new().with_focused_color(color);
        assert_eq!(cursor.focused_color, color);
    }

    #[test]
    fn test_color_for_state() {
        let cursor = GutterCursor::new();
        let none_color = cursor.color_for_state(SelectionState::None);
        let selected_color = cursor.color_for_state(SelectionState::Selected);
        let focused_color = cursor.color_for_state(SelectionState::Focused);
        let focused_selected_color = cursor.color_for_state(SelectionState::FocusedSelected);

        // None should be dim
        assert!(none_color.r < 0.3);
        // Selected should be cyan-ish
        assert_eq!(selected_color, cursor.selected_color);
        // Focused should be gold-ish
        assert_eq!(focused_color, cursor.focused_color);
        // FocusedSelected should also use focused color
        assert_eq!(focused_selected_color, cursor.focused_color);
    }

    #[test]
    fn test_measure() {
        let cursor = GutterCursor::new().with_visible_rows(10);
        let size = cursor.measure(Constraints {
            min_width: 0.0,
            min_height: 0.0,
            max_width: 100.0,
            max_height: 100.0,
        });
        assert!((size.width - 1.0).abs() < f32::EPSILON);
        assert!((size.height - 10.0).abs() < f32::EPSILON);
    }

    #[test]
    fn test_layout_sets_visible_rows() {
        let mut cursor = GutterCursor::new();
        cursor.layout(Rect::new(0.0, 0.0, 1.0, 15.0));
        assert_eq!(cursor.visible_rows, 15);
    }

    #[test]
    fn test_paint_empty_bounds() {
        let cursor = GutterCursor::new();
        let mut buffer = CellBuffer::new(0, 0);
        let mut canvas = DirectTerminalCanvas::new(&mut buffer);
        cursor.paint(&mut canvas);
        // Should not panic
    }

    #[test]
    fn test_paint_with_multi_select() {
        let mut cursor = GutterCursor::new()
            .with_row_states(vec![
                SelectionState::Selected,
                SelectionState::None,
                SelectionState::Focused,
            ])
            .with_visible_rows(3);

        cursor.layout(Rect::new(0.0, 0.0, 1.0, 3.0));

        let mut buffer = CellBuffer::new(1, 3);
        let mut canvas = DirectTerminalCanvas::new(&mut buffer);
        cursor.paint(&mut canvas);
        // Should render without panic
    }

    #[test]
    fn test_type_id() {
        let cursor = GutterCursor::new();
        let id = Widget::type_id(&cursor);
        let _ = id;
        // Just verify it returns something
    }

    #[test]
    fn test_event() {
        let mut cursor = GutterCursor::new();
        let result = cursor.event(&Event::Resize {
            width: 100.0,
            height: 50.0,
        });
        assert!(result.is_none());
    }

    #[test]
    fn test_children() {
        let cursor = GutterCursor::new();
        assert!(cursor.children().is_empty());
    }

    #[test]
    fn test_children_mut() {
        let mut cursor = GutterCursor::new();
        assert!(cursor.children_mut().is_empty());
    }

    #[test]
    fn test_brick_name() {
        let cursor = GutterCursor::new();
        assert_eq!(cursor.brick_name(), "gutter_cursor");
    }

    #[test]
    fn test_brick_assertions() {
        let cursor = GutterCursor::new();
        let assertions = cursor.assertions();
        assert!(!assertions.is_empty());
    }

    #[test]
    fn test_brick_budget() {
        let cursor = GutterCursor::new();
        let budget = cursor.budget();
        // Budget is uniform(1), so total should be some positive value
        let total = budget.paint_ms + budget.layout_ms + budget.measure_ms;
        assert!(total > 0 || total == 0); // Just verify it doesn't panic
    }

    #[test]
    fn test_to_html() {
        let cursor = GutterCursor::new().with_selected(5);
        let html = cursor.to_html();
        assert!(html.contains("gutter-cursor"));
        assert!(html.contains("5"));
    }

    #[test]
    fn test_to_html_no_selection() {
        let cursor = GutterCursor::new();
        let html = cursor.to_html();
        assert!(html.contains("gutter-cursor"));
    }

    #[test]
    fn test_to_css() {
        let cursor = GutterCursor::new();
        let css = cursor.to_css();
        assert!(css.is_empty());
    }

    #[test]
    fn test_verify_zero_width() {
        let mut cursor = GutterCursor::new().with_selected(3).with_visible_rows(10);
        cursor.layout(Rect::new(0.0, 0.0, 0.0, 10.0));
        let v = cursor.verify();
        assert!(!v.failed.is_empty(), "Zero width should fail verification");
    }

    #[test]
    fn test_get_row_state_out_of_bounds() {
        let cursor = GutterCursor::new().with_row_states(vec![SelectionState::Selected]);
        let state = cursor.get_row_state(100);
        assert_eq!(state, SelectionState::None);
    }
}