icedwright-semantics 0.0.2

The icedwright semantic tree: inference from recorded widget operations, stable node paths, hit testing, diffs and YAML
Documentation
//! Collecting the tree from a live interface: the probe's recorder through
//! `UserInterface::operate`, then [`infer`]. Behind the `collect` feature.

use iced_runtime::UserInterface;
use icedwright_probe::RawRecorder;
use icedwright_protocol::{RawTree, RawWindowInfo};

use crate::infer::infer;
use crate::tree::SemanticTree;

/// Records one window's interface. Run it after the update that handled the probing event
/// and before `into_cache`, so annotations' cursor readings are this frame's.
pub fn record<Message, Theme, Renderer: iced_core::Renderer>(
    ui: &mut UserInterface<'_, Message, Theme, Renderer>,
    renderer: &Renderer,
    window: RawWindowInfo,
) -> RawTree {
    let mut recorder = RawRecorder::for_window(window);
    ui.operate(renderer, &mut recorder);
    recorder.into_tree()
}

/// The semantic tree of one window's interface.
#[must_use]
pub fn collect<Message, Theme, Renderer: iced_core::Renderer>(
    ui: &mut UserInterface<'_, Message, Theme, Renderer>,
    renderer: &Renderer,
    window: RawWindowInfo,
) -> SemanticTree {
    infer(&record(ui, renderer, window))
}

#[cfg(test)]
mod tests {
    use iced_core::widget::text::Text;
    use iced_core::{Element, Size, Theme};
    use iced_runtime::user_interface::Cache;
    use icedwright_protocol::{RawCall, WindowId};
    use icedwright_types::{Role, ScaleFactor};

    use super::*;

    fn window() -> RawWindowInfo {
        RawWindowInfo {
            id: WindowId(0),
            title: "Hello".to_owned(),
            size: icedwright_types::Size::new(200.0, 100.0),
            scale_factor: ScaleFactor::default(),
        }
    }

    #[test]
    fn a_text_widget_becomes_a_text_node() {
        let mut renderer = ();
        let element: Element<'_, (), Theme, ()> = Text::new("Hi there").into();
        let mut ui = UserInterface::build(
            element,
            Size::new(200.0, 100.0),
            Cache::default(),
            &mut renderer,
        );
        let raw = record(&mut ui, &renderer, window());
        assert_eq!(raw.windows.len(), 1);
        let calls: Vec<&RawCall> = raw.windows[0]
            .root
            .children
            .iter()
            .map(|n| &n.call)
            .collect();
        assert!(
            matches!(calls.as_slice(), [RawCall::Text { content }] if content == "Hi there"),
            "{raw:#?}"
        );

        let tree = collect(&mut ui, &renderer, window());
        let text = tree.iter().find(|n| n.role == Role::Text);
        assert_eq!(text.and_then(|n| n.name.as_deref()), Some("Hi there"));
        let root = tree.roots().first().and_then(|id| tree.get(*id));
        assert_eq!(root.and_then(|n| n.name.as_deref()), Some("Hello"));
        assert_eq!(tree, infer(&raw));
    }
}