facett-console 0.1.4

facett — themed terminal/shell component: fixed monospace cell grid, block/beam cursor, ANSI colour mapped to the palette, scrollback on the CygnusEd smooth-scroll engine
Documentation
//! **facett-console** (§8 TYPE-2) — a themed terminal/shell component: a fixed
//! **monospace cell grid**, a block/beam **cursor**, optional **ANSI** colour
//! mapped to the palette, and **scrollback** on the CygnusEd smooth-scroll engine
//! (§11). A [`Facet`]: themeable · resizable · scalable · copyable · searchable.
//!
//! Lines are appended by the host (a process' stdout, a REPL); the console owns
//! the scrollback ring + the smooth-scroll offset (deterministic under an
//! injected clock via `advance`). ANSI SGR colour codes (30–37/90–97) map onto
//! the active [`Theme`](facett_core::Theme) so the terminal matches the app.

use egui::{Align2, FontId, Rect, Sense, Stroke, Ui, WidgetType, pos2, vec2};
use facett_core::scroll_engine::SmoothScroll;
use facett_core::{Facet, FacetCaps, Semantics, a11y_node, stable_id, theme};
use serde::{Deserialize, Serialize};

/// Cursor shape (TYPE-2).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Cursor {
    Block,
    Beam,
    Underline,
}

/// A coloured run of text within a console line, with a palette-role colour.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Span {
    pub text: String,
    /// Palette role index (see [`AnsiColor`]); `None` = default fg.
    pub color: Option<AnsiColor>,
}

/// The 8 ANSI colours, mapped to **palette roles** (not raw RGB) so the terminal
/// follows the theme.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum AnsiColor {
    Black,
    Red,
    Green,
    Yellow,
    Blue,
    Magenta,
    Cyan,
    White,
}

impl AnsiColor {
    /// Map an SGR foreground code (30–37, 90–97) to a colour.
    fn from_sgr(code: u8) -> Option<AnsiColor> {
        Some(match code % 10 {
            0 => AnsiColor::Black,
            1 => AnsiColor::Red,
            2 => AnsiColor::Green,
            3 => AnsiColor::Yellow,
            4 => AnsiColor::Blue,
            5 => AnsiColor::Magenta,
            6 => AnsiColor::Cyan,
            7 => AnsiColor::White,
            _ => return None,
        })
    }

    /// Resolve to a [`Theme`](facett_core::Theme) colour — palette roles, never raw
    /// literals (COH-1).
    fn to_color(self, th: &facett_core::Theme) -> egui::Color32 {
        match self {
            AnsiColor::Black => th.text_dim,
            AnsiColor::Red => th.accent, // error-ish; themes pick the accent
            AnsiColor::Green => th.point,
            AnsiColor::Yellow => th.glow,
            AnsiColor::Blue => th.node_stroke,
            AnsiColor::Magenta => th.panel_stroke,
            AnsiColor::Cyan => th.accent,
            AnsiColor::White => th.text,
        }
    }
}

/// Parse a line containing ANSI SGR colour escapes into coloured [`Span`]s. Only
/// the foreground-colour subset is handled (others are stripped); enough to make
/// CLI output match the palette.
pub fn parse_ansi(line: &str) -> Vec<Span> {
    let mut spans = Vec::new();
    let mut cur = String::new();
    let mut color: Option<AnsiColor> = None;
    let bytes = line.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == 0x1b && i + 1 < bytes.len() && bytes[i + 1] == b'[' {
            // Flush the current run.
            if !cur.is_empty() {
                spans.push(Span { text: std::mem::take(&mut cur), color });
            }
            // Read until 'm'.
            let mut j = i + 2;
            let mut num = String::new();
            while j < bytes.len() && bytes[j] != b'm' {
                num.push(bytes[j] as char);
                j += 1;
            }
            // Apply the (last) SGR code.
            if let Some(code) = num.split(';').next_back().and_then(|s| s.parse::<u8>().ok()) {
                if code == 0 {
                    color = None;
                } else if (30..=37).contains(&code) || (90..=97).contains(&code) {
                    color = AnsiColor::from_sgr(code);
                }
            }
            i = j + 1;
        } else {
            cur.push(bytes[i] as char);
            i += 1;
        }
    }
    if !cur.is_empty() || spans.is_empty() {
        spans.push(Span { text: cur, color });
    }
    spans
}

