ftui-runtime 0.3.1

Elm-style runtime loop and subscriptions for FrankenTUI.
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
#![forbid(unsafe_code)]

//! Easy-mode adapter for string-based views.
//!
//! `StringModel` provides a simpler alternative to the full [`Model`] trait
//! for applications that render their view as a string rather than directly
//! manipulating a [`Frame`]. The string is parsed as styled text and rendered
//! into the frame automatically.
//!
//! This preserves the full kernel pipeline: String -> Text -> Frame -> Diff -> Presenter.
//!
//! # Example
//!
//! ```ignore
//! use ftui_runtime::string_model::StringModel;
//! use ftui_runtime::program::Cmd;
//! use ftui_core::event::Event;
//!
//! struct Counter { count: i32 }
//!
//! enum Msg { Increment, Quit }
//!
//! impl From<Event> for Msg {
//!     fn from(_: Event) -> Self { Msg::Increment }
//! }
//!
//! impl StringModel for Counter {
//!     type Message = Msg;
//!
//!     fn update(&mut self, msg: Msg) -> Cmd<Msg> {
//!         match msg {
//!             Msg::Increment => { self.count += 1; Cmd::none() }
//!             Msg::Quit => Cmd::quit(),
//!         }
//!     }
//!
//!     fn view_string(&self) -> String {
//!         format!("Count: {}", self.count)
//!     }
//! }
//! ```

use crate::program::{Cmd, Model};
use ftui_core::event::Event;
use ftui_render::cell::{Cell, CellContent};
use ftui_render::frame::Frame;
use ftui_text::{Text, grapheme_width};
use unicode_segmentation::UnicodeSegmentation;

/// A simplified model trait that uses string-based views.
///
/// Instead of rendering directly to a [`Frame`], implementations return
/// a `String` from [`view_string`](Self::view_string). The string is
/// converted to [`Text`] and rendered automatically.
///
/// This is ideal for quick prototyping and simple applications where
/// full frame control isn't needed.
pub trait StringModel: Sized {
    /// The message type for this model.
    type Message: From<Event> + Send + 'static;

    /// Initialize the model with startup commands.
    fn init(&mut self) -> Cmd<Self::Message> {
        Cmd::none()
    }

    /// Update the model in response to a message.
    fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message>;

    /// Render the view as a string.
    ///
    /// The returned string is split by newlines and rendered into the frame.
    /// Each line is rendered left-aligned starting from the top of the frame area.
    fn view_string(&self) -> String;
}

/// Adapter that bridges a [`StringModel`] to the full [`Model`] trait.
///
/// This wrapper converts the string output of `view_string()` into
/// `Text` and renders it into the frame, preserving the full kernel
/// pipeline (Text -> Buffer -> Diff -> Presenter).
pub struct StringModelAdapter<S: StringModel> {
    inner: S,
}

impl<S: StringModel> StringModelAdapter<S> {
    /// Create a new adapter wrapping the given string model.
    #[inline]
    pub fn new(inner: S) -> Self {
        Self { inner }
    }

    /// Get a reference to the inner model.
    #[inline]
    #[must_use]
    pub fn inner(&self) -> &S {
        &self.inner
    }

    /// Get a mutable reference to the inner model.
    #[inline]
    pub fn inner_mut(&mut self) -> &mut S {
        &mut self.inner
    }

    /// Consume the adapter and return the inner model.
    #[inline]
    #[must_use]
    pub fn into_inner(self) -> S {
        self.inner
    }
}

impl<S: StringModel> Model for StringModelAdapter<S> {
    type Message = S::Message;

    fn init(&mut self) -> Cmd<Self::Message> {
        self.inner.init()
    }

    fn update(&mut self, msg: Self::Message) -> Cmd<Self::Message> {
        self.inner.update(msg)
    }

    fn view(&self, frame: &mut Frame) {
        let s = self.inner.view_string();
        let text = Text::raw(&s);
        render_text_to_frame(&text, frame);
    }
}

/// Render a `Text` into a `Buffer`, line by line with span styles.
///
/// Each line is rendered left-aligned from (0, y). Lines beyond the
/// buffer height are clipped. Characters beyond buffer width are clipped.
fn render_text_to_frame(text: &Text, frame: &mut Frame) {
    let width = frame.width();
    let height = frame.height();

    for (y, line) in text.lines().iter().enumerate() {
        if y as u16 >= height {
            break;
        }

        let mut x: u16 = 0;
        for span in line.spans() {
            if x >= width {
                break;
            }

            let style = span.style.unwrap_or_default();

            for grapheme in span.content.graphemes(true) {
                if x >= width {
                    break;
                }

                let w = grapheme_width(grapheme);
                if w == 0 {
                    continue;
                }

                // Skip if the wide character would exceed the buffer width
                if x + w as u16 > width {
                    break;
                }

                let content = if w > 1 || grapheme.chars().count() > 1 {
                    let id = frame.intern_with_width(grapheme, w as u8);
                    CellContent::from_grapheme(id)
                } else if let Some(c) = grapheme.chars().next() {
                    CellContent::from_char(c)
                } else {
                    continue;
                };

                let mut cell = Cell::new(content);
                apply_style(&mut cell, style);
                frame.buffer.set(x, y as u16, cell);

                x = x.saturating_add(w as u16);
            }
        }
    }
}

