arc-flow 0.4.0

GPUI node & workflow editor canvas built on arc-flow-core, arc-tokens, arc-motion, and arc-ui.
Documentation
//! F9 无障碍:节点 / 画布的读屏描述与键盘导航顺序。本地设计。
//!
//! - 每个节点在可访问性树里是一个 `Group`,名称为标题,描述为状态与连线(来自谁、连到谁),
//!   并带 `position_in_set / size_of_set`。
//! - 视口外被裁剪掉的节点以合成节点(`a11y_synthetic_children`)挂在画布下的列表里,
//!   保证读屏能遍历整张图,不受视口裁剪影响。
//! - 键盘:Tab / Shift+Tab 按阅读顺序切换节点;Alt+→ / Alt+← 沿连线到下游 / 上游节点,
//!   Alt+↓ / Alt+↑ 在同一组相邻节点之间切换。当前节点为 active descendant,移出视口时画布跟随。

use std::collections::HashSet;

use arc_flow_core::{Graph, NodeId, NodeStatus};
use arc_tokens::Locale;

/// 双语文案。
fn t(locale: Locale, zh: &'static str, en: &'static str) -> &'static str {
    match locale {
        Locale::ZhCn => zh,
        Locale::EnUs => en,
    }
}

pub fn status_label(status: NodeStatus, locale: Locale) -> &'static str {
    match status {
        NodeStatus::Idle => t(locale, "空闲", "idle"),
        NodeStatus::Queued => t(locale, "排队中", "queued"),
        NodeStatus::Running => t(locale, "运行中", "running"),
        NodeStatus::Done => t(locale, "已完成", "done"),
        NodeStatus::Failed => t(locale, "失败", "failed"),
        NodeStatus::Skipped => t(locale, "已跳过", "skipped"),
    }
}

/// 阅读顺序:无环时按拓扑序(源 → 汇),有环时退回插入顺序。
pub fn reading_order(graph: &Graph) -> Vec<NodeId> {
    graph
        .topo_order()
        .unwrap_or_else(|_| graph.node_ids().to_vec())
}

/// 与 `id` 直接相连的上游(`downstream = false`)或下游节点,去重,按世界坐标自上而下、自左而右。
pub fn neighbours(graph: &Graph, id: NodeId, downstream: bool) -> Vec<NodeId> {
    let mut seen = HashSet::new();
    let mut out: Vec<NodeId> = graph
        .edges()
        .filter_map(|e| {
            let from = graph.port(e.from)?.node;
            let to = graph.port(e.to)?.node;
            match downstream {
                true if from == id => Some(to),
                false if to == id => Some(from),
                _ => None,
            }
        })
        .filter(|n| *n != id && seen.insert(*n))
        .collect();
    out.sort_by(|a, b| {
        let pa = graph.world_rect(*a).map(|r| r.min);
        let pb = graph.world_rect(*b).map(|r| r.min);
        match (pa, pb) {
            (Some(a), Some(b)) => a.y.total_cmp(&b.y).then(a.x.total_cmp(&b.x)),
            _ => std::cmp::Ordering::Equal,
        }
    });
    out
}

fn join_labels(graph: &Graph, ids: &[NodeId], locale: Locale) -> String {
    let sep = t(locale, "、", ", ");
    ids.iter()
        .filter_map(|id| graph.node(*id).map(|n| n.label.to_string()))
        .collect::<Vec<_>>()
        .join(sep)
}