/// The console / shell component.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Console {
    title: String,
    /// Scrollback lines (parsed into coloured spans).
    lines: Vec<Vec<Span>>,
    /// Max scrollback (oldest dropped).
    max_lines: usize,
    /// The prompt + the in-progress input line.
    prompt: String,
    input: String,
    cursor: Cursor,
    /// Smooth scrollback offset (CygnusEd engine; deterministic via `advance`).
    scroll: SmoothScroll,
    scale: f32,
    /// Free-text find filter (searchable).
    filter: String,
}

impl Console {
    pub fn new(title: impl Into<String>) -> Self {
        Self {
            title: title.into(),
            lines: Vec::new(),
            max_lines: 5000,
            prompt: "$ ".into(),
            input: String::new(),
            cursor: Cursor::Block,
            scroll: SmoothScroll::default(),
            scale: 1.0,
            filter: String::new(),
        }
    }

    pub fn with_prompt(mut self, p: impl Into<String>) -> Self {
        self.prompt = p.into();
        self
    }
    pub fn with_cursor(mut self, c: Cursor) -> Self {
        self.cursor = c;
        self
    }

    /// Append a raw line (ANSI-parsed), dropping the oldest past `max_lines`.
    pub fn push_line(&mut self, raw: impl AsRef<str>) {
        self.lines.push(parse_ansi(raw.as_ref()));
        if self.lines.len() > self.max_lines {
            let drop = self.lines.len() - self.max_lines;
            self.lines.drain(0..drop);
        }
        // Stick to the bottom on new output.
        self.scroll.scroll_to(self.scroll.max);
    }

    pub fn set_input(&mut self, s: impl Into<String>) {
        self.input = s.into();
    }
    pub fn line_count(&self) -> usize {
        self.lines.len()
    }

    /// Whether the console is idle (FC-8). The console is host-pushed and
    /// synchronous — lines arrive via [`push_line`](Self::push_line) on the host's
    /// thread and there is no internal async work — so it is always idle from the
    /// component's own perspective.
    pub fn is_idle(&self) -> bool {
        true
    }

    /// Advance the scrollback animation (the injected clock; deterministic).
    pub fn advance(&mut self, dt: f32) {
        self.scroll.advance(dt);
    }

    /// The plain-text scrollback (for copy/search).
    pub fn plain_text(&self) -> String {
        self.lines
            .iter()
            .map(|spans| spans.iter().map(|s| s.text.as_str()).collect::<String>())
            .collect::<Vec<_>>()
            .join("\n")
    }
}

impl Facet for Console {
    fn title(&self) -> &str {
        &self.title
    }

