abstracttui 0.2.1

A reactive, compositor-grade terminal UI engine: fine-grained signals, layered rendering with damage tracking, images (kitty/iTerm2/sixel/mosaic), software-rasterized 3D (GLB), themes and animation.
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
//! Feed: virtualized, append-only, keyed rich-block items — the
//! chat/log/transcript surface (backlog 0100).
//!
//! An app owns a [`FeedState`] handle and mutates it (`push`, `update`,
//! `stream_*`); the [`Feed`] widget renders a WINDOW over it. Appending
//! is O(1): one item typesets, prefix sums extend, one damaged region
//! repaints. 100k items cost only the visible rows per frame.
//!
//! ```
//! use abstracttui::base::Size;
//! use abstracttui::reactive::{create_root, flush_effects};
//! use abstracttui::ui::{BufferCanvas, Element, UiTree};
//! use abstracttui::widgets::{Feed, FeedItem, FeedState};
//!
//! let mut tree = UiTree::new(Size::new(24, 4));
//! let (root, ()) = create_root(|cx| {
//!     let feed = FeedState::new(cx);
//!     feed.push("m1", FeedItem::markdown("**hello** feed"));
//!     let view = Element::new().child(Feed::new(&feed).view(cx)).build();
//!     tree.mount(cx, view);
//! });
//! flush_effects();
//! let mut canvas = BufferCanvas::new(Size::new(24, 4));
//! tree.draw(&mut canvas);
//! assert!(canvas.row_text(0).contains("hello feed"));
//! root.dispose();
//! ```
//!
//! ## Content model
//!
//! An item is a list of [`FeedBlock`]s: plain text (wrapped verbatim),
//! markdown (the `render::md` vocabulary through the SAME typeset
//! recipe as [`MarkdownView`](super::MarkdownView) — one recipe, no
//! drift), a code fence, or a custom-draw block (app escape hatch with
//! an honest height-at-width callback). A STREAMING item wraps
//! [`md::StreamSession`](crate::render::md::StreamSession): closed
//! blocks typeset once and freeze; only the open tail block
//! re-typesets per delta.
//!
//! ## Windowing
//!
//! Prefix sums over item heights (the `List` machinery generalized to
//! multi-row rich items): first visible item by binary search, walk
//! until off-screen. The visible band is `rect ∩ canvas bounds`, so a
//! feed mounted inside `Scroll` (its rect huge, mostly off-screen)
//! still draws only a screenful.
//!
//! ## Geometry and the width fixup
//!
//! Typesetting needs a width, which draw discovers. Rows re-typeset
//! inside draw (a pure cache fill, the `MarkdownView` recipe); the
//! reactive HEIGHT (`total_rows`, consumed by the element style and by
//! `Scroll`'s intrinsic measure) must not be written from a draw
//! closure (RT1-2), so a width change schedules a one-shot
//! `reactive::after(0)` fixup that syncs the signal next turn —
//! latched, so steady frames schedule nothing. Appends at a known
//! width update the signal synchronously (single-frame correct).
//!
//! OWNER: CONTENT (app-widgets wave).

use std::cell::RefCell;
use std::rc::Rc;

use crate::base::Rect;
use crate::layout::{Dimension, Style as LayoutStyle};
use crate::reactive::{Scope, Signal};
use crate::render::md::StreamSession;
use crate::theme::TokenSet;
use crate::ui::{dyn_view, Element, StyledCanvas};

use super::markdown::{draw_rows, md_styles};

/// One rich block of a feed item.
pub enum FeedBlock {
    /// Plain text, wrapped verbatim (log lines, tool output). No
    /// markdown parsing.
    Text(String),
    /// Markdown source (the supported `render::md` subset).
    Markdown(String),
    /// A fenced code block: highlighted like a markdown fence.
    Code {
        /// Language label. Routes the lexer like a markdown fence:
        /// `"diff"`/`"patch"` tint through the diff mapping
        /// (`code::diff_token_color`); every other label renders with
        /// the C-like lexer.
        lang: String,
        /// Verbatim source.
        source: String,
    },
    /// App-drawn block: an honest height-at-width callback plus a draw
    /// closure over the block's solved sub-rect. The draw MUST NOT
    /// mutate the owning `FeedState` (it runs during paint).
    Custom(CustomBlock),
}

/// Shared draw closure (custom blocks are drawn from cloned handles so
/// user paint code runs outside the feed-state borrow).
type SharedDrawFn = Rc<dyn Fn(&mut dyn StyledCanvas, Rect)>;

/// The custom-draw escape hatch (badges, tool cards, charts).
pub struct CustomBlock {
    height: Box<dyn Fn(i32) -> i32>,
    draw: SharedDrawFn,
}