/// Apply a style to a cell using merge semantics.
///
/// - **fg:** replaced when set.
/// - **bg:** alpha-aware compositing (Porter-Duff SourceOver).
/// - **attrs:** OR-merged on top of existing flags (never cleared).
fn apply_style(cell: &mut Cell, style: ftui_style::Style) {
    if let Some(fg) = style.fg {
        cell.fg = fg;
    }
    if let Some(bg) = style.bg {
        match bg.a() {
            0 => {}                          // Fully transparent: no-op
            255 => cell.bg = bg,             // Fully opaque: replace
            _ => cell.bg = bg.over(cell.bg), // Composite src-over-dst
        }
    }
    if let Some(attrs) = style.attrs {
        let cell_flags: ftui_render::cell::StyleFlags = attrs.into();
        cell.attrs = cell.attrs.merged_flags(cell_flags);
    }
}

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

    // ---------- Shared test message type ----------

    #[derive(Debug)]
    enum TestMsg {
        Increment,
        Decrement,
        Quit,
        NoOp,
    }

    impl From<Event> for TestMsg {
        fn from(_: Event) -> Self {
            TestMsg::NoOp
        }
    }

    // ---------- Test StringModel ----------

    struct CounterModel {
        value: i32,
    }

    impl StringModel for CounterModel {
        type Message = TestMsg;

        fn update(&mut self, msg: TestMsg) -> Cmd<TestMsg> {
            match msg {
                TestMsg::Increment => {
                    self.value += 1;
                    Cmd::none()
                }
                TestMsg::Decrement => {
                    self.value -= 1;
                    Cmd::none()
                }
                TestMsg::Quit => Cmd::quit(),
                TestMsg::NoOp => Cmd::none(),
            }
        }

        fn view_string(&self) -> String {
            format!("Count: {}", self.value)
        }
    }

    // ---------- Tests ----------

    #[test]
    fn adapter_delegates_update() {
        let mut adapter = StringModelAdapter::new(CounterModel { value: 0 });
        adapter.update(TestMsg::Increment);
        assert_eq!(adapter.inner().value, 1);
        adapter.update(TestMsg::Decrement);
        assert_eq!(adapter.inner().value, 0);
    }

    #[test]
    fn adapter_delegates_quit() {
        let mut adapter = StringModelAdapter::new(CounterModel { value: 0 });
        let cmd = adapter.update(TestMsg::Quit);
        assert!(matches!(cmd, Cmd::Quit));
    }

    #[test]
    fn adapter_view_renders_text() {
        let adapter = StringModelAdapter::new(CounterModel { value: 42 });
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(80, 24, &mut pool);

        adapter.view(&mut frame);

        // "Count: 42" should be rendered
        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('C'));
        assert_eq!(frame.buffer.get(1, 0).unwrap().content.as_char(), Some('o'));
        assert_eq!(frame.buffer.get(7, 0).unwrap().content.as_char(), Some('4'));
        assert_eq!(frame.buffer.get(8, 0).unwrap().content.as_char(), Some('2'));
    }

    #[test]
    fn adapter_view_multiline() {
        struct MultiLineModel;

        impl StringModel for MultiLineModel {
            type Message = TestMsg;

            fn update(&mut self, _msg: TestMsg) -> Cmd<TestMsg> {
                Cmd::none()
            }

            fn view_string(&self) -> String {
                "Line 1\nLine 2\nLine 3".to_string()
            }
        }

        let adapter = StringModelAdapter::new(MultiLineModel);
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(20, 5, &mut pool);

        adapter.view(&mut frame);

        // Line 1 at y=0
        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('L'));
        assert_eq!(frame.buffer.get(5, 0).unwrap().content.as_char(), Some('1'));

        // Line 2 at y=1
        assert_eq!(frame.buffer.get(0, 1).unwrap().content.as_char(), Some('L'));
        assert_eq!(frame.buffer.get(5, 1).unwrap().content.as_char(), Some('2'));

        // Line 3 at y=2
        assert_eq!(frame.buffer.get(0, 2).unwrap().content.as_char(), Some('L'));
        assert_eq!(frame.buffer.get(5, 2).unwrap().content.as_char(), Some('3'));
    }

    #[test]
    fn adapter_clips_to_buffer_height() {
        struct TallModel;

        impl StringModel for TallModel {
            type Message = TestMsg;
            fn update(&mut self, _: TestMsg) -> Cmd<TestMsg> {
                Cmd::none()
            }
            fn view_string(&self) -> String {
                (0..100)
                    .map(|i| format!("Line {}", i))
                    .collect::<Vec<_>>()
                    .join("\n")
            }
        }

        let adapter = StringModelAdapter::new(TallModel);
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(20, 3, &mut pool);

        // Should not panic even with 100 lines in a 3-row buffer
        adapter.view(&mut frame);

        // Only first 3 lines rendered
        assert_eq!(frame.buffer.get(5, 0).unwrap().content.as_char(), Some('0'));
        assert_eq!(frame.buffer.get(5, 1).unwrap().content.as_char(), Some('1'));
        assert_eq!(frame.buffer.get(5, 2).unwrap().content.as_char(), Some('2'));
    }

    #[test]
    fn adapter_clips_to_buffer_width() {
        struct WideModel;

        impl StringModel for WideModel {
            type Message = TestMsg;
            fn update(&mut self, _: TestMsg) -> Cmd<TestMsg> {
                Cmd::none()
            }
            fn view_string(&self) -> String {
                "ABCDEFGHIJKLMNOPQRSTUVWXYZ".to_string()
            }
        }

        let adapter = StringModelAdapter::new(WideModel);
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(5, 1, &mut pool);

        // Should not panic
        adapter.view(&mut frame);

        // Only first 5 chars rendered
        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('A'));
        assert_eq!(frame.buffer.get(4, 0).unwrap().content.as_char(), Some('E'));
    }

    #[test]
    fn adapter_renders_grapheme_clusters() {
        struct EmojiModel;

        impl StringModel for EmojiModel {
            type Message = TestMsg;
            fn update(&mut self, _: TestMsg) -> Cmd<TestMsg> {
                Cmd::none()
            }
            fn view_string(&self) -> String {
                "👩‍🚀X".to_string()
            }
        }

        let adapter = StringModelAdapter::new(EmojiModel);
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(6, 1, &mut pool);

        adapter.view(&mut frame);

        let grapheme_width = grapheme_width("👩‍🚀");
        assert!(grapheme_width >= 2);

        let head = frame.buffer.get(0, 0).unwrap();
        assert!(head.content.is_grapheme());
        assert_eq!(head.content.width(), grapheme_width);

        for i in 1..grapheme_width {
            let tail = frame.buffer.get(i as u16, 0).unwrap();
            assert!(tail.is_continuation(), "cell {i} should be continuation");
        }

        let next = frame.buffer.get(grapheme_width as u16, 0).unwrap();
        assert_eq!(next.content.as_char(), Some('X'));
    }

    #[test]
    fn adapter_inner_access() {
        let adapter = StringModelAdapter::new(CounterModel { value: 99 });
        assert_eq!(adapter.inner().value, 99);
    }

    #[test]
    fn adapter_inner_mut_access() {
        let mut adapter = StringModelAdapter::new(CounterModel { value: 0 });
        adapter.inner_mut().value = 50;
        assert_eq!(adapter.inner().value, 50);
    }

    #[test]
    fn adapter_into_inner() {
        let adapter = StringModelAdapter::new(CounterModel { value: 42 });
        let model = adapter.into_inner();
        assert_eq!(model.value, 42);
    }

    #[test]
    fn empty_view_string() {
        struct EmptyModel;

        impl StringModel for EmptyModel {
            type Message = TestMsg;
            fn update(&mut self, _: TestMsg) -> Cmd<TestMsg> {
                Cmd::none()
            }
            fn view_string(&self) -> String {
                String::new()
            }
        }

        let adapter = StringModelAdapter::new(EmptyModel);
        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(10, 5, &mut pool);

        // Should not panic
        adapter.view(&mut frame);
    }

    #[test]
    fn default_init_returns_none() {
        let mut adapter = StringModelAdapter::new(CounterModel { value: 0 });
        let cmd = adapter.init();
        assert!(matches!(cmd, Cmd::None));
    }

    #[test]
    fn render_text_styled_fg() {
        use ftui_render::cell::PackedRgba;
        use ftui_style::Style;
        use ftui_text::{Line, Span, Text};

        let style = Style::new().fg(PackedRgba::rgb(255, 0, 0));
        let line = Line::from_spans([Span::styled("Hi", style)]);
        let text = Text::from_lines([line]);

        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(10, 1, &mut pool);
        render_text_to_frame(&text, &mut frame);

        let cell = frame.buffer.get(0, 0).unwrap();
        assert_eq!(cell.content.as_char(), Some('H'));
        assert_eq!(cell.fg, PackedRgba::rgb(255, 0, 0));
    }

    #[test]
    fn render_blank_lines_between_content() {
        let text = Text::raw("A\n\nB");

        let mut pool = GraphemePool::new();
        let mut frame = Frame::new(10, 5, &mut pool);
        render_text_to_frame(&text, &mut frame);

        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('A'));
        // blank line at y=1 remains default
        assert_eq!(frame.buffer.get(0, 2).unwrap().content.as_char(), Some('B'));
    }

    #[test]
    fn adapter_noop_message() {
        let mut adapter = StringModelAdapter::new(CounterModel { value: 5 });
        let cmd = adapter.update(TestMsg::NoOp);
        assert!(matches!(cmd, Cmd::None));
        assert_eq!(adapter.inner().value, 5);
    }
}