    fn ui(&mut self, ui: &mut Ui) {
        let th = theme(ui);
        let cell_h = 16.0 * self.scale;
        let font = FontId::monospace(13.0 * self.scale);

        // Keep the scroll extent in sync with the content.
        let total_h = self.lines.len() as f32 * cell_h;
        let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), ui.available_height().max(cell_h * 3.0)), Sense::hover());
        let view_h = rect.height();
        self.scroll.set_max((total_h - view_h).max(0.0));

        let painter = ui.painter_at(rect);
        painter.rect_filled(rect, 0.0, th.bg);

        // Render only visible lines (virtualised), at the fractional smooth offset.
        let (first, frac) = self.scroll.first_row_and_frac(cell_h);
        let visible = (view_h / cell_h).ceil() as usize + 1;
        for vi in 0..visible {
            let li = first + vi;
            if li >= self.lines.len() {
                break;
            }
            let y = rect.top() + vi as f32 * cell_h - frac;
            let mut x = rect.left() + 4.0;
            for span in &self.lines[li] {
                let color = span.color.map(|c| c.to_color(&th)).unwrap_or(th.text);
                let g = painter.layout_no_wrap(span.text.clone(), font.clone(), color);
                let w = g.size().x;
                painter.galley(pos2(x, y), g, color);
                x += w;
            }
        }

        // The prompt + input on the last visible row + the cursor.
        let py = rect.bottom() - cell_h;
        let prompt_text = format!("{}{}", self.prompt, self.input);
        let pg = painter.layout_no_wrap(prompt_text.clone(), font.clone(), th.accent);
        painter.galley(pos2(rect.left() + 4.0, py), pg, th.accent);
        // Cursor glyph after the input.
        let cw = font.size * 0.6;
        let cx = rect.left() + 4.0 + prompt_text.chars().count() as f32 * cw;
        let crect = Rect::from_min_size(pos2(cx, py), vec2(cw, cell_h));
        match self.cursor {
            Cursor::Block => {
                painter.rect_filled(crect, 0.0, th.accent.linear_multiply(0.5));
            }
            Cursor::Beam => {
                painter.line_segment([crect.left_top(), crect.left_bottom()], Stroke::new(2.0, th.accent));
            }
            Cursor::Underline => {
                painter.line_segment([crect.left_bottom(), crect.right_bottom()], Stroke::new(2.0, th.accent));
            }
        }
        let _ = Align2::LEFT_TOP;

        // FC-4: the whole console (input line + cursor + scrollback) was painted on
        // a single `Sense::hover()` alloc above — nothing rode into the AccessKit
        // tree. Surface the two value-bearing surfaces as real accesskit nodes.

        // (a) The input line → a TextInput node whose accesskit *value* is the
        // current `self.input` string, so `get_by_role(Role::TextInput)` / a value
        // query reads back the typed text. `WidgetInfo::text_edit` carries the
        // editable string as the accesskit value (a Semantics(TextEdit) would map
        // the label, not the typed text — so we set widget_info directly).
        let base = ui.id().with("console");
        let input_rect = Rect::from_min_size(pos2(rect.left(), py), vec2(rect.width(), cell_h));
        let input_id = stable_id(base, "input");
        let input_resp = ui.interact(input_rect, input_id, Sense::click());
        let typed = self.input.clone();
        input_resp.widget_info(|| egui::WidgetInfo::text_edit(true, "", &typed, "console input"));

        // (b) The scrollback region → a labelled Label node carrying the line count
        // as its numeric value, so a robot driver / screen reader can find the
        // scrollback and read how many lines it holds.
        let count = self.lines.len();
        let scrollback_rect = Rect::from_min_max(rect.min, pos2(rect.right(), py));
        a11y_node(
            ui,
            base,
            "scrollback",
            Sense::hover(),
            scrollback_rect,
            Semantics::new(WidgetType::Label, format!("console — {count} lines")).value(count as f64),
        );
    }

    fn state_json(&self) -> serde_json::Value {
        serde_json::json!({
            "title": self.title,
            "lines": self.lines.len(),
            "prompt": self.prompt,
            "input": self.input,
            "cursor": format!("{:?}", self.cursor),
            "scroll_offset": self.scroll.offset,
            "scroll_max": self.scroll.max,
            "scale": self.scale,
            "filter": self.filter,
            "idle": self.is_idle(),
        })
    }

    fn caps(&self) -> FacetCaps {
        FacetCaps::NONE.themeable().resizable().scalable().copyable().searchable()
    }

    fn scale(&self) -> f32 {
        self.scale
    }
    fn set_scale(&mut self, scale: f32) {
        self.scale = scale.clamp(0.25, 4.0);
    }

    fn copy(&mut self) -> Option<String> {
        let t = self.plain_text();
        if t.is_empty() { None } else { Some(t) }
    }
}

#[cfg(test)]
mod tests;