impl CustomBlock {
    /// `height(width) -> rows` must be honest (windowing trusts it);
    /// `draw(canvas, rect)` paints inside the block's rect.
    pub fn new(
        height: impl Fn(i32) -> i32 + 'static,
        draw: impl Fn(&mut dyn StyledCanvas, Rect) + 'static,
    ) -> CustomBlock {
        CustomBlock {
            height: Box::new(height),
            draw: Rc::new(draw),
        }
    }
}

/// One feed item: a small block list. Items are IDENTITIES (keyed);
/// see [`FeedState::push`].
pub struct FeedItem {
    blocks: Vec<FeedBlock>,
}

impl FeedItem {
    pub fn new() -> FeedItem {
        FeedItem { blocks: Vec::new() }
    }

    /// Single markdown-block item (the common chat message).
    pub fn markdown(src: impl Into<String>) -> FeedItem {
        FeedItem::new().block(FeedBlock::Markdown(src.into()))
    }

    /// Single plain-text item (the common log line).
    pub fn text(s: impl Into<String>) -> FeedItem {
        FeedItem::new().block(FeedBlock::Text(s.into()))
    }

    /// Single code-fence item.
    pub fn code(lang: impl Into<String>, source: impl Into<String>) -> FeedItem {
        FeedItem::new().block(FeedBlock::Code {
            lang: lang.into(),
            source: source.into(),
        })
    }

    pub fn block(mut self, b: FeedBlock) -> FeedItem {
        self.blocks.push(b);
        self
    }
}

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

// Entry storage + typesetting internals (file-size discipline; the
// same child-module pattern `md.rs` uses for its stream half).
#[path = "feed_typeset.rs"]
mod typeset;
use typeset::{Entry, EntryKind, FeedInner, Segment, StreamEntry};

/// Cloneable handle to a feed's items. Mutations are O(1) for appends
/// and tail streaming; the widget re-renders one dyn region per change.
#[derive(Clone)]
pub struct FeedState {
    inner: Rc<RefCell<FeedInner>>,
    /// Bumped per mutation — the widget's re-render key.
    version: Signal<u64>,
    /// Total content rows at the current width (0 before first draw).
    /// The element's reactive height; `Scroll` measures it intrinsically.
    rows: Signal<i32>,
}

impl FeedState {
    pub fn new(cx: Scope) -> FeedState {
        FeedState {
            inner: Rc::new(RefCell::new(FeedInner::new())),
            version: cx.signal(0u64),
            rows: cx.signal(0i32),
        }
    }

    /// Append a keyed item. A duplicate key replaces that item's
    /// content instead (keys are identities).
    pub fn push(&self, key: impl Into<String>, item: FeedItem) {
        let key = key.into();
        {
            let mut inner = self.inner.borrow_mut();
            let existing = inner.index.get(&key).copied();
            if let Some(i) = existing {
                drop(inner);
                self.update_at(i, EntryKind::Static(item.blocks));
                return;
            }
            let i = inner.entries.len();
            inner.index.insert(key, i);
            inner.entries.push(Entry {
                kind: EntryKind::Static(item.blocks),
                segments: Vec::new(),
                height: 0,
            });
            inner.typeset_entry(i, true);
            inner.rebuild_prefix_from(i);
        }
        self.publish();
    }

    /// Replace an item's content by key. Returns false for an unknown
    /// key (nothing changes).
    pub fn update(&self, key: &str, item: FeedItem) -> bool {
        let Some(i) = self.inner.borrow().index.get(key).copied() else {
            return false;
        };
        self.update_at(i, EntryKind::Static(item.blocks));
        true
    }

    fn update_at(&self, i: usize, kind: EntryKind) {
        {
            let mut inner = self.inner.borrow_mut();
            inner.entries[i].kind = kind;
            inner.entries[i].segments = Vec::new();
            inner.typeset_entry(i, true);
            inner.rebuild_prefix_from(i);
        }
        self.publish();
    }

    /// Open a STREAMING markdown item (a live answer). Feed deltas with
    /// [`FeedState::stream_append`]; seal with [`FeedState::stream_finish`].
    pub fn push_stream(&self, key: impl Into<String>) {
        let key = key.into();
        {
            let mut inner = self.inner.borrow_mut();
            let styles = inner.tokens.as_ref().map(md_styles).unwrap_or_default();
            let kind = EntryKind::Stream(Box::new(StreamEntry {
                raw: String::new(),
                session: StreamSession::new(styles),
                closed_seen: 0,
                finished: false,
            }));
            let existing = inner.index.get(&key).copied();
            let i = match existing {
                Some(i) => {
                    inner.entries[i].kind = kind;
                    inner.entries[i].segments = Vec::new();
                    i
                }
                None => {
                    let i = inner.entries.len();
                    inner.index.insert(key, i);
                    inner.entries.push(Entry {
                        kind,
                        segments: Vec::new(),
                        height: 0,
                    });
                    i
                }
            };
            inner.typeset_entry(i, true);
            inner.rebuild_prefix_from(i);
        }
        self.publish();
    }

