Skip to main content

arc_flow/
canvas.rs

1//! `FlowCanvas`:视口(平移 / 滚轮与捏合缩放 / 适配)、分层渲染与视口裁剪(F2),
2//! 选择、框选、拖拽、吸附、连线与重新连接、删除、剪贴板、撤销与快捷键(F3),
3//! 边命中与选中(F4),对齐参考线、小地图、控件栏、锁定与右键菜单回调(F5),
4//! Arc 动效(F6,见 `motion`)。
5//!
6//! 节点内控件若不希望触发拖拽,在其上 `on_mouse_down(.., |_, _, cx| cx.stop_propagation())`
7//! (等价于 xyflow 的 `nodrag`);键盘快捷键只在画布本身持有焦点时生效,不会抢节点内输入框的按键。
8
9use std::cell::Cell;
10use std::collections::{HashMap, HashSet};
11use std::rc::Rc;
12use std::sync::Arc;
13
14use arc_flow_core::edge_path::{infer_target_side, path_between};
15use arc_flow_core::{
16    AlignSnap, Clip, ConnectError, ConnectionValidator, DefaultValidator, Edge, EdgeGeometry,
17    EdgeId, EdgeShape, EdgeState, Graph, GraphOp, Guide, History, Marker, MinimapTransform, NodeId,
18    PortDirection, PortId, Rect, Side, Size2, SpatialGrid, Vec2, Viewport, align_snap, port_anchor,
19};
20use arc_motion::{is_reduced_motion, motion_now};
21use arc_tokens::{ActiveArcLocale as _, ActiveArcTheme as _, Radii, Spacing, Typography};
22use arc_ui::{Button, ButtonSize, ButtonVariant};
23use gpui_kit::{
24    App, BorderStyle, Bounds, Context, Corners, Edges, ElementId, FocusHandle, Focusable,
25    InteractiveElement, IntoElement, KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent,
26    MouseUpEvent, ParentElement, PinchEvent, Pixels, Render, Role, ScrollDelta, ScrollEvent,
27    SharedString, Styled, TestSupportExt as _, Window, assets::IconName, canvas, div, prelude::*,
28    px, quad, size,
29};
30
31use crate::a11y;
32use crate::metrics::*;
33use crate::motion::{Appear, FlowMotion};
34use crate::paint::{EdgeColors, EdgePaint, paint_edge, paint_edge_batch, paint_grid, paint_port};
35use crate::renderer::{DefaultNodeRenderer, NodeRenderCtx, NodeRenderer};
36
37/// 空间索引格子边长(世界 px)。
38const GRID_CELL: f32 = 256.0;
39/// 方向键微移的撤销合并键。
40const NUDGE_KEY: u64 = 0x6e75_6467;
41
42/// 图修订号变化时才重建的派生数据。
43struct DerivedCache {
44    revision: u64,
45    nodes: SpatialGrid<NodeId>,
46    order: HashMap<NodeId, usize>,
47    edge_index: SpatialGrid<EdgeId>,
48    edge_lookup: HashMap<EdgeId, Rc<EdgeGeometry>>,
49    /// 每条边几何的输入;没变就复用上次的几何(F8:拖动少量节点时不必重算全部边)。
50    edge_keys: HashMap<EdgeId, EdgeKey>,
51    /// 每条边的 (源端口, 目标端口, 形状, 源节点, 目标节点),用于判断结构是否变化。
52    edge_ends: HashMap<EdgeId, (PortId, PortId, EdgeShape, NodeId, NodeId)>,
53}
54
55type EdgeKey = (Vec2, Side, Vec2, Side, EdgeShape);
56
57/// 可见集合缓存(F8 静态层缓存):图与视口都没变时直接复用。
58struct VisibleCache {
59    key: (u64, [u32; 5], Option<EdgeId>),
60    nodes: Vec<NodeId>,
61    edges: Vec<(EdgeId, Rc<EdgeGeometry>)>,
62}
63
64/// 节点的细节层级(F8)。
65#[derive(Clone, Copy, Debug, PartialEq, Eq)]
66pub enum Lod {
67    /// 完整渲染(div + 自定义渲染器 + 端口)。
68    Full,
69    /// 只画外壳(圆角矩形),批量绘制。
70    Shell,
71    /// 只画一个点。
72    Dot,
73}
74
75impl DerivedCache {
76    fn empty() -> Self {
77        Self {
78            revision: u64::MAX,
79            nodes: SpatialGrid::new(GRID_CELL),
80            order: HashMap::new(),
81            edge_index: SpatialGrid::new(GRID_CELL),
82            edge_lookup: HashMap::new(),
83            edge_keys: HashMap::new(),
84            edge_ends: HashMap::new(),
85        }
86    }
87}
88
89/// 正在进行的连线(或重新连接)。
90#[derive(Clone, Debug)]
91pub struct ConnectDrag {
92    /// 固定的一端。
93    pub origin: PortId,
94    /// 重新连接时被拾起的边。
95    pub replacing: Option<EdgeId>,
96    /// 指针(世界坐标)。
97    pub pointer: Vec2,
98    /// 吸附到的目标端口。
99    pub target: Option<PortId>,
100    /// 目标端口不合法时的原因。
101    pub error: Option<ConnectError>,
102}
103
104#[derive(Clone, Debug)]
105enum Drag {
106    Pan {
107        last: gpui_kit::Point<Pixels>,
108        start: Vec2,
109        moved: bool,
110        clear_on_click: bool,
111    },
112    Nodes {
113        start: Vec2,
114        origins: Vec<(NodeId, Vec2)>,
115        moved: bool,
116        /// 拖动开始时被拖节点的世界包围盒(首次移动时计算),用于对齐。
117        base: Option<Rect>,
118    },
119    /// 在小地图上按住拖动:视口中心跟随指针。变换在按下时冻结,
120    /// 否则视口移动会改变小地图的内容范围,指针下的世界点随之漂移。
121    Minimap {
122        transform: MinimapTransform,
123        origin: Vec2,
124    },
125    Marquee {
126        start: Vec2,
127        current: Vec2,
128        base: HashSet<NodeId>,
129    },
130    Connect(ConnectDrag),
131}
132
133type ViewportHandler = Rc<dyn Fn(&Viewport, &mut Window, &mut App)>;
134type ConnectErrorHandler = Rc<dyn Fn(&ConnectError, &mut Window, &mut App)>;
135type ContextMenuHandler =
136    Rc<dyn Fn(&ContextTarget, gpui_kit::Point<Pixels>, &mut Window, &mut App)>;
137
138/// 右键菜单的目标。菜单本身由调用方用 arc-ui 的 context-menu(P3)渲染。
139#[derive(Clone, Copy, Debug, PartialEq, Eq)]
140pub enum ContextTarget {
141    Pane,
142    Node(NodeId),
143    Edge(EdgeId),
144}
145
146pub struct FlowCanvas {
147    id: SharedString,
148    graph: Graph,
149    history: History,
150    viewport: Viewport,
151    renderers: HashMap<Arc<str>, Rc<dyn NodeRenderer>>,
152    default_renderer: Rc<dyn NodeRenderer>,
153    validator: Rc<dyn ConnectionValidator>,
154    new_edge_shape: EdgeShape,
155    snap_grid: Option<f32>,
156    focus: FocusHandle,
157    bounds: Rc<Cell<Option<Bounds<Pixels>>>>,
158    cache: DerivedCache,
159    drag: Option<Drag>,
160    selection: HashSet<NodeId>,
161    edge_selection: HashSet<EdgeId>,
162    clipboard: Option<Clip>,
163    paste_count: u32,
164    last_connect_error: Option<ConnectError>,
165    fit_pending: bool,
166    on_viewport_change: Option<ViewportHandler>,
167    on_connect_error: Option<ConnectErrorHandler>,
168    on_context_menu: Option<ContextMenuHandler>,
169    align_guides: bool,
170    guides: Vec<Guide>,
171    show_minimap: bool,
172    show_controls: bool,
173    interactive: bool,
174    motion: FlowMotion,
175    /// 视口动画的终点(连续按缩放键时在它上面累加)。
176    view_target: Option<Viewport>,
177    /// 上一次同步进出场时的节点 / 边集合。
178    known_nodes: HashSet<NodeId>,
179    known_edges: HashSet<EdgeId>,
180    presence_revision: Option<u64>,
181    visible_cache: Option<VisibleCache>,
182    rendered_lod: (usize, usize, usize),
183    /// 键盘沿连线导航的上下文:(出发节点, 是否下游, 在相邻节点中的序号)。
184    nav_ring: Option<(NodeId, bool, usize)>,
185    /// 阅读顺序缓存:(图修订号, 节点 → 序号)。
186    reading_order: (u64, HashMap<NodeId, usize>),
187    /// 画布的可访问名称。
188    label: SharedString,
189    rendered_offscreen: usize,
190    rendered_nodes: usize,
191    rendered_edges: usize,
192}
193
194impl Focusable for FlowCanvas {
195    fn focus_handle(&self, _: &App) -> FocusHandle {
196        self.focus.clone()
197    }
198}
199
200impl FlowCanvas {
201    pub fn new(id: impl Into<SharedString>, graph: Graph, cx: &mut Context<Self>) -> Self {
202        Self {
203            id: id.into(),
204            graph,
205            history: History::default(),
206            viewport: Viewport::default(),
207            renderers: HashMap::new(),
208            default_renderer: Rc::new(DefaultNodeRenderer),
209            validator: Rc::new(DefaultValidator::default()),
210            new_edge_shape: EdgeShape::Bezier { curvature: 0.25 },
211            snap_grid: None,
212            focus: cx.focus_handle(),
213            bounds: Rc::new(Cell::new(None)),
214            cache: DerivedCache::empty(),
215            drag: None,
216            selection: HashSet::new(),
217            edge_selection: HashSet::new(),
218            clipboard: None,
219            paste_count: 0,
220            last_connect_error: None,
221            fit_pending: false,
222            on_viewport_change: None,
223            on_connect_error: None,
224            on_context_menu: None,
225            align_guides: true,
226            guides: Vec::new(),
227            show_minimap: false,
228            show_controls: false,
229            interactive: true,
230            motion: FlowMotion::default(),
231            view_target: None,
232            known_nodes: HashSet::new(),
233            known_edges: HashSet::new(),
234            presence_revision: None,
235            visible_cache: None,
236            rendered_lod: (0, 0, 0),
237            nav_ring: None,
238            reading_order: (u64::MAX, HashMap::new()),
239            label: SharedString::from("Flow canvas"),
240            rendered_offscreen: 0,
241            rendered_nodes: 0,
242            rendered_edges: 0,
243        }
244    }
245
246    // ---------- 构建 ----------
247
248    /// 为某种 `Node::kind` 注册渲染器。
249    pub fn renderer(mut self, kind: impl Into<Arc<str>>, renderer: impl NodeRenderer) -> Self {
250        self.renderers.insert(kind.into(), Rc::new(renderer));
251        self
252    }
253
254    /// 连线校验器,默认 [`DefaultValidator`](允许成环);工作流可用 `DefaultValidator::dag()`。
255    pub fn validator(mut self, validator: impl ConnectionValidator + 'static) -> Self {
256        self.validator = Rc::new(validator);
257        self
258    }
259
260    /// 新建连线的形状。
261    pub fn new_edge_shape(mut self, shape: EdgeShape) -> Self {
262        self.new_edge_shape = shape;
263        self
264    }
265
266    /// 拖拽时吸附到网格(世界 px)。
267    pub fn snap_to_grid(mut self, grid: Option<f32>) -> Self {
268        self.snap_grid = grid.filter(|g| *g > 0.0);
269        self
270    }
271
272    /// 首次布局后自动适配视图。
273    /// 拖动节点时与其他节点的边线 / 中线对齐并画参考线(默认开启)。
274    pub fn align_guides(mut self, enabled: bool) -> Self {
275        self.align_guides = enabled;
276        self
277    }
278
279    /// 右下角小地图(点击或拖动可移动视口)。
280    pub fn minimap(mut self, show: bool) -> Self {
281        self.show_minimap = show;
282        self
283    }
284
285    /// 左下角控件栏:放大、缩小、适配视图、锁定编辑。
286    pub fn controls(mut self, show: bool) -> Self {
287        self.show_controls = show;
288        self
289    }
290
291    /// 右键回调:给出目标与窗口坐标,调用方据此弹出菜单。
292    pub fn on_context_menu(
293        mut self,
294        handler: impl Fn(&ContextTarget, gpui_kit::Point<Pixels>, &mut Window, &mut App) + 'static,
295    ) -> Self {
296        self.on_context_menu = Some(Rc::new(handler));
297        self
298    }
299
300    pub fn fit_on_mount(mut self) -> Self {
301        self.fit_pending = true;
302        self
303    }
304
305    pub fn initial_viewport(mut self, viewport: Viewport) -> Self {
306        self.viewport = viewport;
307        self
308    }
309
310    pub fn on_viewport_change(
311        mut self,
312        handler: impl Fn(&Viewport, &mut Window, &mut App) + 'static,
313    ) -> Self {
314        self.on_viewport_change = Some(Rc::new(handler));
315        self
316    }
317
318    /// 连线被拒时回调(F5 接 toast)。
319    pub fn on_connect_error(
320        mut self,
321        handler: impl Fn(&ConnectError, &mut Window, &mut App) + 'static,
322    ) -> Self {
323        self.on_connect_error = Some(Rc::new(handler));
324        self
325    }
326
327    // ---------- 读写 ----------
328
329    pub fn graph(&self) -> &Graph {
330        &self.graph
331    }
332
333    /// 直接修改图(运行状态等,不进撤销历史);结束后自动重绘。
334    pub fn update_graph<R>(
335        &mut self,
336        cx: &mut Context<Self>,
337        f: impl FnOnce(&mut Graph) -> R,
338    ) -> R {
339        let r = f(&mut self.graph);
340        self.prune_selection();
341        cx.notify();
342        r
343    }
344
345    /// 应用一个可撤销的操作。
346    pub fn commit(
347        &mut self,
348        op: GraphOp,
349        label: &'static str,
350        cx: &mut Context<Self>,
351    ) -> Result<(), arc_flow_core::GraphError> {
352        let r = self.history.commit(&mut self.graph, op, label);
353        self.prune_selection();
354        cx.notify();
355        r
356    }
357
358    pub fn history(&self) -> &History {
359        &self.history
360    }
361
362    pub fn undo(&mut self, cx: &mut Context<Self>) {
363        let _ = self.history.undo(&mut self.graph);
364        self.prune_selection();
365        cx.notify();
366    }
367
368    pub fn redo(&mut self, cx: &mut Context<Self>) {
369        let _ = self.history.redo(&mut self.graph);
370        self.prune_selection();
371        cx.notify();
372    }
373
374    pub fn selection(&self) -> &HashSet<NodeId> {
375        &self.selection
376    }
377
378    pub fn edge_selection(&self) -> &HashSet<EdgeId> {
379        &self.edge_selection
380    }
381
382    pub fn select_edges(&mut self, ids: impl IntoIterator<Item = EdgeId>, cx: &mut Context<Self>) {
383        self.edge_selection = ids
384            .into_iter()
385            .filter(|id| self.graph.edge(*id).is_some())
386            .collect();
387        cx.notify();
388    }
389
390    pub fn select(&mut self, ids: impl IntoIterator<Item = NodeId>, cx: &mut Context<Self>) {
391        self.selection = ids
392            .into_iter()
393            .filter(|id| self.graph.node(*id).is_some())
394            .collect();
395        cx.notify();
396    }
397
398    /// 正在进行的连线草稿(测试与外部提示用)。
399    pub fn connect_drag(&self) -> Option<&ConnectDrag> {
400        match &self.drag {
401            Some(Drag::Connect(c)) => Some(c),
402            _ => None,
403        }
404    }
405
406    pub fn last_connect_error(&self) -> Option<&ConnectError> {
407        self.last_connect_error.as_ref()
408    }
409
410    /// 是否允许编辑(拖动、连线、删除、粘贴、选择)。锁定时仍可平移缩放。
411    pub fn interactive(&self) -> bool {
412        self.interactive
413    }
414
415    pub fn set_interactive(&mut self, interactive: bool, cx: &mut Context<Self>) {
416        self.interactive = interactive;
417        if !interactive {
418            self.selection.clear();
419            self.edge_selection.clear();
420            self.drag = None;
421        }
422        cx.notify();
423    }
424
425    /// 当前绘制中的对齐参考线(世界坐标)。
426    pub fn guides(&self) -> &[Guide] {
427        &self.guides
428    }
429
430    pub fn viewport(&self) -> Viewport {
431        self.viewport
432    }
433
434    /// 画布在可访问性树中的名称(默认 “Flow canvas”)。
435    pub fn aria_label(mut self, label: impl Into<SharedString>) -> Self {
436        self.label = label.into();
437        self
438    }
439
440    /// 上一帧以合成可访问节点暴露的视口外节点数(F9)。
441    pub fn rendered_offscreen(&self) -> usize {
442        self.rendered_offscreen
443    }
444
445    /// 键盘导航的当前节点:恰好选中一个节点时即它。
446    pub fn active_node(&self) -> Option<NodeId> {
447        (self.selection.len() == 1)
448            .then(|| self.selection.iter().next().copied())
449            .flatten()
450    }
451
452    fn ensure_reading_order(&mut self) {
453        let rev = self.graph.revision();
454        if self.reading_order.0 != rev {
455            let order = a11y::reading_order(&self.graph)
456                .into_iter()
457                .enumerate()
458                .map(|(i, id)| (id, i))
459                .collect();
460            self.reading_order = (rev, order);
461        }
462    }
463
464    /// 键盘导航到节点:选中它,必要时把视口平移过去(保持缩放)。
465    fn nav_to(&mut self, id: NodeId, window: &mut Window, cx: &mut Context<Self>) {
466        self.selection = HashSet::from([id]);
467        self.edge_selection.clear();
468        if let (Some(rect), Some(view)) = (self.graph.world_rect(id), self.view_size()) {
469            let target = self.target_viewport();
470            let shown = target
471                .visible_world_rect(view)
472                .inflate(-FIT_PADDING / target.zoom);
473            if !shown.contains_rect(&rect) {
474                let mut vp = target;
475                vp.offset = self.view_center().minus(rect.center().scale(vp.zoom));
476                self.animate_viewport(vp, window, cx);
477            }
478        }
479        cx.notify();
480    }
481
482    /// Tab / Shift+Tab / Alt+方向键。返回是否处理。
483    fn on_nav_key(
484        &mut self,
485        key: &str,
486        shift: bool,
487        alt: bool,
488        window: &mut Window,
489        cx: &mut Context<Self>,
490    ) -> bool {
491        let active = self.active_node();
492        match (key, alt) {
493            ("tab", false) => {
494                let order = a11y::reading_order(&self.graph);
495                if order.is_empty() {
496                    return true;
497                }
498                let n = order.len();
499                let next = match active.and_then(|a| order.iter().position(|x| *x == a)) {
500                    Some(i) if shift => (i + n - 1) % n,
501                    Some(i) => (i + 1) % n,
502                    None if shift => n - 1,
503                    None => 0,
504                };
505                self.nav_ring = None;
506                self.nav_to(order[next], window, cx);
507                true
508            }
509            ("right" | "left", true) => {
510                let Some(a) = active else {
511                    return true;
512                };
513                let downstream = key == "right";
514                if let Some(first) = a11y::neighbours(&self.graph, a, downstream).first() {
515                    self.nav_ring = Some((a, downstream, 0));
516                    self.nav_to(*first, window, cx);
517                }
518                true
519            }
520            ("down" | "up", true) => {
521                let Some((origin, downstream, i)) = self.nav_ring else {
522                    return true;
523                };
524                let ring = a11y::neighbours(&self.graph, origin, downstream);
525                if ring.is_empty() || active != ring.get(i).copied() {
526                    self.nav_ring = None;
527                    return true;
528                }
529                let n = ring.len();
530                let j = if key == "down" {
531                    (i + 1) % n
532                } else {
533                    (i + n - 1) % n
534                };
535                self.nav_ring = Some((origin, downstream, j));
536                self.nav_to(ring[j], window, cx);
537                true
538            }
539            _ => false,
540        }
541    }
542
543    /// 上一帧按细节层级统计的节点数:(完整, 外壳, 点)。
544    pub fn rendered_lod(&self) -> (usize, usize, usize) {
545        self.rendered_lod
546    }
547
548    pub fn rendered_counts(&self) -> (usize, usize) {
549        (self.rendered_nodes, self.rendered_edges)
550    }
551
552    pub fn set_viewport(
553        &mut self,
554        viewport: Viewport,
555        window: &mut Window,
556        cx: &mut Context<Self>,
557    ) {
558        self.stop_view_animation();
559        self.viewport = viewport;
560        self.viewport_changed(window, cx);
561    }
562
563    /// 平滑过渡到 `target`(`spring.smooth`);reduced motion 下立即跳转。
564    pub fn animate_viewport(
565        &mut self,
566        target: Viewport,
567        window: &mut Window,
568        cx: &mut Context<Self>,
569    ) {
570        let now = self.motion_now(cx);
571        let center = self.view_center();
572        if self
573            .motion
574            .animate_view(&self.viewport, &target, center, now)
575        {
576            self.view_target = Some(target);
577            cx.notify();
578        } else {
579            self.view_target = None;
580            self.viewport = target;
581            self.viewport_changed(window, cx);
582        }
583    }
584
585    /// 视口动画的终点;没有动画时即当前视口。
586    pub fn target_viewport(&self) -> Viewport {
587        self.view_target.unwrap_or(self.viewport)
588    }
589
590    fn stop_view_animation(&mut self) {
591        self.motion.cancel_view();
592        self.view_target = None;
593    }
594
595    /// 动效时钟(随 gallery 慢放缩放),顺带同步 reduced motion 设置。
596    fn motion_now(&mut self, cx: &mut App) -> f64 {
597        self.motion.set_reduced(is_reduced_motion(cx));
598        motion_now(cx)
599    }
600
601    /// 只读访问动效状态(测试与调试)。
602    pub fn motion(&self) -> &FlowMotion {
603        &self.motion
604    }
605
606    /// 节点显示位置相对模型位置的偏移(含祖先的偏移)。
607    fn visual_offset(&self, id: NodeId, now: f64) -> Vec2 {
608        if !self.motion.has_offsets() {
609            return Vec2::ZERO;
610        }
611        let mut sum = Vec2::ZERO;
612        let mut cur = Some(id);
613        while let Some(c) = cur {
614            sum = sum.plus(self.motion.own_offset(c, now));
615            cur = self.graph.node(c).and_then(|n| n.parent);
616        }
617        sum
618    }
619
620    /// 图修订号变化后,对比节点 / 边集合,给新出现的节点进场、新出现的边绘入。
621    fn sync_presence(&mut self, now: f64) {
622        let rev = self.graph.revision();
623        if self.presence_revision == Some(rev) {
624            return;
625        }
626        let nodes: HashSet<NodeId> = self.graph.node_ids().iter().copied().collect();
627        let edges: HashSet<EdgeId> = self.graph.edges().map(|e| e.id).collect();
628        if self.presence_revision.is_some() {
629            for id in nodes.difference(&self.known_nodes) {
630                self.motion.drop_ghost(*id);
631                self.motion.node_entered(*id, now);
632            }
633            for id in edges.difference(&self.known_edges) {
634                self.motion.edge_added(*id, now);
635            }
636        }
637        self.known_nodes = nodes;
638        self.known_edges = edges;
639        self.presence_revision = Some(rev);
640    }
641
642    fn viewport_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
643        if let Some(h) = self.on_viewport_change.clone() {
644            h(&self.viewport, window, cx);
645        }
646        cx.notify();
647    }
648
649    fn view_size(&self) -> Option<Size2> {
650        self.bounds
651            .get()
652            .map(|b| Size2::new(f32::from(b.size.width), f32::from(b.size.height)))
653    }
654
655    fn view_center(&self) -> Vec2 {
656        self.view_size()
657            .map(|s| Vec2::new(s.w / 2.0, s.h / 2.0))
658            .unwrap_or(Vec2::ZERO)
659    }
660
661    /// 适配全部节点;画布尚未布局时推迟到首帧。
662    pub fn fit_view(&mut self, window: &mut Window, cx: &mut Context<Self>) {
663        match (self.view_size(), self.graph.bounds()) {
664            (Some(view), Some(world)) => {
665                let mut target = self.target_viewport();
666                target.fit(&world, view, FIT_PADDING);
667                self.fit_pending = false;
668                self.animate_viewport(target, window, cx);
669            }
670            (None, _) => {
671                self.fit_pending = true;
672                cx.notify();
673            }
674            (Some(_), None) => self.fit_pending = false,
675        }
676    }
677
678    /// 以画布中心缩放。
679    pub fn zoom_by(&mut self, factor: f32, window: &mut Window, cx: &mut Context<Self>) {
680        let center = self.view_center();
681        let mut target = self.target_viewport();
682        target.zoom_by_at(factor, center);
683        self.animate_viewport(target, window, cx);
684    }
685
686    fn local(&self, p: gpui_kit::Point<Pixels>) -> Vec2 {
687        let o = self.bounds.get().map(|b| b.origin).unwrap_or_default();
688        Vec2::new(f32::from(p.x - o.x), f32::from(p.y - o.y))
689    }
690
691    fn refresh_cache(&mut self) {
692        if self.cache.revision == self.graph.revision() {
693            return;
694        }
695        if !self.refresh_cache_incremental() {
696            self.rebuild_cache();
697        }
698        self.cache.revision = self.graph.revision();
699    }
700
701    /// 端口所属节点。
702    fn port_node(&self, port: PortId) -> Option<NodeId> {
703        self.graph.port(port).map(|p| p.node)
704    }
705
706    fn edge_geometry_for(&self, e: &Edge) -> Option<(EdgeKey, Rc<EdgeGeometry>)> {
707        let (a, sa) = port_anchor(&self.graph, e.from)?;
708        let (b, sb) = port_anchor(&self.graph, e.to)?;
709        let key: EdgeKey = (a, sa, b, sb, e.shape);
710        let geo = match (
711            self.cache.edge_keys.get(&e.id),
712            self.cache.edge_lookup.get(&e.id),
713        ) {
714            (Some(k), Some(g)) if *k == key => g.clone(),
715            _ => Rc::new(path_between(a, sa, b, sb, e.shape)),
716        };
717        Some((key, geo))
718    }
719
720    /// 结构(节点集合、边的端口与形状)没变、只是节点移动或缩放时,只更新动过的节点
721    /// 和连到它们的边(F8:拖动 200 个节点时不必重建 5,000 节点 / 8,000 边的索引)。
722    fn refresh_cache_incremental(&mut self) -> bool {
723        if self.cache.revision == u64::MAX
724            || self.graph.node_count() != self.cache.nodes.len()
725            || self.graph.edge_count() != self.cache.edge_ends.len()
726        {
727            return false;
728        }
729        let same_edges = self.graph.edges().all(|e| {
730            self.cache
731                .edge_ends
732                .get(&e.id)
733                .is_some_and(|x| x.0 == e.from && x.1 == e.to && x.2 == e.shape)
734        });
735        if !same_edges {
736            return false;
737        }
738        let mut moved = HashSet::new();
739        for id in self.graph.node_ids() {
740            let Some(old) = self.cache.nodes.rect(*id) else {
741                return false;
742            };
743            let Some(new) = self.graph.world_rect(*id) else {
744                return false;
745            };
746            if old != new {
747                moved.insert(*id);
748            }
749        }
750        // 绘制顺序(置顶会改变它)。
751        self.cache.order = self
752            .graph
753            .node_ids()
754            .iter()
755            .enumerate()
756            .map(|(i, id)| (*id, i))
757            .collect();
758        if moved.is_empty() {
759            return true;
760        }
761        for id in &moved {
762            if let Some(r) = self.graph.world_rect(*id) {
763                self.cache.nodes.insert(*id, r);
764            }
765        }
766        let affected: Vec<EdgeId> = self
767            .cache
768            .edge_ends
769            .iter()
770            .filter(|(_, x)| moved.contains(&x.3) || moved.contains(&x.4))
771            .map(|(id, _)| *id)
772            .collect();
773        for id in affected {
774            let Some(e) = self.graph.edge(id) else {
775                continue;
776            };
777            if let Some((key, geo)) = self.edge_geometry_for(e) {
778                self.cache.edge_index.insert(id, geo.bounds);
779                self.cache.edge_lookup.insert(id, geo);
780                self.cache.edge_keys.insert(id, key);
781            }
782        }
783        true
784    }
785
786    fn rebuild_cache(&mut self) {
787        let mut nodes = SpatialGrid::new(GRID_CELL);
788        let mut order = HashMap::with_capacity(self.graph.node_count());
789        for (i, id) in self.graph.node_ids().iter().enumerate() {
790            order.insert(*id, i);
791            if let Some(r) = self.graph.world_rect(*id) {
792                nodes.insert(*id, r);
793            }
794        }
795        let n = self.graph.edge_count();
796        let mut edge_keys = HashMap::with_capacity(n);
797        let mut edge_ends = HashMap::with_capacity(n);
798        let mut edge_index = SpatialGrid::new(GRID_CELL);
799        let mut edge_lookup = HashMap::with_capacity(n);
800        for e in self.graph.edges() {
801            let (Some(fa), Some(fb)) = (self.port_node(e.from), self.port_node(e.to)) else {
802                continue;
803            };
804            edge_ends.insert(e.id, (e.from, e.to, e.shape, fa, fb));
805            if let Some((key, geo)) = self.edge_geometry_for(e) {
806                edge_index.insert(e.id, geo.bounds);
807                edge_lookup.insert(e.id, geo);
808                edge_keys.insert(e.id, key);
809            }
810        }
811        self.cache = DerivedCache {
812            revision: self.graph.revision(),
813            nodes,
814            order,
815            edge_index,
816            edge_lookup,
817            edge_keys,
818            edge_ends,
819        };
820    }
821
822    fn prune_selection(&mut self) {
823        let g = &self.graph;
824        self.selection.retain(|id| g.node(*id).is_some());
825        self.edge_selection.retain(|id| g.edge(*id).is_some());
826    }
827
828    // ---------- 命中测试 ----------
829
830    /// 最上层(绘制顺序最后)的节点。
831    fn hit_node(&mut self, world: Vec2) -> Option<NodeId> {
832        self.refresh_cache();
833        let probe = Rect::from_corners(world, world);
834        self.cache
835            .nodes
836            .query(&probe)
837            .into_iter()
838            .filter(|id| {
839                self.graph
840                    .world_rect(*id)
841                    .is_some_and(|r| r.contains(world))
842            })
843            .max_by_key(|id| self.cache.order.get(id).copied().unwrap_or(0))
844    }
845
846    /// `radius` 为屏幕 px;可按方向过滤。返回最近的端口。
847    fn hit_port(
848        &mut self,
849        world: Vec2,
850        radius: f32,
851        want: Option<PortDirection>,
852    ) -> Option<PortId> {
853        self.refresh_cache();
854        let r = radius / self.viewport.zoom;
855        let probe = Rect::from_corners(world, world).inflate(r);
856        let mut best: Option<(f32, PortId)> = None;
857        for node in self.cache.nodes.query(&probe) {
858            for p in self.graph.ports_of(node) {
859                if want.is_some_and(|w| w != p.direction) {
860                    continue;
861                }
862                let Some((a, _)) = port_anchor(&self.graph, p.id) else {
863                    continue;
864                };
865                let d = a.distance(world);
866                if d <= r && best.is_none_or(|(bd, _)| d < bd) {
867                    best = Some((d, p.id));
868                }
869            }
870        }
871        best.map(|(_, id)| id)
872    }
873
874    /// 距离最近的边(容差为屏幕 px)。
875    fn hit_edge(&mut self, world: Vec2, radius: f32) -> Option<EdgeId> {
876        self.refresh_cache();
877        let r = radius / self.viewport.zoom;
878        self.cache
879            .edge_index
880            .query_point(world, r)
881            .into_iter()
882            .filter_map(|id| {
883                let d = self.cache.edge_lookup.get(&id)?.distance_to(world);
884                (d <= r).then_some((d, id))
885            })
886            .min_by(|a, b| a.0.total_cmp(&b.0))
887            .map(|(_, id)| id)
888    }
889
890    /// `id` 是否是 `roots` 之一或其后代。
891    fn in_subtree(&self, id: NodeId, roots: &HashSet<NodeId>) -> bool {
892        let mut cur = Some(id);
893        while let Some(c) = cur {
894            if roots.contains(&c) {
895                return true;
896            }
897            cur = self.graph.node(c).and_then(|n| n.parent);
898        }
899        false
900    }
901
902    /// 被拖动的包围盒(已含增量)相对可见的其他节点的对齐吸附。
903    fn compute_align(&mut self, moving: Rect, roots: &HashSet<NodeId>) -> AlignSnap {
904        self.refresh_cache();
905        let tol = ALIGN_SNAP_RADIUS / self.viewport.zoom;
906        let area = match self.view_size() {
907            Some(v) => self.viewport.visible_world_rect(v),
908            None => moving.inflate(1024.0),
909        };
910        let others: Vec<Rect> = self
911            .cache
912            .nodes
913            .query(&area)
914            .into_iter()
915            .filter(|id| !self.in_subtree(*id, roots))
916            .filter_map(|id| self.graph.world_rect(id))
917            .collect();
918        align_snap(moving, &others, tol)
919    }
920
921    /// 小地图的坐标变换与其在画布内的左上角(屏幕坐标)。
922    fn minimap_transform(&self) -> Option<(MinimapTransform, Vec2)> {
923        let view = self.view_size()?;
924        let visible = self.viewport.visible_world_rect(view);
925        let content = self.graph.bounds().map_or(visible, |b| b.union(visible));
926        let t = MinimapTransform::new(
927            content,
928            Size2::new(MINIMAP_WIDTH, MINIMAP_HEIGHT),
929            MINIMAP_PADDING,
930        );
931        let origin = Vec2::new(
932            view.w - MINIMAP_WIDTH - OVERLAY_MARGIN,
933            view.h - MINIMAP_HEIGHT - OVERLAY_MARGIN,
934        );
935        Some((t, origin))
936    }
937
938    /// 把视口中心移到小地图上 `local`(画布坐标)对应的世界点。
939    fn center_from_minimap(
940        &mut self,
941        t: &MinimapTransform,
942        origin: Vec2,
943        local: Vec2,
944        window: &mut Window,
945        cx: &mut Context<Self>,
946    ) {
947        let target = t.to_world(local.minus(origin));
948        let center = self.viewport.screen_to_world(self.view_center());
949        self.viewport
950            .pan_by(center.minus(target).scale(self.viewport.zoom));
951        self.viewport_changed(window, cx);
952    }
953
954    fn on_minimap_down(
955        &mut self,
956        ev: &MouseDownEvent,
957        window: &mut Window,
958        cx: &mut Context<Self>,
959    ) {
960        window.focus(&self.focus, cx);
961        self.stop_view_animation();
962        let local = self.local(ev.position);
963        let Some((transform, origin)) = self.minimap_transform() else {
964            return;
965        };
966        self.center_from_minimap(&transform, origin, local, window, cx);
967        self.drag = Some(Drag::Minimap { transform, origin });
968        cx.stop_propagation();
969        cx.notify();
970    }
971
972    fn on_right_down(&mut self, ev: &MouseDownEvent, window: &mut Window, cx: &mut Context<Self>) {
973        window.focus(&self.focus, cx);
974        let Some(handler) = self.on_context_menu.clone() else {
975            return;
976        };
977        let world = self.viewport.screen_to_world(self.local(ev.position));
978        let target = if let Some(n) = self.hit_node(world) {
979            ContextTarget::Node(n)
980        } else if let Some(e) = self.hit_edge(world, EDGE_HIT_RADIUS) {
981            ContextTarget::Edge(e)
982        } else {
983            ContextTarget::Pane
984        };
985        // 与桌面习惯一致:右键未选中的元素时先改为选中它。
986        if self.interactive {
987            match target {
988                ContextTarget::Node(n) if !self.selection.contains(&n) => {
989                    self.selection = HashSet::from([n]);
990                    self.edge_selection.clear();
991                }
992                ContextTarget::Edge(e) if !self.edge_selection.contains(&e) => {
993                    self.selection.clear();
994                    self.edge_selection = HashSet::from([e]);
995                }
996                _ => {}
997            }
998        }
999        cx.stop_propagation();
1000        cx.notify();
1001        handler(&target, ev.position, window, cx);
1002    }
1003
1004    /// 选中边的源端把手:返回 (边, 固定的目标端口)。
1005    fn hit_selected_edge_source(&self, world: Vec2) -> Option<(EdgeId, PortId)> {
1006        let r = PORT_HIT_RADIUS / self.viewport.zoom;
1007        self.edge_selection.iter().find_map(|id| {
1008            let e = self.graph.edge(*id)?;
1009            let (a, _) = port_anchor(&self.graph, e.from)?;
1010            (a.distance(world) <= r).then_some((e.id, e.to))
1011        })
1012    }
1013
1014    /// 被选中且祖先未被选中的节点(拖拽 / 复制的根)。
1015    fn selection_roots(&self) -> Vec<NodeId> {
1016        let mut roots: Vec<NodeId> = self
1017            .selection
1018            .iter()
1019            .copied()
1020            .filter(|id| {
1021                !self
1022                    .selection
1023                    .iter()
1024                    .any(|other| other != id && self.graph.is_ancestor(*other, *id))
1025            })
1026            .collect();
1027        roots.sort_by_key(|id| self.cache.order.get(id).copied().unwrap_or(usize::MAX));
1028        roots
1029    }
1030
1031    // ---------- 指针 ----------
1032
1033    fn on_left_down(&mut self, ev: &MouseDownEvent, window: &mut Window, cx: &mut Context<Self>) {
1034        window.focus(&self.focus, cx);
1035        self.stop_view_animation();
1036        self.history.seal();
1037        let local = self.local(ev.position);
1038        let world = self.viewport.screen_to_world(local);
1039        let additive = ev.modifiers.shift || ev.modifiers.secondary(cx) || ev.modifiers.control;
1040
1041        if !self.interactive {
1042            self.drag = Some(Drag::Pan {
1043                last: ev.position,
1044                start: local,
1045                moved: false,
1046                clear_on_click: false,
1047            });
1048        } else if let Some((edge, fixed)) = self.hit_selected_edge_source(world) {
1049            // 选中边的源端把手:固定目标端,拖动源端重新连接。
1050            self.drag = Some(Drag::Connect(ConnectDrag {
1051                origin: fixed,
1052                replacing: Some(edge),
1053                pointer: world,
1054                target: None,
1055                error: None,
1056            }));
1057        } else if let Some(port) = self.hit_port(world, PORT_HIT_RADIUS, None) {
1058            self.begin_connect(port, world);
1059        } else if let Some(node) = self.hit_node(world) {
1060            if !additive {
1061                self.edge_selection.clear();
1062            }
1063            if additive {
1064                if !self.selection.remove(&node) {
1065                    self.selection.insert(node);
1066                }
1067            } else if !self.selection.contains(&node) {
1068                self.selection = HashSet::from([node]);
1069            }
1070            if self.selection.contains(&node) {
1071                let origins = self
1072                    .selection_roots()
1073                    .into_iter()
1074                    .filter_map(|id| self.graph.node(id).map(|n| (id, n.pos)))
1075                    .collect();
1076                self.drag = Some(Drag::Nodes {
1077                    start: local,
1078                    origins,
1079                    moved: false,
1080                    base: None,
1081                });
1082            }
1083        } else if let Some(edge) = self.hit_edge(world, EDGE_HIT_RADIUS) {
1084            if additive {
1085                if !self.edge_selection.remove(&edge) {
1086                    self.edge_selection.insert(edge);
1087                }
1088            } else {
1089                self.selection.clear();
1090                self.edge_selection = HashSet::from([edge]);
1091            }
1092        } else if ev.modifiers.shift {
1093            self.drag = Some(Drag::Marquee {
1094                start: local,
1095                current: local,
1096                base: self.selection.clone(),
1097            });
1098        } else {
1099            self.drag = Some(Drag::Pan {
1100                last: ev.position,
1101                start: local,
1102                moved: false,
1103                clear_on_click: !additive,
1104            });
1105        }
1106        cx.stop_propagation();
1107        cx.notify();
1108    }
1109
1110    fn on_middle_down(&mut self, ev: &MouseDownEvent, window: &mut Window, cx: &mut Context<Self>) {
1111        window.focus(&self.focus, cx);
1112        self.stop_view_animation();
1113        self.drag = Some(Drag::Pan {
1114            last: ev.position,
1115            start: self.local(ev.position),
1116            moved: false,
1117            clear_on_click: false,
1118        });
1119        cx.notify();
1120    }
1121
1122    fn begin_connect(&mut self, port: PortId, world: Vec2) {
1123        let Some(p) = self.graph.port(port) else {
1124            return;
1125        };
1126        // 从已占用的输入端拖动 = 拾起最后一条边重新连接(xyflow 的 reconnect 手感)。
1127        let (origin, replacing) = match (p.direction, self.graph.edges_of_port(port).last()) {
1128            (PortDirection::Input, Some(e)) => match self.graph.edge(*e) {
1129                Some(edge) => (edge.from, Some(edge.id)),
1130                None => (port, None),
1131            },
1132            _ => (port, None),
1133        };
1134        self.drag = Some(Drag::Connect(ConnectDrag {
1135            origin,
1136            replacing,
1137            pointer: world,
1138            target: None,
1139            error: None,
1140        }));
1141    }
1142
1143    fn on_drag_move(
1144        &mut self,
1145        position: gpui_kit::Point<Pixels>,
1146        window: &mut Window,
1147        cx: &mut Context<Self>,
1148    ) {
1149        let local = self.local(position);
1150        let zoom = self.viewport.zoom;
1151        let now = self.motion_now(cx);
1152        let Some(drag) = self.drag.take() else {
1153            return;
1154        };
1155        let drag = match drag {
1156            Drag::Pan {
1157                last,
1158                start,
1159                moved,
1160                clear_on_click,
1161            } => {
1162                let d = position - last;
1163                self.viewport
1164                    .pan_by(Vec2::new(f32::from(d.x), f32::from(d.y)));
1165                self.viewport_changed(window, cx);
1166                Drag::Pan {
1167                    last: position,
1168                    start,
1169                    moved: moved || local.distance(start) > DRAG_THRESHOLD,
1170                    clear_on_click,
1171                }
1172            }
1173            Drag::Nodes {
1174                start,
1175                origins,
1176                moved,
1177                mut base,
1178            } => {
1179                let moved = moved || local.distance(start) > DRAG_THRESHOLD;
1180                if moved && let Some((_, first)) = origins.first() {
1181                    if base.is_none() {
1182                        // 首次移动前图里仍是原位置。
1183                        base = origins
1184                            .iter()
1185                            .filter_map(|(id, _)| self.graph.world_rect(*id))
1186                            .reduce(|a, b| a.union(b));
1187                    }
1188                    let raw = local.minus(start).scale(1.0 / zoom);
1189                    let mut delta = raw;
1190                    if let Some(g) = self.snap_grid {
1191                        delta = first.plus(delta).snap(g).minus(*first);
1192                    }
1193                    self.guides.clear();
1194                    if self.align_guides
1195                        && let Some(b) = base
1196                    {
1197                        let roots: HashSet<NodeId> = origins.iter().map(|(id, _)| *id).collect();
1198                        let moving = Rect {
1199                            min: b.min.plus(delta),
1200                            max: b.max.plus(delta),
1201                        };
1202                        let snap = self.compute_align(moving, &roots);
1203                        // 参考线优先于网格:对齐的轴上取消网格取整。
1204                        delta = delta.plus(Vec2::new(snap.dx, snap.dy));
1205                        self.guides = snap.guides;
1206                    }
1207                    let moves = origins.iter().map(|(id, o)| (*id, o.plus(delta))).collect();
1208                    let _ = self.graph.apply(GraphOp::MoveNodes { moves });
1209                    // 模型落在吸附位置,显示跟手;松手后弹簧落位(reduced motion 下直接吸附)。
1210                    let follow = if self.motion.reduced() {
1211                        Vec2::ZERO
1212                    } else {
1213                        raw.minus(delta)
1214                    };
1215                    for (id, _) in &origins {
1216                        self.motion.set_live_offset(*id, follow);
1217                    }
1218                    cx.notify();
1219                }
1220                Drag::Nodes {
1221                    start,
1222                    origins,
1223                    moved,
1224                    base,
1225                }
1226            }
1227            Drag::Minimap { transform, origin } => {
1228                self.center_from_minimap(&transform, origin, local, window, cx);
1229                Drag::Minimap { transform, origin }
1230            }
1231            Drag::Marquee { start, base, .. } => {
1232                let rect = Rect::from_corners(
1233                    self.viewport.screen_to_world(start),
1234                    self.viewport.screen_to_world(local),
1235                );
1236                let mut sel = base.clone();
1237                sel.extend(self.graph.nodes_in_rect(&rect, true));
1238                self.selection = sel;
1239                cx.notify();
1240                Drag::Marquee {
1241                    start,
1242                    current: local,
1243                    base,
1244                }
1245            }
1246            Drag::Connect(mut c) => {
1247                c.pointer = self.viewport.screen_to_world(local);
1248                let want = match self.graph.port(c.origin).map(|p| p.direction) {
1249                    Some(PortDirection::Output) => PortDirection::Input,
1250                    _ => PortDirection::Output,
1251                };
1252                c.target = self.hit_port(c.pointer, CONNECT_SNAP_RADIUS, Some(want));
1253                self.motion.target_changed(c.target, now);
1254                c.error = c.target.and_then(|t| {
1255                    let (from, to) = DefaultValidator::normalise(&self.graph, c.origin, t)?;
1256                    if let Some(e) = c.replacing.and_then(|e| self.graph.edge(e))
1257                        && e.from == from
1258                        && e.to == to
1259                    {
1260                        return None;
1261                    }
1262                    self.validator
1263                        .validate(&self.graph, from, to, c.replacing)
1264                        .err()
1265                });
1266                cx.notify();
1267                Drag::Connect(c)
1268            }
1269        };
1270        self.drag = Some(drag);
1271    }
1272
1273    fn on_drag_end(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1274        let Some(drag) = self.drag.take() else {
1275            return;
1276        };
1277        let now = self.motion_now(cx);
1278        self.motion.release(now);
1279        self.motion.target_changed(None, now);
1280        match drag {
1281            Drag::Pan {
1282                moved,
1283                clear_on_click,
1284                ..
1285            } => {
1286                if !moved && clear_on_click {
1287                    self.selection.clear();
1288                    self.edge_selection.clear();
1289                }
1290            }
1291            Drag::Minimap { .. } => {}
1292            Drag::Nodes { origins, moved, .. } => {
1293                self.guides.clear();
1294                if moved {
1295                    self.history
1296                        .record(GraphOp::MoveNodes { moves: origins }, "移动节点", None);
1297                }
1298            }
1299            Drag::Marquee { .. } => {}
1300            Drag::Connect(c) => self.finish_connect(c, window, cx),
1301        }
1302        cx.notify();
1303    }
1304
1305    fn finish_connect(&mut self, c: ConnectDrag, window: &mut Window, cx: &mut Context<Self>) {
1306        if let Some(err) = c.error {
1307            if let Some(t) = c.target {
1308                let now = self.motion_now(cx);
1309                self.motion.reject(t, now);
1310            }
1311            if let Some(h) = self.on_connect_error.clone() {
1312                h(&err, window, cx);
1313            }
1314            self.last_connect_error = Some(err);
1315            return;
1316        }
1317        let normalised = c
1318            .target
1319            .and_then(|t| DefaultValidator::normalise(&self.graph, c.origin, t));
1320        let op = match (
1321            normalised,
1322            c.replacing.and_then(|e| self.graph.edge(e).cloned()),
1323        ) {
1324            (Some((from, to)), Some(old)) if old.from == from && old.to == to => None,
1325            (Some((from, to)), Some(old)) => Some((
1326                GraphOp::SetEdge {
1327                    edge: Edge { from, to, ..old },
1328                },
1329                "重新连接",
1330            )),
1331            (Some((from, to)), None) => {
1332                let mut edge = Edge::new(self.graph.alloc_edge_id(), from, to);
1333                edge.shape = self.new_edge_shape;
1334                Some((GraphOp::AddEdge { edge }, "连线"))
1335            }
1336            (None, Some(old)) => Some((GraphOp::RemoveEdge { id: old.id }, "断开连线")),
1337            (None, None) => None,
1338        };
1339        if let Some((op, label)) = op {
1340            self.last_connect_error = None;
1341            let _ = self.history.commit(&mut self.graph, op, label);
1342        }
1343    }
1344
1345    fn on_scroll(&mut self, ev: &ScrollEvent, window: &mut Window, cx: &mut Context<Self>) {
1346        self.stop_view_animation();
1347        let delta = ev.delta.pixel_delta(px(LINE_HEIGHT));
1348        let (dx, dy) = (f32::from(delta.x), f32::from(delta.y));
1349        if ev.modifiers.secondary(cx) || ev.modifiers.control {
1350            let anchor = self.local(ev.position);
1351            // 行滚动(鼠标滚轮)一格约 20 px;像素滚动(触控板)细腻连续。
1352            let dy = if matches!(ev.delta, ScrollDelta::Lines(_)) {
1353                dy * 2.0
1354            } else {
1355                dy
1356            };
1357            self.viewport
1358                .zoom_by_at((dy * WHEEL_ZOOM_SPEED).exp(), anchor);
1359        } else {
1360            self.viewport.pan_by(Vec2::new(dx, dy));
1361        }
1362        cx.stop_propagation();
1363        self.viewport_changed(window, cx);
1364    }
1365
1366    fn on_pinch(&mut self, ev: &PinchEvent, window: &mut Window, cx: &mut Context<Self>) {
1367        self.stop_view_animation();
1368        let anchor = self.local(ev.position);
1369        self.viewport.zoom_by_at(1.0 + ev.delta, anchor);
1370        self.viewport_changed(window, cx);
1371    }
1372
1373    // ---------- 键盘 ----------
1374
1375    fn delete_selection(&mut self, label: &'static str, now: f64) {
1376        let nodes: Vec<NodeId> = self.selection_roots();
1377        let mut edges: Vec<EdgeId> = self.edge_selection.iter().copied().collect();
1378        edges.sort();
1379        if nodes.is_empty() && edges.is_empty() {
1380            return;
1381        }
1382        let roots: HashSet<NodeId> = nodes.iter().copied().collect();
1383        let doomed: Vec<(arc_flow_core::Node, Rect)> = self
1384            .graph
1385            .node_ids()
1386            .iter()
1387            .filter(|id| self.in_subtree(**id, &roots))
1388            .filter_map(|id| Some((self.graph.node(*id)?.clone(), self.graph.world_rect(*id)?)))
1389            .collect();
1390        let op = self.graph.delete_ops(&nodes, &edges);
1391        if self.history.commit(&mut self.graph, op, label).is_ok() {
1392            for (node, rect) in doomed {
1393                self.motion.node_removed(node, rect, now);
1394            }
1395        }
1396        self.prune_selection();
1397    }
1398
1399    fn copy_selection(&mut self) {
1400        let roots = self.selection_roots();
1401        if !roots.is_empty() {
1402            self.clipboard = Some(self.graph.copy_nodes(&roots));
1403            self.paste_count = 0;
1404        }
1405    }
1406
1407    fn paste(&mut self, clip: &Clip, steps: u32, label: &'static str) {
1408        if clip.is_empty() {
1409            return;
1410        }
1411        let offset = PASTE_OFFSET * steps as f32;
1412        let (op, roots) = self.graph.paste_op(clip, Vec2::new(offset, offset));
1413        if self.history.commit(&mut self.graph, op, label).is_ok() {
1414            self.selection = roots.into_iter().collect();
1415        }
1416    }
1417
1418    fn nudge(&mut self, d: Vec2) {
1419        let moves: Vec<(NodeId, Vec2)> = self
1420            .selection_roots()
1421            .into_iter()
1422            .filter_map(|id| self.graph.node(id).map(|n| (id, n.pos.plus(d))))
1423            .collect();
1424        let _ = self.history.commit_merged(
1425            &mut self.graph,
1426            GraphOp::MoveNodes { moves },
1427            "微移节点",
1428            NUDGE_KEY,
1429        );
1430    }
1431
1432    fn on_key(&mut self, ev: &KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) {
1433        // 焦点在节点内控件上时不处理,避免 Backspace 删节点。
1434        if !self.focus.is_focused(window) {
1435            return;
1436        }
1437        let k = &ev.keystroke;
1438        let m = k.modifiers;
1439        // 导航不改图,锁定模式下也可用。
1440        if !m.control && !m.platform && self.on_nav_key(k.key.as_str(), m.shift, m.alt, window, cx)
1441        {
1442            cx.stop_propagation();
1443            return;
1444        }
1445        let secondary = m.secondary(cx) || m.control;
1446        let step = if m.shift {
1447            NUDGE_STEP_LARGE
1448        } else {
1449            NUDGE_STEP
1450        };
1451        let editing = matches!(
1452            k.key.as_str(),
1453            "z" | "y"
1454                | "a"
1455                | "x"
1456                | "v"
1457                | "d"
1458                | "backspace"
1459                | "delete"
1460                | "left"
1461                | "right"
1462                | "up"
1463                | "down"
1464        );
1465        if !self.interactive && editing {
1466            return;
1467        }
1468        let mut handled = true;
1469        match k.key.as_str() {
1470            "=" | "+" if secondary => self.zoom_by(KEY_ZOOM_STEP, window, cx),
1471            "-" if secondary => self.zoom_by(1.0 / KEY_ZOOM_STEP, window, cx),
1472            "0" if secondary => {
1473                let mut vp = self.target_viewport();
1474                vp.zoom_to_at(1.0, self.view_center());
1475                self.animate_viewport(vp, window, cx);
1476            }
1477            "1" | "!" if m.shift => self.fit_view(window, cx),
1478            "z" if secondary && m.shift => self.redo(cx),
1479            "z" if secondary => self.undo(cx),
1480            "y" if secondary => self.redo(cx),
1481            "a" if secondary => {
1482                self.selection = self.graph.node_ids().iter().copied().collect();
1483                self.edge_selection = self.graph.edges().map(|e| e.id).collect();
1484            }
1485            "c" if secondary => self.copy_selection(),
1486            "x" if secondary => {
1487                self.copy_selection();
1488                let now = self.motion_now(cx);
1489                self.delete_selection("剪切", now);
1490            }
1491            "v" if secondary => {
1492                if let Some(clip) = self.clipboard.clone() {
1493                    self.paste_count += 1;
1494                    self.paste(&clip, self.paste_count, "粘贴");
1495                }
1496            }
1497            "d" if secondary => {
1498                let clip = self.graph.copy_nodes(&self.selection_roots());
1499                self.paste(&clip, 1, "复制副本");
1500            }
1501            "backspace" | "delete" => {
1502                let now = self.motion_now(cx);
1503                self.delete_selection("删除", now);
1504            }
1505            "escape" => {
1506                if self.drag.is_some() {
1507                    // 取消拖拽:节点回到原位,不记历史。
1508                    if let Some(Drag::Nodes {
1509                        origins,
1510                        moved: true,
1511                        ..
1512                    }) = self.drag.take()
1513                    {
1514                        let _ = self.graph.apply(GraphOp::MoveNodes { moves: origins });
1515                    }
1516                    self.motion.cancel_live();
1517                    self.guides.clear();
1518                } else {
1519                    self.selection.clear();
1520                    self.edge_selection.clear();
1521                }
1522            }
1523            "left" => self.nudge(Vec2::new(-step, 0.0)),
1524            "right" => self.nudge(Vec2::new(step, 0.0)),
1525            "up" => self.nudge(Vec2::new(0.0, -step)),
1526            "down" => self.nudge(Vec2::new(0.0, step)),
1527            _ => handled = false,
1528        }
1529        if handled {
1530            cx.stop_propagation();
1531            cx.notify();
1532        }
1533    }
1534}
1535
1536impl Render for FlowCanvas {
1537    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1538        if self.fit_pending
1539            && let (Some(view), Some(world)) = (self.view_size(), self.graph.bounds())
1540        {
1541            self.viewport.fit(&world, view, FIT_PADDING);
1542            self.fit_pending = false;
1543        }
1544        let now = self.motion_now(cx);
1545        if let Some((vp, done)) = self
1546            .motion
1547            .view_sample(&self.viewport, self.view_center(), now)
1548        {
1549            self.viewport = vp;
1550            if done {
1551                self.motion.finish_view();
1552                self.view_target = None;
1553                if let Some(h) = self.on_viewport_change.clone() {
1554                    h(&self.viewport, window, cx);
1555                }
1556            }
1557        }
1558        self.refresh_cache();
1559        self.sync_presence(now);
1560        let animating = self.motion.tick(now);
1561
1562        let theme = cx.arc_theme().clone();
1563        let colors = theme.colors;
1564        let vp = self.viewport;
1565        // 首帧尚无尺寸:先按一块足够大的区域裁剪,布局后立即重绘。
1566        let view = self.view_size().unwrap_or(Size2::new(4096.0, 4096.0));
1567        let visible = vp.visible_world_rect(view).inflate(CULL_MARGIN);
1568
1569        let hidden_edge = self.connect_drag().and_then(|c| c.replacing);
1570        let vkey = (
1571            self.graph.revision(),
1572            [
1573                vp.offset.x.to_bits(),
1574                vp.offset.y.to_bits(),
1575                vp.zoom.to_bits(),
1576                view.w.to_bits(),
1577                view.h.to_bits(),
1578            ],
1579            hidden_edge,
1580        );
1581        if self.visible_cache.as_ref().is_none_or(|c| c.key != vkey) {
1582            let mut nodes = self.cache.nodes.query(&visible);
1583            nodes.sort_by_key(|id| self.cache.order.get(id).copied().unwrap_or(usize::MAX));
1584            let mut edges: Vec<(EdgeId, Rc<EdgeGeometry>)> = self
1585                .cache
1586                .edge_index
1587                .query(&visible.inflate(ARROW_LENGTH))
1588                .into_iter()
1589                .filter(|id| Some(*id) != hidden_edge)
1590                .filter_map(|id| {
1591                    let g = self.cache.edge_lookup.get(&id)?;
1592                    g.bounds
1593                        .inflate(ARROW_LENGTH)
1594                        .intersects(&visible)
1595                        .then(|| (id, g.clone()))
1596                })
1597                .collect();
1598            edges.sort_by_key(|(id, _)| *id);
1599            self.visible_cache = Some(VisibleCache {
1600                key: vkey,
1601                nodes,
1602                edges,
1603            });
1604        }
1605        let (nodes, edges) = {
1606            let c = self.visible_cache.as_ref().expect("filled above");
1607            (c.nodes.clone(), c.edges.clone())
1608        };
1609        // 细节层级:大图缩得很小时整体只画外壳;单个节点在屏幕上过小时也降级。
1610        let global_shell = self.graph.node_count() >= LOD_MIN_NODES && vp.zoom <= LOD_ZOOM;
1611        // 拖拽降级:拖动节点时暂停边标签与节点阴影。
1612        let dragging_nodes = matches!(self.drag, Some(Drag::Nodes { moved: true, .. }));
1613        self.rendered_nodes = nodes.len();
1614        self.rendered_edges = edges.len();
1615
1616        // ---- 第 1 层:点阵 + 边 ----
1617        let offsets_on = self.motion.has_offsets();
1618        let node_of = |port: PortId| self.graph.port(port).map(|p| p.node);
1619        let edge_paint: Vec<(Rc<EdgeGeometry>, EdgeState, Marker, bool, f32)> = edges
1620            .iter()
1621            .filter_map(|(id, g)| {
1622                let e = self.graph.edge(*id)?;
1623                let mut geo = g.clone();
1624                if offsets_on {
1625                    // 落位动画中的节点:边端点跟随显示位置,不和节点脱开。
1626                    let o1 = node_of(e.from).map_or(Vec2::ZERO, |n| self.visual_offset(n, now));
1627                    let o2 = node_of(e.to).map_or(Vec2::ZERO, |n| self.visual_offset(n, now));
1628                    if (o1 != Vec2::ZERO || o2 != Vec2::ZERO)
1629                        && let (Some((a, sa)), Some((b, sb))) = (
1630                            port_anchor(&self.graph, e.from),
1631                            port_anchor(&self.graph, e.to),
1632                        )
1633                    {
1634                        geo = Rc::new(path_between(a.plus(o1), sa, b.plus(o2), sb, e.shape));
1635                    }
1636                }
1637                Some((
1638                    geo,
1639                    e.state,
1640                    if global_shell {
1641                        Marker::None
1642                    } else {
1643                        e.marker_end
1644                    },
1645                    self.edge_selection.contains(id),
1646                    self.motion.draw_progress(*id, now),
1647                ))
1648            })
1649            .collect();
1650        // 选中边两端的把手(源端可拖动重新连接)。
1651        let edge_handles: Vec<Vec2> = edge_paint
1652            .iter()
1653            .filter(|e| e.3)
1654            .flat_map(|(g, ..)| [g.points[0], *g.points.last().expect("non-empty")])
1655            .collect();
1656        let dash_phase = self.motion.dash_phase(now);
1657        let has_active = edge_paint.iter().any(|e| e.1 == EdgeState::Active);
1658        let edge_colors = EdgeColors {
1659            idle: colors.border_strong,
1660            selected: colors.accent,
1661            active: colors.accent,
1662            error: colors.danger,
1663        };
1664        let grid_color = colors.border;
1665        let bounds_cell = self.bounds.clone();
1666        let had_bounds = bounds_cell.get().is_some();
1667        let dragging = self.drag.is_some();
1668        let entity = cx.entity();
1669        let back_layer = canvas(
1670            move |b, window, _| {
1671                let changed = bounds_cell.get() != Some(b);
1672                bounds_cell.set(Some(b));
1673                if changed && !had_bounds {
1674                    window.refresh();
1675                }
1676            },
1677            move |b, _, window, _| {
1678                if dragging {
1679                    // 拖拽期间在窗口层捕获指针:移出画布也能继续,并在任意处松手结束。
1680                    let e_move = entity.clone();
1681                    window.on_mouse_event(move |ev: &MouseMoveEvent, phase, window, cx| {
1682                        if phase.bubble() {
1683                            e_move
1684                                .update(cx, |this, cx| this.on_drag_move(ev.position, window, cx));
1685                        }
1686                    });
1687                    let e_up = entity.clone();
1688                    window.on_mouse_event(move |_: &MouseUpEvent, phase, window, cx| {
1689                        if phase.bubble() {
1690                            e_up.update(cx, |this, cx| this.on_drag_end(window, cx));
1691                        }
1692                    });
1693                }
1694                paint_grid(b, &vp, grid_color, window);
1695                // 同色同宽的普通边合并成一条路径;选中、运行中、出错、正在绘入的单独画。
1696                let batch: Vec<(&EdgeGeometry, Marker)> = edge_paint
1697                    .iter()
1698                    .filter(|e| e.1 == EdgeState::Idle && !e.3 && e.4 >= 1.0)
1699                    .map(|e| (&*e.0, e.2))
1700                    .collect();
1701                paint_edge_batch(b, &vp, &batch, edge_colors.idle, global_shell, window);
1702                for (g, state, marker, selected, progress) in edge_paint
1703                    .iter()
1704                    .filter(|e| !(e.1 == EdgeState::Idle && !e.3 && e.4 >= 1.0))
1705                {
1706                    let ep = EdgePaint {
1707                        geometry: g,
1708                        state: *state,
1709                        marker: *marker,
1710                        selected: *selected,
1711                        progress: *progress,
1712                        dash_phase,
1713                    };
1714                    paint_edge(b, &vp, &ep, &edge_colors, window);
1715                }
1716            },
1717        )
1718        .absolute()
1719        .size_full();
1720
1721        // ---- 第 2 层:边标签 ----
1722        let labels: Vec<_> = edges
1723            .iter()
1724            .filter(|_| !(global_shell || dragging_nodes))
1725            .filter_map(|(id, g)| {
1726                let label = self.graph.edge(*id)?.label.clone()?;
1727                let p = vp.world_to_screen(g.label);
1728                Some(
1729                    div()
1730                        .absolute()
1731                        .left(px(p.x))
1732                        .top(px(p.y))
1733                        .w(px(0.0))
1734                        .h(px(0.0))
1735                        .flex()
1736                        .items_center()
1737                        .justify_center()
1738                        .child(
1739                            div()
1740                                .flex_none()
1741                                .px(px(f32::from(Spacing::S2) * vp.zoom))
1742                                .py(px(2.0 * vp.zoom))
1743                                .rounded(Radii::PILL)
1744                                .bg(colors.surface_raised)
1745                                .border_1()
1746                                .border_color(colors.border)
1747                                .text_size(px(f32::from(Typography::TEXT_XS) * vp.zoom))
1748                                .text_color(colors.text_secondary)
1749                                .whitespace_nowrap()
1750                                .child(label.to_string()),
1751                        ),
1752                )
1753            })
1754            .collect();
1755
1756        // ---- 第 3 层:节点 ----
1757        let mut node_elements = Vec::with_capacity(nodes.len());
1758        let mut port_paint: Vec<Vec2> = Vec::new();
1759        let pulse = self.motion.pulse(now);
1760        let mut has_running = false;
1761        let active = self.active_node();
1762        let locale = cx.arc_locale();
1763        self.ensure_reading_order();
1764        let total = self.graph.node_count();
1765        // LOD 外壳与点:(屏幕矩形, 层级, 是否高亮),在一个 canvas 里批量画。
1766        let mut shells: Vec<(Rect, Lod, bool)> = Vec::new();
1767        // 删除后的残影画在最底下,避免挡住仍在的节点。
1768        for (ghost, appear) in self.motion.ghosts(now) {
1769            let s = scale_about_center(vp.world_rect_to_screen(&ghost.rect), appear.scale);
1770            let ctx = NodeRenderCtx {
1771                zoom: vp.zoom * appear.scale,
1772                selected: false,
1773                colors: &colors,
1774                mode: theme.mode,
1775                pulse,
1776                interacting: false,
1777            };
1778            let renderer = self
1779                .renderers
1780                .get(&ghost.node.kind)
1781                .unwrap_or(&self.default_renderer)
1782                .clone();
1783            let content = renderer.render(&ghost.node, &ctx, window, cx);
1784            node_elements.push(
1785                div()
1786                    .id(ElementId::NamedInteger(
1787                        format!("{}-ghost", self.id).into(),
1788                        ghost.node.id.0,
1789                    ))
1790                    .absolute()
1791                    .left(px(s.min.x))
1792                    .top(px(s.min.y))
1793                    .w(px(s.width()))
1794                    .h(px(s.height()))
1795                    .opacity(appear.opacity)
1796                    .child(content)
1797                    .into_any_element(),
1798            );
1799        }
1800        for id in &nodes {
1801            let (Some(node), Some(rect)) = (self.graph.node(*id), self.graph.world_rect(*id))
1802            else {
1803                continue;
1804            };
1805            has_running |= node.status == arc_flow_core::NodeStatus::Running;
1806            let offset = self.visual_offset(*id, now);
1807            let appear: Appear = self.motion.enter_sample(*id, now);
1808            let moved = Rect {
1809                min: rect.min.plus(offset),
1810                max: rect.max.plus(offset),
1811            };
1812            let s = scale_about_center(vp.world_rect_to_screen(&moved), appear.scale);
1813            let lod = if active == Some(*id) {
1814                // 键盘当前节点始终完整渲染,读屏才能把它报告为焦点。
1815                Lod::Full
1816            } else if s.height() < LOD_DOT_PX {
1817                Lod::Dot
1818            } else if global_shell || s.height() < LOD_SHELL_PX {
1819                Lod::Shell
1820            } else {
1821                Lod::Full
1822            };
1823            if lod != Lod::Full {
1824                let selected = self.selection.contains(id);
1825                let running = node.status == arc_flow_core::NodeStatus::Running;
1826                shells.push((s, lod, selected || running));
1827                continue;
1828            }
1829            let ctx = NodeRenderCtx {
1830                zoom: vp.zoom * appear.scale,
1831                selected: self.selection.contains(id),
1832                colors: &colors,
1833                mode: theme.mode,
1834                pulse,
1835                interacting: dragging_nodes,
1836            };
1837            let renderer = self
1838                .renderers
1839                .get(&node.kind)
1840                .unwrap_or(&self.default_renderer)
1841                .clone();
1842            let content = renderer.render(node, &ctx, window, cx);
1843            node_elements.push(
1844                div()
1845                    .id(ElementId::NamedInteger(self.id.clone(), id.0))
1846                    .test_support()
1847                    .role(Role::Group)
1848                    .aria_label(SharedString::from(node.label.to_string()))
1849                    .aria_description(SharedString::from(a11y::describe_node(
1850                        &self.graph,
1851                        *id,
1852                        locale,
1853                    )))
1854                    .aria_selected(self.selection.contains(id))
1855                    .aria_position_in_set(self.reading_order.1.get(id).copied().unwrap_or(0) + 1)
1856                    .aria_size_of_set(total)
1857                    .when(active == Some(*id), |d| d.aria_active_descendant())
1858                    .absolute()
1859                    .left(px(s.min.x))
1860                    .top(px(s.min.y))
1861                    .w(px(s.width()))
1862                    .h(px(s.height()))
1863                    .when(appear.opacity < 1.0, |d| d.opacity(appear.opacity))
1864                    .child(content)
1865                    .into_any_element(),
1866            );
1867            port_paint.extend(
1868                self.graph
1869                    .ports_of(*id)
1870                    .filter_map(|p| port_anchor(&self.graph, p.id))
1871                    .map(|(a, _)| a.plus(offset)),
1872            );
1873        }
1874
1875        let full_count = node_elements.len() - self.motion.ghosts(now).count();
1876        let shell_count = shells.iter().filter(|s| s.1 == Lod::Shell).count();
1877        self.rendered_lod = (full_count, shell_count, shells.len() - shell_count);
1878        let shell_fill = colors.surface_raised;
1879        let shell_border = colors.border_strong;
1880        let shell_accent = colors.accent;
1881        let shell_radius = f32::from(Radii::CONTROL) * vp.zoom;
1882        let shell_layer = (!shells.is_empty()).then(|| {
1883            canvas(
1884                |_, _, _| {},
1885                move |b, _, window, _| {
1886                    for (r, lod, hot) in &shells {
1887                        let border = if *hot { shell_accent } else { shell_border };
1888                        match lod {
1889                            Lod::Dot => {
1890                                let c = r.center();
1891                                let w = r.width().max(LOD_DOT_MIN);
1892                                let h = r.height().max(LOD_DOT_MIN);
1893                                window.paint_quad(gpui_kit::fill(
1894                                    Bounds {
1895                                        origin: gpui_kit::point(
1896                                            b.origin.x + px(c.x - w / 2.0),
1897                                            b.origin.y + px(c.y - h / 2.0),
1898                                        ),
1899                                        size: size(px(w), px(h)),
1900                                    },
1901                                    border,
1902                                ));
1903                            }
1904                            _ => {
1905                                let radius = shell_radius.min(r.height() / 2.0);
1906                                window.paint_quad(quad(
1907                                    Bounds {
1908                                        origin: gpui_kit::point(
1909                                            b.origin.x + px(r.min.x),
1910                                            b.origin.y + px(r.min.y),
1911                                        ),
1912                                        size: size(px(r.width()), px(r.height())),
1913                                    },
1914                                    Corners::all(px(radius)),
1915                                    shell_fill,
1916                                    Edges::all(px(1.0)),
1917                                    border,
1918                                    BorderStyle::Solid,
1919                                ));
1920                            }
1921                        }
1922                    }
1923                },
1924            )
1925            .absolute()
1926            .size_full()
1927        });
1928
1929        // ---- 第 4 层:端口、连线草稿、框选(canvas 无命中区,不拦截指针) ----
1930        let port_fill = colors.surface_raised;
1931        let port_stroke = colors.border_strong;
1932        let draft = self.connect_drag().and_then(|c| {
1933            let (a, side) = port_anchor(&self.graph, c.origin)?;
1934            let (end, end_side) = match c.target.and_then(|t| port_anchor(&self.graph, t)) {
1935                Some(t) => t,
1936                None => (c.pointer, infer_target_side(a, side, c.pointer)),
1937            };
1938            let geo = path_between(a, side, end, end_side, self.new_edge_shape);
1939            let target = c.target.and_then(|t| {
1940                let (a, _) = port_anchor(&self.graph, t)?;
1941                let (scale, glow) = self.motion.target_sample(t, now);
1942                Some((a, scale, glow))
1943            });
1944            Some((geo, target, c.error.is_some()))
1945        });
1946        let shake = self.motion.shake(now).and_then(|(port, dx)| {
1947            let (a, _) = port_anchor(&self.graph, port)?;
1948            let node = self.graph.port(port)?.node;
1949            Some((a.plus(self.visual_offset(node, now)), dx))
1950        });
1951        let marquee = match &self.drag {
1952            Some(Drag::Marquee { start, current, .. }) => {
1953                Some(Rect::from_corners(*start, *current))
1954            }
1955            _ => None,
1956        };
1957        let accent = colors.accent;
1958        let danger = colors.danger;
1959        let guides: Vec<(Vec2, Vec2)> = self
1960            .guides
1961            .iter()
1962            .map(|g| (vp.world_to_screen(g.from), vp.world_to_screen(g.to)))
1963            .collect();
1964        let front_layer = canvas(
1965            |_, _, _| {},
1966            move |b, _, window, _| {
1967                for a in &port_paint {
1968                    paint_port(b, &vp, *a, port_fill, port_stroke, window);
1969                }
1970                for h in &edge_handles {
1971                    paint_port(b, &vp, *h, port_fill, accent, window);
1972                }
1973                if let Some((geo, target, invalid)) = &draft {
1974                    let color = if *invalid { danger } else { accent };
1975                    let ep = EdgePaint {
1976                        geometry: geo,
1977                        state: EdgeState::Idle,
1978                        marker: Marker::None,
1979                        selected: true,
1980                        progress: 1.0,
1981                        dash_phase: 0.0,
1982                    };
1983                    let colors = EdgeColors {
1984                        idle: color,
1985                        selected: color,
1986                        active: color,
1987                        error: color,
1988                    };
1989                    paint_edge(b, &vp, &ep, &colors, window);
1990                    if let Some((t, scale, glow)) = target {
1991                        if let Some(g) = glow {
1992                            // 吸附光晕:从端口向外扩散并淡出。
1993                            let c = vp.world_to_screen(*t);
1994                            let r = PORT_RADIUS * vp.zoom * (1.0 + (TARGET_GLOW_SCALE - 1.0) * g);
1995                            window.paint_quad(quad(
1996                                Bounds {
1997                                    origin: gpui_kit::point(
1998                                        b.origin.x + px(c.x - r),
1999                                        b.origin.y + px(c.y - r),
2000                                    ),
2001                                    size: size(px(r * 2.0), px(r * 2.0)),
2002                                },
2003                                Corners::all(px(r)),
2004                                color.opacity(TARGET_GLOW_ALPHA * (1.0 - g)),
2005                                Edges::default(),
2006                                color,
2007                                BorderStyle::Solid,
2008                            ));
2009                        }
2010                        let mut big = vp;
2011                        big.zoom *= *scale;
2012                        // 放大后的端口仍以原锚点为中心。
2013                        big.offset = vp.world_to_screen(*t).minus(t.scale(big.zoom));
2014                        paint_port(b, &big, *t, port_fill, color, window);
2015                    }
2016                }
2017                if let Some((a, dx)) = shake {
2018                    let mut shifted = vp;
2019                    shifted.offset.x += dx;
2020                    paint_port(b, &shifted, a, port_fill, danger, window);
2021                }
2022                for (a, c) in &guides {
2023                    let r = Rect::from_corners(*a, *c).inflate(GUIDE_WIDTH * 0.5);
2024                    window.paint_quad(gpui_kit::fill(
2025                        Bounds {
2026                            origin: gpui_kit::point(
2027                                b.origin.x + px(r.min.x),
2028                                b.origin.y + px(r.min.y),
2029                            ),
2030                            size: size(px(r.width()), px(r.height())),
2031                        },
2032                        accent,
2033                    ));
2034                }
2035                if let Some(r) = marquee {
2036                    let origin =
2037                        gpui_kit::point(b.origin.x + px(r.min.x), b.origin.y + px(r.min.y));
2038                    window.paint_quad(quad(
2039                        Bounds {
2040                            origin,
2041                            size: size(px(r.width()), px(r.height())),
2042                        },
2043                        Corners::default(),
2044                        accent.opacity(MARQUEE_FILL_ALPHA),
2045                        Edges::all(px(1.0)),
2046                        accent,
2047                        BorderStyle::Solid,
2048                    ));
2049                }
2050            },
2051        )
2052        .absolute()
2053        .size_full();
2054
2055        // 一次性动画在跑,或有运行中的边 / 节点(虚线流动、边框呼吸)时持续请求下一帧。
2056        if animating || (!self.motion.reduced() && (has_active || has_running)) {
2057            window.request_animation_frame();
2058        }
2059
2060        // ---- 视口外节点的可访问列表(F9):裁剪掉的节点以合成节点暴露,读屏可遍历整张图 ----
2061        let offscreen: Vec<(NodeId, String, String, usize)> = if window.is_a11y_active() {
2062            let shown: HashSet<NodeId> = nodes.iter().copied().collect();
2063            let mut list: Vec<(NodeId, String, String, usize)> = self
2064                .graph
2065                .node_ids()
2066                .iter()
2067                .filter(|id| !shown.contains(id))
2068                .filter_map(|id| {
2069                    let n = self.graph.node(*id)?;
2070                    Some((
2071                        *id,
2072                        n.label.to_string(),
2073                        a11y::describe_node(&self.graph, *id, locale),
2074                        self.reading_order.1.get(id).copied().unwrap_or(0),
2075                    ))
2076                })
2077                .collect();
2078            list.sort_by_key(|x| x.3);
2079            list
2080        } else {
2081            Vec::new()
2082        };
2083        self.rendered_offscreen = offscreen.len();
2084        let outline = (!offscreen.is_empty()).then(|| {
2085            div()
2086                .id(SharedString::from(format!("{}-offscreen", self.id)))
2087                .role(Role::List)
2088                .aria_label(SharedString::from(match locale {
2089                    arc_tokens::Locale::ZhCn => "视口外的节点",
2090                    arc_tokens::Locale::EnUs => "Nodes outside the viewport",
2091                }))
2092                .absolute()
2093                .size_0()
2094                .a11y_synthetic_children(move |b| {
2095                    for (id, label, desc, pos) in offscreen {
2096                        let mut node = gpui_kit::accesskit::Node::new(Role::ListItem);
2097                        node.set_label(label);
2098                        node.set_description(desc);
2099                        node.set_position_in_set(pos + 1);
2100                        node.set_size_of_set(total);
2101                        let nid = b.synthetic_node_id(id.0);
2102                        b.push_child(nid, node);
2103                    }
2104                })
2105        });
2106
2107        // ---- 外围:小地图(右下)与控件栏(左下) ----
2108        let minimap = self
2109            .show_minimap
2110            .then(|| self.minimap_transform())
2111            .flatten()
2112            .map(|(t, origin)| {
2113                let rects: Vec<(Rect, bool)> = self
2114                    .graph
2115                    .node_ids()
2116                    .iter()
2117                    .filter_map(|id| {
2118                        let r = self.graph.world_rect(*id)?;
2119                        Some((t.rect_to_frame(&r), self.selection.contains(id)))
2120                    })
2121                    .collect();
2122                let view_rect = t.rect_to_frame(&vp.visible_world_rect(view));
2123                minimap_element(
2124                    ElementId::Name(format!("{}-minimap", self.id).into()),
2125                    origin,
2126                    rects,
2127                    view_rect,
2128                    &colors,
2129                    cx.listener(Self::on_minimap_down),
2130                )
2131            });
2132        let controls = self.show_controls.then(|| {
2133            let this = cx.entity().downgrade();
2134            let id = self.id.clone();
2135            let button = |key: &str, icon: IconName, label: &'static str| {
2136                Button::new(ElementId::Name(format!("{id}-{key}").into()))
2137                    .variant(ButtonVariant::Ghost)
2138                    .size(ButtonSize::Sm)
2139                    .icon(icon)
2140                    .accessibility_label(label)
2141            };
2142            let act = |f: fn(&mut FlowCanvas, &mut Window, &mut Context<FlowCanvas>)| {
2143                let this = this.clone();
2144                move |_: &gpui_kit::ClickEvent, window: &mut Window, cx: &mut App| {
2145                    let _ = this.update(cx, |c, cx| f(c, window, cx));
2146                }
2147            };
2148            div()
2149                .id(ElementId::Name(format!("{}-controls", self.id).into()))
2150                .absolute()
2151                .left(px(OVERLAY_MARGIN))
2152                .bottom(px(OVERLAY_MARGIN))
2153                .flex()
2154                .flex_col()
2155                .gap(Spacing::S1)
2156                .p(Spacing::S1)
2157                .rounded(Radii::CONTROL)
2158                .bg(colors.surface_raised)
2159                .border_1()
2160                .border_color(colors.border)
2161                .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
2162                .child(
2163                    button("zoom-in", IconName::ZoomIn, "放大")
2164                        .on_click(act(|c, w, cx| c.zoom_by(KEY_ZOOM_STEP, w, cx))),
2165                )
2166                .child(
2167                    button("zoom-out", IconName::ZoomOut, "缩小")
2168                        .on_click(act(|c, w, cx| c.zoom_by(1.0 / KEY_ZOOM_STEP, w, cx))),
2169                )
2170                .child(
2171                    button("fit", IconName::Maximize, "适配视图")
2172                        .on_click(act(|c, w, cx| c.fit_view(w, cx))),
2173                )
2174                .child(
2175                    button(
2176                        "lock",
2177                        if self.interactive {
2178                            IconName::LockOpen
2179                        } else {
2180                            IconName::Lock
2181                        },
2182                        if self.interactive {
2183                            "锁定编辑"
2184                        } else {
2185                            "解锁编辑"
2186                        },
2187                    )
2188                    .selected(!self.interactive)
2189                    .on_click(act(|c, _, cx| c.set_interactive(!c.interactive, cx))),
2190                )
2191        });
2192
2193        div()
2194            .id(self.id.clone())
2195            .test_support()
2196            .role(Role::Application)
2197            .aria_label(self.label.clone())
2198            .aria_description(SharedString::from(a11y::describe_canvas(
2199                &self.graph,
2200                locale,
2201            )))
2202            .aria_keyshortcuts(a11y::KEY_SHORTCUTS)
2203            .track_focus(&self.focus)
2204            .relative()
2205            .size_full()
2206            .overflow_hidden()
2207            .bg(colors.background)
2208            .when(matches!(self.drag, Some(Drag::Pan { .. })), |d| {
2209                d.cursor_grabbing()
2210            })
2211            .on_mouse_down(MouseButton::Left, cx.listener(Self::on_left_down))
2212            .on_mouse_down(MouseButton::Middle, cx.listener(Self::on_middle_down))
2213            .on_mouse_down(MouseButton::Right, cx.listener(Self::on_right_down))
2214            .on_scroll(cx.listener(Self::on_scroll))
2215            .on_pinch(cx.listener(Self::on_pinch))
2216            .on_key_down(cx.listener(Self::on_key))
2217            .child(back_layer)
2218            .children(labels)
2219            .children(shell_layer)
2220            .children(node_elements)
2221            .child(front_layer)
2222            .children(outline)
2223            .children(minimap)
2224            .children(controls)
2225    }
2226}
2227
2228/// 以中心为原点缩放矩形(进出场的 0.96→1)。
2229fn scale_about_center(r: Rect, scale: f32) -> Rect {
2230    if scale == 1.0 {
2231        return r;
2232    }
2233    let c = r.center();
2234    let half = Vec2::new(r.width() * 0.5 * scale, r.height() * 0.5 * scale);
2235    Rect {
2236        min: c.minus(half),
2237        max: c.plus(half),
2238    }
2239}
2240
2241/// 小地图面板:节点块、当前视口框。坐标均为面板内的屏幕 px。
2242fn minimap_element(
2243    id: ElementId,
2244    origin: Vec2,
2245    rects: Vec<(Rect, bool)>,
2246    view_rect: Rect,
2247    colors: &arc_tokens::ArcColors,
2248    on_down: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
2249) -> gpui_kit::AnyElement {
2250    let (node_fill, accent) = (colors.border_strong, colors.accent);
2251    let to_bounds = |b: Bounds<Pixels>, r: &Rect| Bounds {
2252        origin: gpui_kit::point(b.origin.x + px(r.min.x), b.origin.y + px(r.min.y)),
2253        size: size(px(r.width().max(1.0)), px(r.height().max(1.0))),
2254    };
2255    div()
2256        .id(id)
2257        .test_support()
2258        .role(Role::Group)
2259        .aria_label(SharedString::from("Minimap"))
2260        .absolute()
2261        .left(px(origin.x))
2262        .top(px(origin.y))
2263        .w(px(MINIMAP_WIDTH))
2264        .h(px(MINIMAP_HEIGHT))
2265        .rounded(Radii::CONTROL)
2266        .overflow_hidden()
2267        .bg(colors.surface_raised)
2268        .border_1()
2269        .border_color(colors.border)
2270        .on_mouse_down(MouseButton::Left, on_down)
2271        .child(
2272            canvas(
2273                |_, _, _| {},
2274                move |b, _, window, _| {
2275                    for (r, selected) in &rects {
2276                        let fill = if *selected { accent } else { node_fill };
2277                        window.paint_quad(gpui_kit::fill(to_bounds(b, r), fill));
2278                    }
2279                    window.paint_quad(quad(
2280                        to_bounds(b, &view_rect),
2281                        Corners::default(),
2282                        accent.opacity(MINIMAP_VIEW_FILL_ALPHA),
2283                        Edges::all(px(1.0)),
2284                        accent,
2285                        BorderStyle::Solid,
2286                    ));
2287                },
2288            )
2289            .absolute()
2290            .size_full(),
2291        )
2292        .into_any_element()
2293}
2294
2295#[cfg(test)]
2296mod tests {
2297    use super::*;
2298    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
2299    use gpui_kit::{
2300        AnyElement, Entity, Modifiers, PlatformInput, TestAppContext, TouchPhase,
2301        VisualTestContext, point, test::TestWindowExt as _,
2302    };
2303
2304    const SZ: Size2 = Size2 { w: 160.0, h: 64.0 };
2305
2306    struct Host {
2307        canvas: Entity<FlowCanvas>,
2308    }
2309
2310    impl Render for Host {
2311        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2312            div().w(px(800.0)).h(px(600.0)).child(self.canvas.clone())
2313        }
2314    }
2315
2316    /// 节点内带可聚焦控件的渲染器(模拟输入框)。
2317    struct FieldRenderer {
2318        focus: FocusHandle,
2319    }
2320
2321    impl NodeRenderer for FieldRenderer {
2322        fn render(
2323            &self,
2324            _: &arc_flow_core::Node,
2325            _: &NodeRenderCtx,
2326            _: &mut Window,
2327            _: &mut App,
2328        ) -> AnyElement {
2329            let focus = self.focus.clone();
2330            div()
2331                .size_full()
2332                .child(
2333                    div()
2334                        .id("in-node-field")
2335                        .track_focus(&self.focus)
2336                        .size(px(40.0))
2337                        // 等价于 xyflow 的 nodrag:控件自己处理指针,不触发节点拖拽。
2338                        .on_mouse_down(MouseButton::Left, move |_, window, cx| {
2339                            window.focus(&focus, cx);
2340                            cx.stop_propagation();
2341                        }),
2342                )
2343                .into_any_element()
2344        }
2345    }
2346
2347    /// start(0,0)→llm(260,0)→end(520,120);src(0,200) 与 sink(260,200) 未连;field(520,300);far 远处。
2348    fn sample_graph() -> Graph {
2349        let mut g = Graph::new();
2350        let (_, _, a) = g.add_node_with("start", Vec2::new(0.0, 0.0), SZ, 0, 1);
2351        let (_, b_in, b_out) = g.add_node_with("llm", Vec2::new(260.0, 0.0), SZ, 1, 1);
2352        let (_, c_in, _) = g.add_node_with("end", Vec2::new(520.0, 120.0), SZ, 1, 0);
2353        let e = g.connect(a[0], b_in[0]).unwrap();
2354        g.connect(b_out[0], c_in[0]).unwrap();
2355        let mut edge = g.edge(e).unwrap().clone();
2356        edge.shape = EdgeShape::SmoothStep {
2357            radius: 8.0,
2358            offset: 20.0,
2359        };
2360        edge.label = Some("ok".into());
2361        g.apply(GraphOp::SetEdge { edge }).unwrap();
2362        g.add_node_with("src", Vec2::new(0.0, 200.0), SZ, 0, 1);
2363        g.add_node_with("sink", Vec2::new(260.0, 200.0), SZ, 1, 0);
2364        g.add_node_with("field", Vec2::new(520.0, 300.0), SZ, 0, 0);
2365        g.add_node_with("far", Vec2::new(20_000.0, 20_000.0), SZ, 0, 0);
2366        g
2367    }
2368
2369    fn id_of(c: &FlowCanvas, kind: &str) -> NodeId {
2370        c.graph()
2371            .nodes()
2372            .find(|n| &*n.kind == kind)
2373            .map(|n| n.id)
2374            .unwrap()
2375    }
2376
2377    /// 交互测试默认开启 reduced motion,位移与视口变化即时生效;F6 测试用 `setup_with(.., false)`。
2378    fn setup(cx: &mut TestAppContext) -> (Entity<FlowCanvas>, FocusHandle, &mut VisualTestContext) {
2379        setup_with(cx, true)
2380    }
2381
2382    fn setup_with(
2383        cx: &mut TestAppContext,
2384        reduced: bool,
2385    ) -> (Entity<FlowCanvas>, FocusHandle, &mut VisualTestContext) {
2386        cx.update(|cx| {
2387            gpui_kit::init(cx);
2388            install_arc_theme(ThemeMode::Light, Accent::Blue, cx);
2389            arc_motion::set_reduced_motion(
2390                if reduced {
2391                    arc_motion::ReducedMotionChoice::Reduce
2392                } else {
2393                    arc_motion::ReducedMotionChoice::Allow
2394                },
2395                cx,
2396            );
2397        });
2398        let mut canvas = None;
2399        let mut field = None;
2400        let (_, vcx) = cx.add_window_view(|_, cx| {
2401            let f = cx.focus_handle();
2402            field = Some(f.clone());
2403            let c = cx.new(|cx| {
2404                FlowCanvas::new("flow", sample_graph(), cx)
2405                    .renderer("field", FieldRenderer { focus: f })
2406            });
2407            canvas = Some(c.clone());
2408            Host { canvas: c }
2409        });
2410        vcx.update(|window, cx| {
2411            window.render_frame(cx);
2412            window.render_frame(cx);
2413        });
2414        (canvas.unwrap(), field.unwrap(), vcx)
2415    }
2416
2417    fn p(x: f32, y: f32) -> gpui_kit::Point<Pixels> {
2418        point(px(x), px(y))
2419    }
2420
2421    /// 带修饰键的拖拽(测试工具的 `drag` 不带修饰键)。
2422    fn drag_with(
2423        window: &mut Window,
2424        from: gpui_kit::Point<Pixels>,
2425        to: gpui_kit::Point<Pixels>,
2426        modifiers: Modifiers,
2427        cx: &mut App,
2428    ) {
2429        window.dispatch_event(
2430            PlatformInput::MouseDown(MouseDownEvent {
2431                button: MouseButton::Left,
2432                position: from,
2433                modifiers,
2434                click_count: 1,
2435                first_mouse: false,
2436            }),
2437            cx,
2438        );
2439        window.render_frame(cx);
2440        for step in 1..=4 {
2441            let t = step as f32 / 4.0;
2442            window.dispatch_event(
2443                PlatformInput::MouseMove(MouseMoveEvent {
2444                    position: point(from.x + (to.x - from.x) * t, from.y + (to.y - from.y) * t),
2445                    pressed_button: Some(MouseButton::Left),
2446                    modifiers,
2447                }),
2448                cx,
2449            );
2450            window.render_frame(cx);
2451        }
2452        window.dispatch_event(
2453            PlatformInput::MouseUp(MouseUpEvent {
2454                button: MouseButton::Left,
2455                position: to,
2456                modifiers,
2457                click_count: 1,
2458            }),
2459            cx,
2460        );
2461        window.render_frame(cx);
2462    }
2463
2464    fn anchor(
2465        c: &Entity<FlowCanvas>,
2466        cx: &mut VisualTestContext,
2467        kind: &str,
2468        input: bool,
2469    ) -> gpui_kit::Point<Pixels> {
2470        c.read_with(cx, |c, _| {
2471            let n = c.graph().node(id_of(c, kind)).unwrap();
2472            let port = if input { n.inputs[0] } else { n.outputs[0] };
2473            let a = port_anchor(c.graph(), port).unwrap().0;
2474            let s = c.viewport().world_to_screen(a);
2475            p(s.x, s.y)
2476        })
2477    }
2478
2479    // ---------- F2:视口 ----------
2480
2481    #[gpui_kit::test]
2482    fn renders_layers_and_culls_offscreen_nodes(cx: &mut TestAppContext) {
2483        let (canvas, _, cx) = setup(cx);
2484        cx.update(|window, _| {
2485            let root = window.find("flow");
2486            assert_eq!(root.role(), Some(Role::Application));
2487            assert_eq!(root.bounds().size, size(px(800.0), px(600.0)));
2488            let start = window.find(ElementId::NamedInteger("flow".into(), 1));
2489            assert_eq!(start.role(), Some(Role::Group));
2490            assert_eq!(start.bounds().size, size(px(160.0), px(64.0)));
2491        });
2492        assert_eq!(canvas.read_with(cx, |c, _| c.rendered_counts()), (6, 2));
2493    }
2494
2495    #[gpui_kit::test]
2496    fn background_drag_pans_and_wheel_zooms_about_cursor(cx: &mut TestAppContext) {
2497        let (canvas, _, cx) = setup(cx);
2498        cx.update(|window, cx| window.drag(p(700.0, 500.0), p(760.0, 470.0), cx));
2499        let vp = canvas.read_with(cx, |c, _| c.viewport());
2500        assert!(
2501            (vp.offset.x - 60.0).abs() < 0.5 && (vp.offset.y + 30.0).abs() < 0.5,
2502            "{vp:?}"
2503        );
2504
2505        cx.update(|window, cx| {
2506            window.scroll("flow", ScrollDelta::Pixels(point(px(-15.0), px(-25.0))), cx)
2507        });
2508        let vp = canvas.read_with(cx, |c, _| c.viewport());
2509        assert_eq!(vp.offset, Vec2::new(45.0, -55.0));
2510
2511        let world_before = vp.screen_to_world(Vec2::new(300.0, 200.0));
2512        cx.update(|window, cx| {
2513            window.dispatch_event(
2514                PlatformInput::Scroll(ScrollEvent {
2515                    position: p(300.0, 200.0),
2516                    delta: ScrollDelta::Pixels(point(px(0.0), px(80.0))),
2517                    modifiers: Modifiers {
2518                        control: true,
2519                        ..Default::default()
2520                    },
2521                    ..Default::default()
2522                }),
2523                cx,
2524            );
2525        });
2526        let vp = canvas.read_with(cx, |c, _| c.viewport());
2527        assert!(vp.zoom > 1.0);
2528        assert!(
2529            vp.world_to_screen(world_before)
2530                .distance(Vec2::new(300.0, 200.0))
2531                < 0.01
2532        );
2533    }
2534
2535    #[gpui_kit::test]
2536    fn pinch_zooms_and_keyboard_fits(cx: &mut TestAppContext) {
2537        let (canvas, _, cx) = setup(cx);
2538        cx.update(|window, cx| {
2539            window.dispatch_event(
2540                PlatformInput::Pinch(PinchEvent {
2541                    position: p(400.0, 300.0),
2542                    delta: -0.5,
2543                    modifiers: Modifiers::default(),
2544                    phase: TouchPhase::Moved,
2545                }),
2546                cx,
2547            );
2548        });
2549        assert!((canvas.read_with(cx, |c, _| c.viewport()).zoom - 0.5).abs() < 1e-5);
2550
2551        // 远处节点让内容超出最小缩放的容纳范围:适配视图钳制到 min_zoom,内容中心对准视图中心。
2552        cx.update(|window, cx| {
2553            window.drag(p(700.0, 550.0), p(700.0, 551.0), cx);
2554            window.press("shift-1", cx);
2555            window.render_frame(cx);
2556        });
2557        let vp = canvas.read_with(cx, |c, _| c.viewport());
2558        assert_eq!(vp.zoom, vp.min_zoom, "{vp:?}");
2559        let world = canvas.read_with(cx, |c, _| c.graph().bounds().unwrap());
2560        assert!(
2561            vp.world_to_screen(world.center())
2562                .distance(Vec2::new(400.0, 300.0))
2563                < 0.5
2564        );
2565
2566        cx.update(|window, cx| window.press("ctrl-0", cx));
2567        assert_eq!(canvas.read_with(cx, |c, _| c.viewport()).zoom, 1.0);
2568    }
2569
2570    // ---------- F3:交互 ----------
2571
2572    #[gpui_kit::test]
2573    fn click_selects_drag_moves_with_snap_and_undo(cx: &mut TestAppContext) {
2574        let (canvas, _, cx) = setup(cx);
2575        canvas.update(cx, |c, _| c.snap_grid = Some(20.0));
2576        let llm = canvas.read_with(cx, |c, _| id_of(c, "llm"));
2577        cx.update(|window, cx| window.drag(p(340.0, 30.0), p(397.0, 71.0), cx));
2578        canvas.read_with(cx, |c, _| {
2579            assert_eq!(c.selection(), &HashSet::from([llm]));
2580            // 260+57=317 → 320;0+41=41 → 40。
2581            assert_eq!(c.graph().node(llm).unwrap().pos, Vec2::new(320.0, 40.0));
2582            assert_eq!(c.history().undo_label(), Some("移动节点"));
2583        });
2584        cx.update(|window, cx| window.press("ctrl-z", cx));
2585        assert_eq!(
2586            canvas.read_with(cx, |c, _| c.graph().node(llm).unwrap().pos),
2587            Vec2::new(260.0, 0.0)
2588        );
2589        cx.update(|window, cx| window.press("ctrl-shift-z", cx));
2590        assert_eq!(
2591            canvas.read_with(cx, |c, _| c.graph().node(llm).unwrap().pos),
2592            Vec2::new(320.0, 40.0)
2593        );
2594
2595        // 点击空白清空选择;Shift 点击叠加选择。
2596        cx.update(|window, cx| window.drag(p(700.0, 500.0), p(700.0, 500.0), cx));
2597        assert!(canvas.read_with(cx, |c, _| c.selection().is_empty()));
2598    }
2599
2600    #[gpui_kit::test]
2601    fn shift_drag_marquee_selects_and_moves_group(cx: &mut TestAppContext) {
2602        let (canvas, _, cx) = setup(cx);
2603        let shift = Modifiers {
2604            shift: true,
2605            ..Default::default()
2606        };
2607        cx.update(|window, cx| {
2608            drag_with(window, p(-5.0 + 10.0, 190.0), p(430.0, 280.0), shift, cx)
2609        });
2610        let (src, sink) = canvas.read_with(cx, |c, _| (id_of(c, "src"), id_of(c, "sink")));
2611        // 左边缘从 x=5 开始,src(0..160) 未被完全包住,只选中 sink。
2612        assert_eq!(
2613            canvas.read_with(cx, |c, _| c.selection().clone()),
2614            HashSet::from([sink])
2615        );
2616        cx.update(|window, cx| drag_with(window, p(-1.0 + 1.0, 195.0), p(430.0, 280.0), shift, cx));
2617        // 叠加:再框一次(起点 x=0)包含 src 与 sink。
2618        assert_eq!(
2619            canvas.read_with(cx, |c, _| c.selection().clone()),
2620            HashSet::from([src, sink])
2621        );
2622
2623        cx.update(|window, cx| {
2624            drag_with(
2625                window,
2626                p(80.0, 230.0),
2627                p(80.0, 330.0),
2628                Modifiers::default(),
2629                cx,
2630            )
2631        });
2632        canvas.read_with(cx, |c, _| {
2633            assert_eq!(c.graph().node(src).unwrap().pos, Vec2::new(0.0, 300.0));
2634            assert_eq!(c.graph().node(sink).unwrap().pos, Vec2::new(260.0, 300.0));
2635        });
2636        // 方向键微移合并为一步撤销。
2637        cx.update(|window, cx| {
2638            window.press("right", cx);
2639            window.press("shift-right", cx);
2640        });
2641        assert_eq!(
2642            canvas.read_with(cx, |c, _| c.graph().node(src).unwrap().pos),
2643            Vec2::new(11.0, 300.0)
2644        );
2645        cx.update(|window, cx| window.press("ctrl-z", cx));
2646        assert_eq!(
2647            canvas.read_with(cx, |c, _| c.graph().node(src).unwrap().pos),
2648            Vec2::new(0.0, 300.0)
2649        );
2650    }
2651
2652    #[gpui_kit::test]
2653    fn drag_from_port_connects_with_snap_and_validation(cx: &mut TestAppContext) {
2654        let (canvas, _, cx) = setup(cx);
2655        let from = anchor(&canvas, cx, "src", false);
2656        let to = anchor(&canvas, cx, "sink", true);
2657        // 松手点离输入端 15 px,仍吸附。
2658        cx.update(|window, cx| {
2659            window.drag(from, p(f32::from(to.x) + 12.0, f32::from(to.y) + 9.0), cx)
2660        });
2661        assert_eq!(canvas.read_with(cx, |c, _| c.graph().edge_count()), 3);
2662        assert_eq!(
2663            canvas.read_with(cx, |c, _| c.history().undo_label()),
2664            Some("连线")
2665        );
2666
2667        // llm 的输入端已占用:从 src 连过去被拒,记录 PortFull。
2668        let llm_in = anchor(&canvas, cx, "llm", true);
2669        let src_out = anchor(&canvas, cx, "src", false);
2670        cx.update(|window, cx| window.drag(src_out, llm_in, cx));
2671        canvas.read_with(cx, |c, _| {
2672            assert_eq!(c.graph().edge_count(), 3);
2673            assert_eq!(
2674                c.last_connect_error().map(|e| e.code),
2675                Some(arc_flow_core::ConnectErrorCode::PortFull)
2676            );
2677        });
2678    }
2679
2680    #[gpui_kit::test]
2681    fn dragging_occupied_input_reconnects_or_detaches(cx: &mut TestAppContext) {
2682        let (canvas, _, cx) = setup(cx);
2683        let (llm, sink) = canvas.read_with(cx, |c, _| (id_of(c, "llm"), id_of(c, "sink")));
2684        let llm_in = anchor(&canvas, cx, "llm", true);
2685        let sink_in = anchor(&canvas, cx, "sink", true);
2686        // 把 start→llm 的末端拖到 sink。
2687        cx.update(|window, cx| window.drag(llm_in, sink_in, cx));
2688        canvas.read_with(cx, |c, _| {
2689            assert_eq!(c.graph().edge_count(), 2);
2690            let sink_port = c.graph().node(sink).unwrap().inputs[0];
2691            let llm_port = c.graph().node(llm).unwrap().inputs[0];
2692            assert_eq!(c.graph().edges_of_port(sink_port).len(), 1);
2693            assert!(c.graph().edges_of_port(llm_port).is_empty());
2694            assert_eq!(c.history().undo_label(), Some("重新连接"));
2695        });
2696        // 再从 sink 拖到空白处 = 断开。
2697        cx.update(|window, cx| window.drag(sink_in, p(700.0, 560.0), cx));
2698        assert_eq!(canvas.read_with(cx, |c, _| c.graph().edge_count()), 1);
2699        cx.update(|window, cx| {
2700            window.press("ctrl-z", cx);
2701            window.press("ctrl-z", cx);
2702        });
2703        let llm_port = canvas.read_with(cx, |c, _| c.graph().node(llm).unwrap().inputs[0]);
2704        assert_eq!(
2705            canvas.read_with(cx, |c, _| c.graph().edges_of_port(llm_port).len()),
2706            1
2707        );
2708    }
2709
2710    #[gpui_kit::test]
2711    fn delete_copy_paste_duplicate_and_select_all(cx: &mut TestAppContext) {
2712        let (canvas, _, cx) = setup(cx);
2713        let llm = canvas.read_with(cx, |c, _| id_of(c, "llm"));
2714        cx.update(|window, cx| {
2715            window.drag(p(340.0, 30.0), p(340.0, 30.0), cx);
2716            window.press("backspace", cx);
2717        });
2718        canvas.read_with(cx, |c, _| {
2719            assert!(c.graph().node(llm).is_none());
2720            assert_eq!(c.graph().edge_count(), 0);
2721            assert!(c.selection().is_empty());
2722        });
2723        cx.update(|window, cx| window.press("ctrl-z", cx));
2724        assert_eq!(
2725            canvas.read_with(cx, |c, _| (c.graph().node_count(), c.graph().edge_count())),
2726            (7, 2)
2727        );
2728
2729        // 复制 start + llm,粘贴两次逐次偏移;内部连线跟随。
2730        let start = canvas.read_with(cx, |c, _| id_of(c, "start"));
2731        canvas.update(cx, |c, cx| c.select([start, llm], cx));
2732        cx.update(|window, cx| {
2733            window.drag(p(340.0, 30.0), p(340.0, 30.0), cx);
2734            window.press("ctrl-c", cx);
2735            window.press("ctrl-v", cx);
2736            window.press("ctrl-v", cx);
2737        });
2738        canvas.read_with(cx, |c, _| {
2739            assert_eq!((c.graph().node_count(), c.graph().edge_count()), (11, 4));
2740            assert_eq!(c.selection().len(), 2);
2741            let min_x = c
2742                .selection()
2743                .iter()
2744                .map(|id| c.graph().node(*id).unwrap().pos.x)
2745                .fold(f32::MAX, f32::min);
2746            assert_eq!(min_x, 2.0 * PASTE_OFFSET);
2747        });
2748        cx.update(|window, cx| window.press("ctrl-d", cx));
2749        assert_eq!(canvas.read_with(cx, |c, _| c.graph().node_count()), 13);
2750        cx.update(|window, cx| window.press("ctrl-a", cx));
2751        assert_eq!(canvas.read_with(cx, |c, _| c.selection().len()), 13);
2752        cx.update(|window, cx| window.press("escape", cx));
2753        assert!(canvas.read_with(cx, |c, _| c.selection().is_empty()));
2754    }
2755
2756    #[gpui_kit::test]
2757    fn in_node_control_keeps_focus_and_keys(cx: &mut TestAppContext) {
2758        let (canvas, field, cx) = setup(cx);
2759        let node = canvas.read_with(cx, |c, _| id_of(c, "field"));
2760        cx.update(|window, cx| {
2761            // 在节点内控件上拖动:控件拿到焦点,节点不动、不被选中。
2762            window.drag(p(540.0, 320.0), p(600.0, 380.0), cx);
2763            assert!(field.is_focused(window));
2764            window.press("backspace", cx);
2765            window.press("ctrl-a", cx);
2766        });
2767        canvas.read_with(cx, |c, _| {
2768            assert_eq!(c.graph().node(node).unwrap().pos, Vec2::new(520.0, 300.0));
2769            assert!(c.selection().is_empty());
2770            assert_eq!(c.graph().node_count(), 7);
2771        });
2772        // 点节点的非控件区域:画布拿回焦点并选中节点。
2773        cx.update(|window, cx| window.drag(p(650.0, 350.0), p(650.0, 350.0), cx));
2774        canvas.read_with(cx, |c, _| assert_eq!(c.selection(), &HashSet::from([node])));
2775    }
2776
2777    // ---------- F4:边 ----------
2778
2779    #[gpui_kit::test]
2780    fn click_edge_selects_and_delete_removes_only_edge(cx: &mut TestAppContext) {
2781        let (canvas, _, cx) = setup(cx);
2782        let start_llm = canvas.read_with(cx, |c, _| {
2783            let out = c.graph().node(id_of(c, "start")).unwrap().outputs[0];
2784            c.graph().edges_of_port(out)[0]
2785        });
2786        // start→llm 是 y=32 的水平线;偏离 4 px 仍命中。
2787        cx.update(|window, cx| window.drag(p(210.0, 36.0), p(210.0, 36.0), cx));
2788        canvas.read_with(cx, |c, _| {
2789            assert_eq!(c.edge_selection(), &HashSet::from([start_llm]));
2790            assert!(c.selection().is_empty());
2791        });
2792        // 偏离 12 px 不命中:点空白清空。
2793        cx.update(|window, cx| window.drag(p(210.0, 44.0), p(210.0, 44.0), cx));
2794        assert!(canvas.read_with(cx, |c, _| c.edge_selection().is_empty()));
2795
2796        cx.update(|window, cx| {
2797            window.drag(p(210.0, 32.0), p(210.0, 32.0), cx);
2798            window.press("delete", cx);
2799        });
2800        canvas.read_with(cx, |c, _| {
2801            assert_eq!((c.graph().node_count(), c.graph().edge_count()), (7, 1));
2802            assert!(c.edge_selection().is_empty());
2803        });
2804        cx.update(|window, cx| window.press("ctrl-z", cx));
2805        assert_eq!(canvas.read_with(cx, |c, _| c.graph().edge_count()), 2);
2806
2807        // 全选包含边;Shift 点击边切换。
2808        cx.update(|window, cx| window.press("ctrl-a", cx));
2809        assert_eq!(canvas.read_with(cx, |c, _| c.edge_selection().len()), 2);
2810        cx.update(|window, cx| window.press("escape", cx));
2811        assert!(canvas.read_with(cx, |c, _| c.edge_selection().is_empty()));
2812    }
2813
2814    #[gpui_kit::test]
2815    fn selected_edge_source_handle_reconnects_source(cx: &mut TestAppContext) {
2816        let (canvas, _, cx) = setup(cx);
2817        let (llm, src, end) = canvas.read_with(cx, |c, _| {
2818            (id_of(c, "llm"), id_of(c, "src"), id_of(c, "end"))
2819        });
2820        let llm_out = anchor(&canvas, cx, "llm", false);
2821        let src_out = anchor(&canvas, cx, "src", false);
2822        // 未选中边时,从 llm 输出端拖动 = 新建连线(拖到空白什么都不做)。
2823        cx.update(|window, cx| window.drag(llm_out, p(700.0, 560.0), cx));
2824        assert_eq!(canvas.read_with(cx, |c, _| c.graph().edge_count()), 2);
2825
2826        // 选中 llm→end(取其几何中点),再拖源端把手到 src 输出端。
2827        let mid = canvas.read_with(cx, |c, _| {
2828            let out = c.graph().node(llm).unwrap().outputs[0];
2829            let e = c.graph().edge(c.graph().edges_of_port(out)[0]).unwrap();
2830            let g = arc_flow_core::edge_geometry(c.graph(), e).unwrap();
2831            let s = c.viewport().world_to_screen(g.points[g.points.len() / 2]);
2832            p(s.x, s.y)
2833        });
2834        cx.update(|window, cx| {
2835            window.drag(mid, mid, cx);
2836            window.drag(llm_out, src_out, cx);
2837        });
2838        canvas.read_with(cx, |c, _| {
2839            let g = c.graph();
2840            let end_in = g.node(end).unwrap().inputs[0];
2841            let e = g.edge(g.edges_of_port(end_in)[0]).unwrap();
2842            assert_eq!(e.from, g.node(src).unwrap().outputs[0]);
2843            assert!(g.edges_of_port(g.node(llm).unwrap().outputs[0]).is_empty());
2844            assert_eq!(c.history().undo_label(), Some("重新连接"));
2845        });
2846    }
2847
2848    // ---------- F5:外围 ----------
2849
2850    fn mouse(window: &mut Window, ev: PlatformInput, cx: &mut App) {
2851        window.dispatch_event(ev, cx);
2852        window.render_frame(cx);
2853    }
2854
2855    fn down(button: MouseButton, at: gpui_kit::Point<Pixels>) -> PlatformInput {
2856        PlatformInput::MouseDown(MouseDownEvent {
2857            button,
2858            position: at,
2859            modifiers: Modifiers::default(),
2860            click_count: 1,
2861            first_mouse: false,
2862        })
2863    }
2864
2865    fn moved(at: gpui_kit::Point<Pixels>) -> PlatformInput {
2866        PlatformInput::MouseMove(MouseMoveEvent {
2867            position: at,
2868            pressed_button: Some(MouseButton::Left),
2869            modifiers: Modifiers::default(),
2870        })
2871    }
2872
2873    fn up(at: gpui_kit::Point<Pixels>) -> PlatformInput {
2874        PlatformInput::MouseUp(MouseUpEvent {
2875            button: MouseButton::Left,
2876            position: at,
2877            modifiers: Modifiers::default(),
2878            click_count: 1,
2879        })
2880    }
2881
2882    #[gpui_kit::test]
2883    fn dragging_aligns_to_neighbours_and_shows_guides(cx: &mut TestAppContext) {
2884        let (canvas, _, cx) = setup(cx);
2885        let sink = canvas.read_with(cx, |c, _| id_of(c, "sink"));
2886        // sink(260,200) 上移 75 → y=125,距 end 的上边 120 只差 5 px,吸附过去;
2887        // x 与 llm 左边 260 重合,画一条竖线。
2888        cx.update(|window, cx| {
2889            mouse(window, down(MouseButton::Left, p(340.0, 232.0)), cx);
2890            mouse(window, moved(p(340.0, 200.0)), cx);
2891            mouse(window, moved(p(340.0, 157.0)), cx);
2892        });
2893        canvas.read_with(cx, |c, _| {
2894            assert_eq!(c.graph().node(sink).unwrap().pos, Vec2::new(260.0, 120.0));
2895            assert_eq!(c.guides().len(), 2);
2896            assert!(
2897                c.guides()
2898                    .iter()
2899                    .any(|g| g.from.x == 260.0 && g.to.x == 260.0)
2900            );
2901            assert!(
2902                c.guides()
2903                    .iter()
2904                    .any(|g| g.from.y == 120.0 && g.to.y == 120.0)
2905            );
2906        });
2907        cx.update(|window, cx| mouse(window, up(p(340.0, 157.0)), cx));
2908        canvas.read_with(cx, |c, _| {
2909            assert!(c.guides().is_empty());
2910            assert_eq!(c.graph().node(sink).unwrap().pos, Vec2::new(260.0, 120.0));
2911        });
2912
2913        // 关闭后按指针原样移动。
2914        canvas.update(cx, |c, _| c.align_guides = false);
2915        cx.update(|window, cx| window.press("ctrl-z", cx));
2916        cx.update(|window, cx| window.drag(p(340.0, 232.0), p(340.0, 157.0), cx));
2917        canvas.read_with(cx, |c, _| {
2918            assert_eq!(c.graph().node(sink).unwrap().pos, Vec2::new(260.0, 125.0));
2919            assert!(c.guides().is_empty());
2920        });
2921    }
2922
2923    #[gpui_kit::test]
2924    fn minimap_click_recentres_without_touching_selection(cx: &mut TestAppContext) {
2925        let (canvas, _, cx) = setup(cx);
2926        canvas.update(cx, |c, cx| {
2927            c.show_minimap = true;
2928            // 去掉远处节点,小地图比例更直观。
2929            let far = id_of(c, "far");
2930            c.commit(c.graph.delete_ops(&[far], &[]), "删除", cx)
2931                .unwrap();
2932            let llm = id_of(c, "llm");
2933            c.select([llm], cx);
2934        });
2935        cx.update(|window, cx| window.render_frame(cx));
2936        let (t, origin) = canvas.read_with(cx, |c, _| c.minimap_transform().unwrap());
2937        // 点小地图框内的 (50, 40)。
2938        let local = origin.plus(Vec2::new(50.0, 40.0));
2939        let target = t.to_world(Vec2::new(50.0, 40.0));
2940        cx.update(|window, cx| window.drag(p(local.x, local.y), p(local.x, local.y), cx));
2941        canvas.read_with(cx, |c, _| {
2942            let centre = c.viewport().screen_to_world(c.view_center());
2943            assert!(centre.distance(target) < 0.5, "{centre:?} vs {target:?}");
2944            assert_eq!(c.selection().len(), 1);
2945        });
2946    }
2947
2948    #[gpui_kit::test]
2949    fn controls_zoom_fit_and_lock(cx: &mut TestAppContext) {
2950        let (canvas, _, cx) = setup(cx);
2951        canvas.update(cx, |c, _| c.show_controls = true);
2952        cx.update(|window, cx| {
2953            window.render_frame(cx);
2954            window.click("flow-zoom-in", cx);
2955        });
2956        let z = canvas.read_with(cx, |c, _| c.viewport().zoom);
2957        assert!((z - KEY_ZOOM_STEP).abs() < 1e-4);
2958        cx.update(|window, cx| window.click("flow-zoom-out", cx));
2959        assert!((canvas.read_with(cx, |c, _| c.viewport().zoom) - 1.0).abs() < 1e-4);
2960
2961        cx.update(|window, cx| window.click("flow-lock", cx));
2962        let llm = canvas.read_with(cx, |c, _| {
2963            assert!(!c.interactive());
2964            id_of(c, "llm")
2965        });
2966        // 锁定后:拖节点变成平移,节点位置不变;Delete 无效。
2967        cx.update(|window, cx| {
2968            window.drag(p(340.0, 32.0), p(400.0, 32.0), cx);
2969            window.press("delete", cx);
2970        });
2971        canvas.read_with(cx, |c, _| {
2972            assert_eq!(c.graph().node(llm).unwrap().pos, Vec2::new(260.0, 0.0));
2973            assert_eq!(c.graph().node_count(), 7);
2974            assert!(c.viewport().offset.distance(Vec2::new(60.0, 0.0)) < 1e-3);
2975        });
2976        cx.update(|window, cx| {
2977            window.click("flow-lock", cx);
2978            window.click("flow-fit", cx);
2979        });
2980        canvas.read_with(cx, |c, _| {
2981            assert!(c.interactive());
2982            assert!(c.viewport().zoom < 1.0, "fit 包含远处节点,必然缩小");
2983        });
2984    }
2985
2986    #[gpui_kit::test]
2987    fn right_click_reports_target_and_selects_it(cx: &mut TestAppContext) {
2988        let (canvas, _, cx) = setup(cx);
2989        let hits: Rc<std::cell::RefCell<Vec<ContextTarget>>> = Rc::default();
2990        let sink = hits.clone();
2991        canvas.update(cx, |c, _| {
2992            c.on_context_menu = Some(Rc::new(move |t, _, _, _| sink.borrow_mut().push(*t)));
2993        });
2994        cx.update(|window, cx| {
2995            mouse(window, down(MouseButton::Right, p(340.0, 32.0)), cx);
2996            mouse(window, down(MouseButton::Right, p(210.0, 32.0)), cx);
2997            mouse(window, down(MouseButton::Right, p(700.0, 560.0)), cx);
2998        });
2999        canvas.read_with(cx, |c, _| {
3000            let llm = id_of(c, "llm");
3001            let out = c.graph().node(id_of(c, "start")).unwrap().outputs[0];
3002            let edge = c.graph().edges_of_port(out)[0];
3003            assert_eq!(
3004                *hits.borrow(),
3005                vec![
3006                    ContextTarget::Node(llm),
3007                    ContextTarget::Edge(edge),
3008                    ContextTarget::Pane
3009                ]
3010            );
3011            // 最后一次右键空白不清空选择(右键边时已改为选中该边)。
3012            assert!(c.selection().is_empty());
3013            assert_eq!(c.edge_selection(), &HashSet::from([edge]));
3014        });
3015    }
3016
3017    // ---------- F6:动效 ----------
3018
3019    fn advance(cx: &mut VisualTestContext, ms: u64) {
3020        cx.executor()
3021            .advance_clock(std::time::Duration::from_millis(ms));
3022        cx.update(|window, cx| window.render_frame(cx));
3023    }
3024
3025    #[gpui_kit::test]
3026    fn release_springs_into_grid_slot(cx: &mut TestAppContext) {
3027        let (canvas, _, cx) = setup_with(cx, false);
3028        canvas.update(cx, |c, _| {
3029            c.snap_grid = Some(20.0);
3030            c.align_guides = false;
3031        });
3032        let llm = canvas.read_with(cx, |c, _| id_of(c, "llm"));
3033        // 拖 47 px:模型吸附到 +40,显示跟手在 +47。
3034        cx.update(|window, cx| {
3035            mouse(window, down(MouseButton::Left, p(340.0, 32.0)), cx);
3036            mouse(window, moved(p(387.0, 32.0)), cx);
3037        });
3038        canvas.read_with(cx, |c, _| {
3039            assert_eq!(c.graph().node(llm).unwrap().pos, Vec2::new(300.0, 0.0));
3040            assert_eq!(c.motion().own_offset(llm, 0.0), Vec2::new(7.0, 0.0));
3041        });
3042        cx.update(|window, cx| mouse(window, up(p(387.0, 32.0)), cx));
3043        advance(cx, 16);
3044        let mid = canvas.read_with(cx, |c, _| c.motion().has_offsets());
3045        assert!(mid, "松手后仍在弹簧落位");
3046        advance(cx, 1500);
3047        canvas.read_with(cx, |c, _| {
3048            assert!(!c.motion().has_offsets());
3049            assert_eq!(c.graph().node(llm).unwrap().pos, Vec2::new(300.0, 0.0));
3050        });
3051    }
3052
3053    #[gpui_kit::test]
3054    fn zoom_and_fit_animate_viewport(cx: &mut TestAppContext) {
3055        let (canvas, _, cx) = setup_with(cx, false);
3056        cx.update(|window, cx| {
3057            // 先点一下空白处让画布获得焦点。
3058            window.drag(p(700.0, 560.0), p(700.0, 560.0), cx);
3059            window.press("ctrl-=", cx);
3060        });
3061        canvas.read_with(cx, |c, _| {
3062            assert!((c.target_viewport().zoom - KEY_ZOOM_STEP).abs() < 1e-4);
3063            assert!(c.viewport().zoom < KEY_ZOOM_STEP);
3064            assert!(c.motion().view_animating());
3065        });
3066        // 连按:终点在上一个终点上累加。
3067        cx.update(|window, cx| window.press("ctrl-=", cx));
3068        let want = KEY_ZOOM_STEP * KEY_ZOOM_STEP;
3069        assert!((canvas.read_with(cx, |c, _| c.target_viewport().zoom) - want).abs() < 1e-4);
3070        advance(cx, 120);
3071        let z = canvas.read_with(cx, |c, _| c.viewport().zoom);
3072        assert!(z > 1.0 && z < want, "{z}");
3073        advance(cx, 1500);
3074        canvas.read_with(cx, |c, _| {
3075            assert!((c.viewport().zoom - want).abs() < 1e-3);
3076            assert!(!c.motion().view_animating());
3077        });
3078        // 滚轮打断动画,立即生效。
3079        cx.update(|window, cx| window.press("shift-1", cx));
3080        canvas.read_with(cx, |c, _| assert!(c.motion().view_animating()));
3081        cx.update(|window, cx| {
3082            window.scroll("flow", ScrollDelta::Pixels(point(px(0.0), px(-10.0))), cx)
3083        });
3084        canvas.read_with(cx, |c, _| assert!(!c.motion().view_animating()));
3085    }
3086
3087    #[gpui_kit::test]
3088    fn nodes_fade_in_and_out_and_new_edges_draw_in(cx: &mut TestAppContext) {
3089        let (canvas, _, cx) = setup_with(cx, false);
3090        let llm = canvas.read_with(cx, |c, _| id_of(c, "llm"));
3091        cx.update(|window, cx| {
3092            window.drag(p(340.0, 32.0), p(340.0, 32.0), cx);
3093            window.press("delete", cx);
3094            window.render_frame(cx);
3095        });
3096        canvas.read_with(cx, |c, _| {
3097            assert!(c.graph().node(llm).is_none());
3098            assert_eq!(c.motion().ghosts(0.0).count(), 1);
3099        });
3100        // 撤销:节点回来,残影撤掉,节点重新进场,连线重新绘入。
3101        cx.update(|window, cx| {
3102            window.press("ctrl-z", cx);
3103            window.render_frame(cx);
3104        });
3105        let edge = canvas.read_with(cx, |c, _| {
3106            let out = c.graph().node(llm).unwrap().outputs[0];
3107            c.graph().edges_of_port(out)[0]
3108        });
3109        canvas.update(cx, |c, cx| {
3110            let now = motion_now(cx);
3111            assert_eq!(c.motion().ghosts(now).count(), 0);
3112            assert!(c.motion().enter_sample(llm, now).opacity < 1.0);
3113            assert!(c.motion().draw_progress(edge, now) < 1.0);
3114        });
3115        advance(cx, 400);
3116        canvas.update(cx, |c, cx| {
3117            let now = motion_now(cx);
3118            assert_eq!(c.motion().enter_sample(llm, now), Appear::FULL);
3119            assert_eq!(c.motion().draw_progress(edge, now), 1.0);
3120        });
3121    }
3122
3123    #[gpui_kit::test]
3124    fn invalid_target_shakes(cx: &mut TestAppContext) {
3125        let (canvas, _, cx) = setup_with(cx, false);
3126        canvas.update(cx, |c, _| c.validator = Rc::new(DefaultValidator::dag()));
3127        // 从 llm 输出拖到 llm 自己的输入:SameNode,非法。
3128        let from = anchor(&canvas, cx, "llm", false);
3129        let to = anchor(&canvas, cx, "llm", true);
3130        cx.update(|window, cx| window.drag(from, to, cx));
3131        canvas.update(cx, |c, cx| {
3132            let now = motion_now(cx);
3133            assert!(c.last_connect_error().is_some());
3134            assert!(c.motion().shake(now).is_some());
3135        });
3136    }
3137
3138    // ---------- F8:LOD 与性能 ----------
3139
3140    /// cols × rows 网格;先连横向,再按行连纵向,直到边数达到 `edges`。
3141    fn grid_graph(cols: usize, rows: usize, edges: usize) -> Graph {
3142        let mut g = Graph::new();
3143        let mut ports = Vec::new();
3144        for r in 0..rows {
3145            for c in 0..cols {
3146                let (_, i, o) =
3147                    g.add_node_with("n", Vec2::new(c as f32 * 220.0, r as f32 * 110.0), SZ, 2, 2);
3148                ports.push((i, o));
3149            }
3150        }
3151        let mut n = 0;
3152        'h: for r in 0..rows {
3153            for c in 0..cols.saturating_sub(1) {
3154                if n == edges {
3155                    break 'h;
3156                }
3157                let _ = g.connect(ports[r * cols + c].1[0], ports[r * cols + c + 1].0[0]);
3158                n += 1;
3159            }
3160        }
3161        'v: for r in 0..rows.saturating_sub(1) {
3162            for c in 0..cols {
3163                if n == edges {
3164                    break 'v;
3165                }
3166                let _ = g.connect(ports[r * cols + c].1[1], ports[(r + 1) * cols + c].0[1]);
3167                n += 1;
3168            }
3169        }
3170        g
3171    }
3172
3173    fn load(canvas: &Entity<FlowCanvas>, cx: &mut VisualTestContext, graph: Graph) {
3174        canvas.update(cx, |c, _| {
3175            c.graph = graph;
3176            c.cache = DerivedCache::empty();
3177            c.visible_cache = None;
3178            c.presence_revision = None;
3179            c.selection.clear();
3180            c.edge_selection.clear();
3181        });
3182        cx.update(|window, cx| window.render_frame(cx));
3183    }
3184
3185    fn set_zoom(canvas: &Entity<FlowCanvas>, cx: &mut VisualTestContext, zoom: f32) {
3186        canvas.update(cx, |c, _| {
3187            c.viewport.zoom = zoom;
3188            c.viewport.offset = Vec2::new(10.0, 10.0);
3189        });
3190        cx.update(|window, cx| window.render_frame(cx));
3191    }
3192
3193    #[gpui_kit::test]
3194    fn lod_switches_between_full_shell_and_dot(cx: &mut TestAppContext) {
3195        let (canvas, _, cx) = setup(cx);
3196        load(&canvas, cx, grid_graph(30, 20, 600));
3197        set_zoom(&canvas, cx, 1.0);
3198        let (full, shell, dot) = canvas.read_with(cx, |c, _| c.rendered_lod());
3199        assert!(full > 0 && shell == 0 && dot == 0);
3200        // ≥500 节点且缩放 ≤0.2:整体外壳,不建节点元素。
3201        set_zoom(&canvas, cx, 0.15);
3202        let (full, shell, dot) = canvas.read_with(cx, |c, _| c.rendered_lod());
3203        assert_eq!((full, dot), (0, 0));
3204        assert!(shell > 100, "{shell}");
3205        // 节点在屏幕上不足 4 px:只画点。
3206        set_zoom(&canvas, cx, 0.05);
3207        let (full, shell, dot) = canvas.read_with(cx, |c, _| c.rendered_lod());
3208        assert_eq!((full, shell), (0, 0));
3209        assert_eq!(dot, 600);
3210        // 小图即使缩到 0.15 也保留完整渲染(节点 64 × 0.15 < 12 px 时按单个节点降级)。
3211        load(&canvas, cx, sample_graph());
3212        set_zoom(&canvas, cx, 0.3);
3213        let (full, shell, _) = canvas.read_with(cx, |c, _| c.rendered_lod());
3214        assert!(full > 0 && shell == 0);
3215    }
3216
3217    #[gpui_kit::test]
3218    fn moving_one_node_only_recomputes_its_edges(cx: &mut TestAppContext) {
3219        let (canvas, _, cx) = setup(cx);
3220        let (llm, untouched, touched) = canvas.read_with(cx, |c, _| {
3221            let llm = id_of(c, "llm");
3222            let start_out = c.graph().node(id_of(c, "start")).unwrap().outputs[0];
3223            let touched = c.graph().edges_of_port(start_out)[0];
3224            (llm, c.cache.edge_lookup.clone(), touched)
3225        });
3226        canvas.update(cx, |c, cx| {
3227            c.update_graph(cx, |g| {
3228                let _ = g.apply(GraphOp::MoveNodes {
3229                    moves: vec![(llm, Vec2::new(260.0, 40.0))],
3230                });
3231            })
3232        });
3233        cx.update(|window, cx| window.render_frame(cx));
3234        canvas.read_with(cx, |c, _| {
3235            for (id, old) in &untouched {
3236                let new = &c.cache.edge_lookup[id];
3237                let llm_edge = {
3238                    let e = c.graph().edge(*id).unwrap();
3239                    [e.from, e.to]
3240                        .iter()
3241                        .any(|p| c.graph().port(*p).unwrap().node == llm)
3242                };
3243                assert_eq!(Rc::ptr_eq(old, new), !llm_edge, "{id:?}");
3244            }
3245            assert!(!Rc::ptr_eq(
3246                &untouched[&touched],
3247                &c.cache.edge_lookup[&touched]
3248            ));
3249        });
3250    }
3251
3252    /// 无窗口帧耗时基准(布局 + 场景构建,不含 GPU 光栅化)。
3253    /// `cargo test -p arc-flow --release -- --ignored --nocapture bench_frame_times`
3254    #[gpui_kit::test]
3255    #[ignore]
3256    fn bench_frame_times(cx: &mut TestAppContext) {
3257        let (canvas, _, cx) = setup(cx);
3258        let report = |name: &str,
3259                      cx: &mut VisualTestContext,
3260                      frames: usize,
3261                      step: &dyn Fn(&mut FlowCanvas, usize)| {
3262            // 预热
3263            cx.update(|window, cx| window.render_frame(cx));
3264            let mut times = Vec::with_capacity(frames);
3265            for i in 0..frames {
3266                canvas.update(cx, |c, _| step(c, i));
3267                let t = std::time::Instant::now();
3268                cx.update(|window, cx| window.render_frame(cx));
3269                times.push(t.elapsed().as_secs_f64() * 1000.0);
3270            }
3271            times.sort_by(f64::total_cmp);
3272            let avg = times.iter().sum::<f64>() / times.len() as f64;
3273            let p95 = times[(times.len() * 95 / 100).min(times.len() - 1)];
3274            let (n, e) = canvas.read_with(cx, |c, _| c.rendered_counts());
3275            let lod = canvas.read_with(cx, |c, _| c.rendered_lod());
3276            println!(
3277                "BENCH {name:<34} avg {avg:6.2} ms  p95 {p95:6.2} ms  drawn {n} nodes / {e} edges  lod {lod:?}"
3278            );
3279        };
3280        let pan = |c: &mut FlowCanvas, i: usize| {
3281            c.viewport.offset.x += if i.is_multiple_of(2) { 3.0 } else { -3.0 };
3282        };
3283
3284        load(&canvas, cx, grid_graph(40, 25, 975));
3285        set_zoom(&canvas, cx, 1.0);
3286        report("1000 nodes pan @1.0", cx, 60, &pan);
3287        canvas.update(cx, |c, _| {
3288            let b = c.graph.bounds().unwrap();
3289            c.viewport.fit(&b, c.view_size().unwrap(), FIT_PADDING);
3290        });
3291        report("1000 nodes pan @fit", cx, 60, &pan);
3292
3293        load(&canvas, cx, grid_graph(100, 50, 8000));
3294        set_zoom(&canvas, cx, 1.0);
3295        report("5000 nodes / 8000 edges pan @1.0", cx, 60, &pan);
3296        set_zoom(&canvas, cx, 0.4);
3297        report("5000 / 8000 pan @0.4", cx, 60, &pan);
3298        canvas.update(cx, |c, _| {
3299            let b = c.graph.bounds().unwrap();
3300            c.viewport.fit(&b, c.view_size().unwrap(), FIT_PADDING);
3301        });
3302        report("5000 / 8000 pan @fit (LOD)", cx, 60, &pan);
3303        report("5000 / 8000 zoom @fit (LOD)", cx, 60, &|c, i| {
3304            let k = if i.is_multiple_of(2) {
3305                1.02
3306            } else {
3307                1.0 / 1.02
3308            };
3309            c.viewport.zoom_by_at(k, Vec2::new(400.0, 300.0));
3310        });
3311
3312        // 对照:同样 5,000 节点但没有边,区分节点外壳与边路径各自的开销。
3313        load(&canvas, cx, grid_graph(100, 50, 0));
3314        canvas.update(cx, |c, _| {
3315            let b = c.graph.bounds().unwrap();
3316            c.viewport.fit(&b, c.view_size().unwrap(), FIT_PADDING);
3317        });
3318        report("5000 / 0 edges pan @fit (LOD)", cx, 60, &pan);
3319        load(&canvas, cx, grid_graph(100, 50, 8000));
3320
3321        // 拖动 200 个选中节点:直接施加 MoveNodes(与拖拽路径相同的重建开销)。
3322        set_zoom(&canvas, cx, 0.5);
3323        let ids: Vec<NodeId> = canvas.read_with(cx, |c, _| c.graph.node_ids()[..200].to_vec());
3324        let origins: Vec<(NodeId, Vec2)> = canvas.read_with(cx, |c, _| {
3325            ids.iter()
3326                .map(|id| (*id, c.graph.node(*id).unwrap().pos))
3327                .collect()
3328        });
3329        report("drag 200 of 5000 nodes @0.5", cx, 60, &|c, i| {
3330            let d = Vec2::new(i as f32 * 2.0, 0.0);
3331            let moves = origins.iter().map(|(id, p)| (*id, p.plus(d))).collect();
3332            let _ = c.graph.apply(GraphOp::MoveNodes { moves });
3333        });
3334    }
3335
3336    // ---------- F9:无障碍 ----------
3337
3338    #[gpui_kit::test]
3339    fn tab_walks_reading_order_and_scrolls_to_far_nodes(cx: &mut TestAppContext) {
3340        let (canvas, _, cx) = setup(cx);
3341        let order = canvas.read_with(cx, |c, _| crate::a11y::reading_order(c.graph()));
3342        cx.update(|window, cx| {
3343            // 点空白处获得焦点(不选中任何节点)。
3344            window.drag(p(700.0, 560.0), p(700.0, 560.0), cx);
3345            window.press("tab", cx);
3346        });
3347        assert_eq!(canvas.read_with(cx, |c, _| c.active_node()), Some(order[0]));
3348        cx.update(|window, cx| window.press("shift-tab", cx));
3349        assert_eq!(
3350            canvas.read_with(cx, |c, _| c.active_node()),
3351            Some(order[0]).map(|_| *order.last().unwrap())
3352        );
3353        // 走一圈:每个节点都会成为当前节点,并且都在视口内。
3354        for want in &order {
3355            cx.update(|window, cx| window.press("tab", cx));
3356            canvas.read_with(cx, |c, _| {
3357                assert_eq!(c.active_node(), Some(*want));
3358                let rect = c.graph().world_rect(*want).unwrap();
3359                let view = c.viewport().visible_world_rect(c.view_size().unwrap());
3360                assert!(view.contains_rect(&rect), "{want:?} 不在视口内");
3361            });
3362        }
3363    }
3364
3365    #[gpui_kit::test]
3366    fn alt_arrows_follow_edges_and_nodes_describe_themselves(cx: &mut TestAppContext) {
3367        let (canvas, _, cx) = setup(cx);
3368        let (start, llm, end) = canvas.read_with(cx, |c, _| {
3369            (id_of(c, "start"), id_of(c, "llm"), id_of(c, "end"))
3370        });
3371        cx.update(|window, cx| {
3372            window.drag(p(40.0, 32.0), p(40.0, 32.0), cx);
3373            window.press("alt-right", cx);
3374        });
3375        assert_eq!(canvas.read_with(cx, |c, _| c.active_node()), Some(llm));
3376        cx.update(|window, cx| window.press("alt-right", cx));
3377        assert_eq!(canvas.read_with(cx, |c, _| c.active_node()), Some(end));
3378        cx.update(|window, cx| window.press("alt-left", cx));
3379        assert_eq!(canvas.read_with(cx, |c, _| c.active_node()), Some(llm));
3380        cx.update(|window, cx| window.press("alt-left", cx));
3381        assert_eq!(canvas.read_with(cx, |c, _| c.active_node()), Some(start));
3382        // 只有一个相邻节点时 Alt+↓ 停在原地。
3383        cx.update(|window, cx| window.press("alt-down", cx));
3384        assert_eq!(canvas.read_with(cx, |c, _| c.active_node()), Some(start));
3385
3386        cx.update(|window, cx| window.render_frame(cx));
3387        let node =
3388            cx.update(|window, _| window.find(ElementId::NamedInteger("flow".into(), start.0)));
3389        assert_eq!(node.role(), Some(Role::Group));
3390        assert_eq!(node.selected(), Some(true));
3391        let want = canvas.read_with(cx, |c, cx| {
3392            crate::a11y::describe_node(c.graph(), start, cx.arc_locale())
3393        });
3394        assert_eq!(node.description(), Some(want.as_str()));
3395        assert!(want.contains("llm") || want.contains("LLM"), "{want}");
3396        let root = cx.update(|window, _| window.find("flow"));
3397        assert!(root.description().unwrap().contains("Tab"));
3398    }
3399
3400    #[gpui_kit::test]
3401    fn navigation_works_when_locked(cx: &mut TestAppContext) {
3402        let (canvas, _, cx) = setup(cx);
3403        cx.update(|window, cx| {
3404            window.drag(p(700.0, 560.0), p(700.0, 560.0), cx);
3405            canvas.update(cx, |c, cx| c.set_interactive(false, cx));
3406            window.press("tab", cx);
3407        });
3408        assert!(canvas.read_with(cx, |c, _| c.active_node()).is_some());
3409    }
3410}