rcus-core 0.2.0

Core types for rcus: retained view tree, style, input, and the host bridge protocol
Documentation
use std::sync::Arc;

use crate::style::{Axis, Size, Style};

pub type RowRenderer = Arc<dyn Fn(usize) -> ViewNode + Send + Sync>;

/// The retained view description a host builds and the layout engine consumes.
/// Script runtimes produce the same tree from JSON, so the renderer never needs
/// to know which frontend authored a frame.
#[derive(Clone)]
pub enum ViewNode {
    Element {
        id: String,
        style: Style,
        axis: Axis,
        children: Vec<ViewNode>,
    },
    Text {
        id: String,
        text: String,
        style: Style,
    },
    VirtualRows {
        id: String,
        count: usize,
        style: Style,
        /// First visible source row, driven by host scroll state.
        first: usize,
        render: RowRenderer,
    },
}

impl ViewNode {
    pub fn element(id: impl Into<String>, style: Style, children: Vec<ViewNode>) -> Self {
        Self::Element {
            id: id.into(),
            style,
            axis: Axis::Column,
            children,
        }
    }

    pub fn row_element(id: impl Into<String>, style: Style, children: Vec<ViewNode>) -> Self {
        Self::Element {
            id: id.into(),
            style,
            axis: Axis::Row,
            children,
        }
    }

    pub fn column(children: Vec<ViewNode>) -> Self {
        Self::Element {
            id: "column".into(),
            style: Style::default(),
            axis: Axis::Column,
            children,
        }
    }

    pub fn row(children: Vec<ViewNode>) -> Self {
        Self::Element {
            id: "row".into(),
            style: Style::default(),
            axis: Axis::Row,
            children,
        }
    }

    pub fn text(text: impl Into<String>, style: Style) -> Self {
        Self::Text {
            id: "text".into(),
            text: text.into(),
            style,
        }
    }

    /// A text node with a stable id, which is what hit testing and focus use.
    pub fn text_node(id: impl Into<String>, text: impl Into<String>, style: Style) -> Self {
        Self::Text {
            id: id.into(),
            text: text.into(),
            style,
        }
    }

    pub fn empty(style: Style) -> Self {
        Self::Element {
            id: "empty".into(),
            style,
            axis: Axis::Column,
            children: Vec::new(),
        }
    }

    pub fn virtual_rows(
        count: usize,
        style: Style,
        render: impl Fn(usize) -> ViewNode + Send + Sync + 'static,
    ) -> Self {
        Self::virtual_rows_named("virtual-rows", 0, count, style, render)
    }

    /// A virtual list scrolled to a starting row.
    pub fn virtual_rows_from(
        first: usize,
        count: usize,
        style: Style,
        render: impl Fn(usize) -> ViewNode + Send + Sync + 'static,
    ) -> Self {
        Self::virtual_rows_named("virtual-rows", first, count, style, render)
    }

    /// A virtual list with an addressable id, so a host can scroll it in place
    /// with [`ViewNode::scroll_virtual_rows`] instead of rebuilding the tree.
    ///
    /// A virtual list always fills its parent on the main axis: it is a
    /// scrollback panel, and the window is derived from the space it is given.
    pub fn virtual_rows_named(
        id: impl Into<String>,
        first: usize,
        count: usize,
        mut style: Style,
        render: impl Fn(usize) -> ViewNode + Send + Sync + 'static,
    ) -> Self {
        style.fill = true;
        Self::VirtualRows {
            id: id.into(),
            count,
            style,
            first: first.min(count.saturating_sub(1)),
            render: Arc::new(render),
        }
    }

    /// Rewrites the window start of a virtual list, so scrolling only rebuilds
    /// the rows the user can actually see.
    pub fn scroll_virtual_rows(&mut self, id: &str, first: usize) -> bool {
        match self {
            Self::VirtualRows {
                id: node_id,
                count,
                first: start,
                ..
            } if node_id == id => {
                let clamped = first.min(count.saturating_sub(1));
                if *start == clamped {
                    return false;
                }
                *start = clamped;
                true
            }
            Self::Element { children, .. } => children
                .iter_mut()
                .any(|child| child.scroll_virtual_rows(id, first)),
            Self::Text { .. } | Self::VirtualRows { .. } => false,
        }
    }

    /// Visits every node, parents before children, which is the paint order.
    pub fn for_each(&self, visit: &mut dyn FnMut(&ViewNode)) {
        visit(self);
        match self {
            Self::Element { children, .. } => {
                for child in children {
                    child.for_each(visit);
                }
            }
            Self::Text { .. } => {}
            Self::VirtualRows { .. } => {}
        }
    }

    /// Total node count, including every materialized virtual row.
    pub fn node_count(&self) -> usize {
        let mut count = 0;
        self.for_each(&mut |_| count += 1);
        count
    }
}

/// A paint-order node, produced by the layout engine and consumed by renderers.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NodeKind {
    Element,
    Text,
    VirtualRow,
}

/// JSON shape accepted from script runtimes. Kept separate from `ViewNode` so
/// the host owns style defaults and script cannot smuggle in a closure.
#[derive(Clone, Debug, serde::Deserialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum ViewSpec {
    Element {
        id: Option<String>,
        #[serde(default)]
        style: Option<Style>,
        #[serde(default)]
        row: bool,
        #[serde(default)]
        children: Vec<ViewSpec>,
    },
    Text {
        id: Option<String>,
        #[serde(default)]
        style: Option<Style>,
        text: String,
    },
    Rows {
        id: Option<String>,
        #[serde(default)]
        style: Option<Style>,
        count: usize,
        #[serde(default)]
        first: usize,
        /// Materialized rows, used when a host renders a bounded list eagerly.
        #[serde(default)]
        rows: Vec<ViewSpec>,
    },
}

impl ViewSpec {
    /// Converts a script-authored spec into a retained node. Virtual row bodies
    /// beyond the supplied rows render as empty placeholders, so a list never
    /// has to cross the language boundary in full.
    pub fn into_node(self) -> ViewNode {
        match self {
            ViewSpec::Element {
                id,
                style,
                row,
                children,
            } => {
                let style = style.unwrap_or_default();
                let axis = if row { Axis::Row } else { Axis::Column };
                let children = children.into_iter().map(ViewSpec::into_node).collect();
                ViewNode::Element {
                    id: id.unwrap_or_else(|| "element".into()),
                    style,
                    axis,
                    children,
                }
            }
            ViewSpec::Text { id, style, text } => ViewNode::Text {
                id: id.unwrap_or_else(|| "text".into()),
                text,
                style: style.unwrap_or_default(),
            },
            ViewSpec::Rows {
                id,
                style,
                count,
                first,
                rows,
            } => {
                let mut style = style.unwrap_or_default();
                // Same rule as `virtual_rows_named`: a list fills its parent.
                style.fill = true;
                let row_height = style.row_height;
                let rows: Vec<ViewNode> = rows.into_iter().map(ViewSpec::into_node).collect();
                ViewNode::VirtualRows {
                    id: id.unwrap_or_else(|| "rows".into()),
                    count,
                    style,
                    first: first.min(count.saturating_sub(1)),
                    render: Arc::new(move |index| {
                        rows.get(index).cloned().unwrap_or_else(|| {
                            ViewNode::empty(Style {
                                size: Some(Size::new(0.0, row_height)),
                                ..Style::default()
                            })
                        })
                    }),
                }
            }
        }
    }
}