    /// Append a delta to a streaming item. Only the OPEN tail block
    /// re-typesets; closed blocks are frozen (0110's contract carried
    /// into pixels). Returns false for unknown keys or non-stream items.
    pub fn stream_append(&self, key: &str, delta: &str) -> bool {
        {
            let mut inner = self.inner.borrow_mut();
            let Some(i) = inner.index.get(key).copied() else {
                return false;
            };
            let EntryKind::Stream(stream) = &mut inner.entries[i].kind else {
                return false;
            };
            stream.raw.push_str(delta);
            stream.session.append(delta);
            inner.typeset_entry(i, false);
            inner.rebuild_prefix_from(i);
        }
        self.publish();
        true
    }

    /// Seal a streaming item (EOF-closes an open fence, freezes all
    /// rows). The item stays updatable by key.
    pub fn stream_finish(&self, key: &str) -> bool {
        {
            let mut inner = self.inner.borrow_mut();
            let Some(i) = inner.index.get(key).copied() else {
                return false;
            };
            let EntryKind::Stream(stream) = &mut inner.entries[i].kind else {
                return false;
            };
            stream.session.finish();
            stream.finished = true;
            inner.typeset_entry(i, false);
            inner.rebuild_prefix_from(i);
        }
        self.publish();
        true
    }

    /// Remove every item (keys, rows, extent). The feed itself stays
    /// append-only; `clear` is the rebuild seam for bounded windows (a
    /// drop-oldest drain rebuilds its whole window in O(window)) and
    /// for "new conversation" flows. Width/theme bindings survive, so
    /// re-pushed items typeset immediately.
    pub fn clear(&self) {
        {
            let mut inner = self.inner.borrow_mut();
            inner.entries.clear();
            inner.index.clear();
            inner.prefix.clear();
        }
        self.publish();
    }

    pub fn len(&self) -> usize {
        self.inner.borrow().entries.len()
    }

    pub fn is_empty(&self) -> bool {
        self.inner.borrow().entries.is_empty()
    }

    /// Total content rows at the current typeset width — the reactive
    /// content extent (`Scroll` reads it through the element's height;
    /// apps can read it for "N rows" chrome). 0 until the first draw
    /// discovers a width.
    pub fn total_rows(&self) -> Signal<i32> {
        self.rows
    }

    /// Diagnostics: blocks typeset since creation. Closed stream
    /// blocks typeset exactly once — cost tests pin deltas on this.
    pub fn blocks_typeset_total(&self) -> u64 {
        self.inner.borrow().blocks_typeset
    }

    /// Publish after a mutation: sync the extent signal (lawful here —
    /// mutations happen in event/effect phases) and bump the render key.
    /// The `try_` reads guard against a disposed UI scope (an app-held
    /// handle outliving its widget must stay inert, never panic).
    fn publish(&self) {
        let total = self.inner.borrow().total_rows();
        if let Some(cur) = self.rows.try_get_untracked() {
            if cur != total {
                self.rows.set(total);
            }
        }
        if self.version.try_get_untracked().is_some() {
            self.version.update(|v| *v += 1);
        }
    }

    /// Deferred geometry sync for width discovered inside draw (RT1-2:
    /// no signal writes from paint). Latched: one pending fixup.
    fn schedule_geometry_sync(&self) {
        let mut inner = self.inner.borrow_mut();
        if inner.fixup_scheduled {
            return;
        }
        inner.fixup_scheduled = true;
        drop(inner);
        let state = self.clone();
        crate::reactive::after(std::time::Duration::ZERO, move || {
            state.inner.borrow_mut().fixup_scheduled = false;
            state.publish();
        });
    }
}

/// The Feed widget builder. See the module docs.
pub struct Feed {
    state: FeedState,
    gap: i32,
    layout: Option<LayoutStyle>,
}

impl Feed {
    pub fn new(state: &FeedState) -> Feed {
        Feed {
            state: state.clone(),
            gap: 1,
            layout: None,
        }
    }

    /// Blank rows between items (default 1).
    pub fn gap(mut self, rows: i32) -> Feed {
        self.gap = rows.max(0);
        self
    }

    /// Explicit layout (fixed-box mode: the feed shows its head and
    /// clips). Default: content-sized height (`total_rows`), full
    /// width — the shape `Scroll` measures intrinsically.
    pub fn layout(mut self, layout: LayoutStyle) -> Feed {
        self.layout = Some(layout);
        self
    }