/// 节点的读屏描述:状态、子节点数、上游与下游。
pub fn describe_node(graph: &Graph, id: NodeId, locale: Locale) -> String {
    let Some(node) = graph.node(id) else {
        return String::new();
    };
    let mut parts = vec![format!(
        "{}{}",
        t(locale, "状态:", "Status: "),
        status_label(node.status, locale)
    )];
    let children = graph
        .node_ids()
        .iter()
        .filter(|c| graph.node(**c).and_then(|n| n.parent) == Some(id))
        .count();
    if children > 0 {
        parts.push(match locale {
            Locale::ZhCn => format!("包含 {children} 个子节点"),
            Locale::EnUs => format!("contains {children} child nodes"),
        });
    }
    let ups = neighbours(graph, id, false);
    let downs = neighbours(graph, id, true);
    parts.push(if ups.is_empty() {
        t(locale, "没有输入连线", "no incoming edges").to_string()
    } else {
        format!(
            "{}{}",
            t(locale, "来自 ", "from "),
            join_labels(graph, &ups, locale)
        )
    });
    parts.push(if downs.is_empty() {
        t(locale, "没有输出连线", "no outgoing edges").to_string()
    } else {
        format!(
            "{}{}",
            t(locale, "连到 ", "to "),
            join_labels(graph, &downs, locale)
        )
    });
    let sep = t(locale, ";", "; ");
    let end = t(locale, "。", ".");
    format!("{}{end}", parts.join(sep))
}

/// 画布的读屏描述:规模与键盘用法。
pub fn describe_canvas(graph: &Graph, locale: Locale) -> String {
    let (n, e) = (graph.node_count(), graph.edge_count());
    match locale {
        Locale::ZhCn => format!(
            "{n} 个节点,{e} 条连线。Tab 切换节点,Alt+左右方向键沿连线移动,Alt+上下方向键切换相邻节点。"
        ),
        Locale::EnUs => format!(
            "{n} nodes, {e} edges. Tab moves between nodes, Alt+Left/Right follows edges, Alt+Up/Down switches between neighbours."
        ),
    }
}

pub const KEY_SHORTCUTS: &str =
    "Tab Shift+Tab Alt+ArrowLeft Alt+ArrowRight Alt+ArrowUp Alt+ArrowDown";

#[cfg(test)]
mod tests {
    use super::*;
    use arc_flow_core::{Size2, Vec2};

    fn chain() -> (Graph, Vec<NodeId>) {
        let mut g = Graph::new();
        let sz = Size2::new(100.0, 40.0);
        let (a, _, ao) = g.add_node_with("t", Vec2::new(0.0, 0.0), sz, 0, 1);
        let (b, bi, bo) = g.add_node_with("t", Vec2::new(200.0, 0.0), sz, 1, 1);
        let (c, ci, _) = g.add_node_with("t", Vec2::new(400.0, 100.0), sz, 1, 0);
        let (d, di, _) = g.add_node_with("t", Vec2::new(400.0, -100.0), sz, 1, 0);
        g.connect(ao[0], bi[0]).unwrap();
        g.connect(bo[0], ci[0]).unwrap();
        g.connect(bo[0], di[0]).unwrap();
        for (id, name) in [(a, "A"), (b, "B"), (c, "C"), (d, "D")] {
            g.apply(arc_flow_core::GraphOp::SetNodeLabel {
                id,
                label: name.into(),
            })
            .unwrap();
        }
        (g, vec![a, b, c, d])
    }

    #[test]
    fn describes_status_and_connections_in_both_locales() {
        let (mut g, ids) = chain();
        g.set_status(ids[1], NodeStatus::Running);
        assert_eq!(
            describe_node(&g, ids[1], Locale::ZhCn),
            "状态:运行中;来自 A;连到 D、C。"
        );
        assert_eq!(
            describe_node(&g, ids[1], Locale::EnUs),
            "Status: running; from A; to D, C."
        );
        assert_eq!(
            describe_node(&g, ids[0], Locale::ZhCn),
            "状态:空闲;没有输入连线;连到 B。"
        );
        assert!(describe_canvas(&g, Locale::ZhCn).starts_with("4 个节点,3 条连线。"));
    }

    #[test]
    fn reading_order_and_neighbours() {
        let (g, ids) = chain();
        let order = reading_order(&g);
        assert_eq!(order[0], ids[0]);
        assert_eq!(order[1], ids[1]);
        // 下游按自上而下:D(y = −100)在 C 之前。
        assert_eq!(neighbours(&g, ids[1], true), vec![ids[3], ids[2]]);
        assert_eq!(neighbours(&g, ids[1], false), vec![ids[0]]);
        assert!(neighbours(&g, ids[2], true).is_empty());
    }
}