    /// Canonical one-call build: tokens resolve from the app's theme
    /// context (tracked read — building inside a `dyn_view` re-renders
    /// on theme switch).
    pub fn view(self, cx: Scope) -> crate::ui::View {
        let t = crate::widgets::theme_tokens(cx);
        self.element(cx, &t).build()
    }

    pub fn element(self, _cx: Scope, t: &TokenSet) -> Element {
        let state = self.state;
        {
            // Bind tokens; a theme change re-typesets everything (and
            // re-parses stream sessions once — their inline styles are
            // parse-time).
            let mut inner = state.inner.borrow_mut();
            if inner.tokens != Some(*t) {
                inner.tokens = Some(*t);
                inner.gap = self.gap;
                inner.retypeset_all();
            } else if inner.gap != self.gap {
                inner.gap = self.gap;
                inner.rebuild_prefix_from(0);
            }
        }
        state.publish();

        let rows = state.rows;
        let len_state = state.clone();
        let content_sized = self.layout.is_none();
        let style = match self.layout {
            Some(explicit) => {
                let mut el_style = explicit;
                // A fixed-box feed keeps the caller's geometry.
                el_style.overflow = crate::layout::Overflow::Clip;
                el_style
            }
            None => LayoutStyle::default().width(Dimension::Percent(1.0)),
        };
        let tokens = *t;

        let mut el = Element::new()
            .role(crate::ui::Role::List)
            .access_value(move || format!("{} items", len_state.len()));
        if content_sized {
            let base = style.clone();
            el = el.style_signal(move || {
                let mut s = base.clone();
                s.height = Dimension::Cells(rows.get().max(1));
                s
            });
        } else {
            el = el.style(style);
        }

        let version = state.version;
        el.child(dyn_view(
            LayoutStyle::default()
                .width(Dimension::Percent(1.0))
                .height(Dimension::Percent(1.0)),
            move || {
                version.get(); // the re-render key: any mutation repaints
                let state = state.clone();
                Element::new()
                    .style(
                        LayoutStyle::default()
                            .width(Dimension::Percent(1.0))
                            .height(Dimension::Percent(1.0)),
                    )
                    .draw(move |canvas, rect| draw_feed(&state, &tokens, canvas, rect))
                    .build()
            },
        ))
    }
}

/// Windowed paint: only entries intersecting `rect ∩ canvas bounds`
/// touch the canvas. Custom draws run after the state borrow releases
/// (they are app code).
fn draw_feed(state: &FeedState, t: &TokenSet, canvas: &mut dyn StyledCanvas, rect: Rect) {
    let mut customs: Vec<(SharedDrawFn, Rect)> = Vec::new();
    {
        let mut inner = state.inner.borrow_mut();
        if rect.w > 1 && inner.width != rect.w {
            // Width discovery / resize: re-typeset (pure cache fill;
            // the reactive extent syncs via the deferred fixup).
            inner.width = rect.w;
            inner.retypeset_all();
            drop(inner);
            state.schedule_geometry_sync();
            inner = state.inner.borrow_mut();
        }
        let bounds = Rect::from_size(canvas.size());
        let band = rect.intersect(bounds);
        if band.is_empty() || inner.entries.is_empty() {
            return;
        }
        let first_row = band.y - rect.y;
        let last_row = first_row + band.h; // exclusive
        let inner = &*inner;
        // First entry whose span can reach the band (binary search on
        // prefix starts, then step back one).
        let mut i = inner
            .prefix
            .partition_point(|&p| p <= first_row)
            .saturating_sub(1);
        while i < inner.entries.len() {
            let top = inner.prefix[i];
            if top >= last_row {
                break;
            }
            let entry = &inner.entries[i];
            let mut seg_top = top;
            for seg in &entry.segments {
                let h = seg.height();
                if seg_top >= last_row {
                    break;
                }
                if seg_top + h > first_row {
                    match seg {
                        Segment::Rows(rows) => {
                            let skip = (first_row - seg_top).max(0) as usize;
                            let visible = ((last_row - seg_top).min(h) as usize).min(rows.len());
                            if skip < visible {
                                let y = rect.y + seg_top + skip as i32;
                                draw_rows(
                                    canvas,
                                    Rect::new(rect.x, y, rect.w, (visible - skip) as i32),
                                    t,
                                    &rows[skip..visible],
                                );
                            }
                        }
                        Segment::Custom { draw, height } => {
                            // The custom block gets its FULL rect (its
                            // top may sit above the band); the canvas
                            // clips.
                            customs.push((
                                draw.clone(),
                                Rect::new(rect.x, rect.y + seg_top, rect.w, *height),
                            ));
                        }
                    }
                }
                seg_top += h;
            }
            i += 1;
        }
    }
    for (draw, r) in customs {
        draw(canvas, r);
    }
}

#[cfg(test)]
#[path = "feed_tests.rs"]
mod tests;