arc-flow-core 0.2.0

Framework-free graph model for arc-flow: nodes, typed ports, edges, reversible ops, history, validation, edge geometry and spatial index.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
//! 图存储与查询。所有可撤销的修改都经由 [`Graph::apply`](见 [`crate::op`])。

use crate::edge::Edge;
use crate::geometry::{Rect, Size2, Vec2};
use crate::ids::{EdgeId, NodeId, PortId};
use crate::node::{Node, NodeStatus};
use crate::port::{Port, PortDirection};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet, VecDeque};
use std::fmt;

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum GraphError {
    MissingNode(NodeId),
    MissingPort(PortId),
    MissingEdge(EdgeId),
    DuplicateId(u64),
    /// 节点仍有连线或子节点,不能直接删除(请用 [`Graph::delete_ops`])。
    NodeInUse(NodeId),
    PortInUse(PortId),
    WouldCreateCycle {
        parent: NodeId,
        child: NodeId,
    },
    Format(String),
}

impl fmt::Display for GraphError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::MissingNode(id) => write!(f, "missing node {id}"),
            Self::MissingPort(id) => write!(f, "missing port {id}"),
            Self::MissingEdge(id) => write!(f, "missing edge {id}"),
            Self::DuplicateId(id) => write!(f, "duplicate id {id}"),
            Self::NodeInUse(id) => write!(f, "node {id} still has edges or children"),
            Self::PortInUse(id) => write!(f, "port {id} still has edges"),
            Self::WouldCreateCycle { parent, child } => {
                write!(f, "reparenting {child} under {parent} would create a cycle")
            }
            Self::Format(m) => write!(f, "invalid document: {m}"),
        }
    }
}

impl std::error::Error for GraphError {}

#[derive(Clone, Debug, Default)]
pub struct Graph {
    pub(crate) nodes: HashMap<NodeId, Node>,
    pub(crate) ports: HashMap<PortId, Port>,
    pub(crate) edges: HashMap<EdgeId, Edge>,
    /// 绘制顺序(后者在上)。
    pub(crate) order: Vec<NodeId>,
    pub(crate) port_edges: HashMap<PortId, Vec<EdgeId>>,
    pub(crate) children: HashMap<NodeId, Vec<NodeId>>,
    next_id: u64,
    revision: u64,
}

/// 持久化文档格式。
#[derive(Serialize, Deserialize)]
struct GraphDoc {
    version: u32,
    next_id: u64,
    nodes: Vec<Node>,
    ports: Vec<Port>,
    edges: Vec<Edge>,
}

impl Graph {
    pub fn new() -> Self {
        Self {
            next_id: 1,
            ..Default::default()
        }
    }

    // ---------- ID 与修订号 ----------

    fn alloc(&mut self) -> u64 {
        let id = self.next_id.max(1);
        self.next_id = id + 1;
        id
    }

    pub fn alloc_node_id(&mut self) -> NodeId {
        NodeId(self.alloc())
    }

    pub fn alloc_port_id(&mut self) -> PortId {
        PortId(self.alloc())
    }

    pub fn alloc_edge_id(&mut self) -> EdgeId {
        EdgeId(self.alloc())
    }

    fn reserve(&mut self, raw: u64) {
        if raw >= self.next_id {
            self.next_id = raw + 1;
        }
    }

    /// 每次修改递增;视图层据此判断缓存(可见集合、空间索引)是否失效。
    pub fn revision(&self) -> u64 {
        self.revision
    }

    pub(crate) fn bump(&mut self) {
        self.revision += 1;
    }

    // ---------- 查询 ----------

    pub fn node(&self, id: NodeId) -> Option<&Node> {
        self.nodes.get(&id)
    }

    pub fn port(&self, id: PortId) -> Option<&Port> {
        self.ports.get(&id)
    }

    pub fn edge(&self, id: EdgeId) -> Option<&Edge> {
        self.edges.get(&id)
    }

    pub fn node_count(&self) -> usize {
        self.nodes.len()
    }

    pub fn edge_count(&self) -> usize {
        self.edges.len()
    }

    /// 按绘制顺序遍历节点。
    pub fn nodes(&self) -> impl Iterator<Item = &Node> {
        self.order.iter().filter_map(|id| self.nodes.get(id))
    }

    pub fn node_ids(&self) -> &[NodeId] {
        &self.order
    }

    pub fn edges(&self) -> impl Iterator<Item = &Edge> {
        self.edges.values()
    }

    pub fn ports_of(&self, node: NodeId) -> impl Iterator<Item = &Port> {
        self.nodes
            .get(&node)
            .into_iter()
            .flat_map(|n| n.inputs.iter().chain(n.outputs.iter()))
            .filter_map(|p| self.ports.get(p))
    }

    pub fn edges_of_port(&self, port: PortId) -> &[EdgeId] {
        self.port_edges.get(&port).map(Vec::as_slice).unwrap_or(&[])
    }

    /// 与节点相连的所有边(gpui-flow `get_connected_edges`)。
    pub fn connected_edges(&self, node: NodeId) -> Vec<EdgeId> {
        let mut out: Vec<EdgeId> = self
            .ports_of(node)
            .flat_map(|p| self.edges_of_port(p.id).iter().copied())
            .collect();
        out.sort();
        out.dedup();
        out
    }

    /// 上游节点(gpui-flow `get_incomers`)。
    pub fn incomers(&self, node: NodeId) -> Vec<NodeId> {
        self.neighbours(node, PortDirection::Input)
    }

    /// 下游节点(gpui-flow `get_outgoers`)。
    pub fn outgoers(&self, node: NodeId) -> Vec<NodeId> {
        self.neighbours(node, PortDirection::Output)
    }

    fn neighbours(&self, node: NodeId, dir: PortDirection) -> Vec<NodeId> {
        let mut out: Vec<NodeId> = self
            .ports_of(node)
            .filter(|p| p.direction == dir)
            .flat_map(|p| self.edges_of_port(p.id))
            .filter_map(|e| self.edges.get(e))
            .filter_map(|e| {
                let other = if dir == PortDirection::Input {
                    e.from
                } else {
                    e.to
                };
                self.ports.get(&other).map(|p| p.node)
            })
            .collect();
        out.sort();
        out.dedup();
        out
    }

    /// 边的 (源节点, 目标节点)。
    pub fn edge_nodes(&self, edge: &Edge) -> Option<(NodeId, NodeId)> {
        Some((
            self.ports.get(&edge.from)?.node,
            self.ports.get(&edge.to)?.node,
        ))
    }

    pub fn children_of(&self, parent: NodeId) -> &[NodeId] {
        self.children.get(&parent).map(Vec::as_slice).unwrap_or(&[])
    }

    /// 节点及其全部后代(先序)。
    pub fn subtree(&self, root: NodeId) -> Vec<NodeId> {
        let mut out = Vec::new();
        let mut stack = vec![root];
        while let Some(id) = stack.pop() {
            if self.nodes.contains_key(&id) {
                out.push(id);
                stack.extend(self.children_of(id).iter().rev());
            }
        }
        out
    }

    pub fn is_ancestor(&self, ancestor: NodeId, mut node: NodeId) -> bool {
        while let Some(p) = self.nodes.get(&node).and_then(|n| n.parent) {
            if p == ancestor {
                return true;
            }
            node = p;
        }
        false
    }

    /// 节点左上角的世界坐标(累加父链的局部坐标)。
    pub fn world_pos(&self, id: NodeId) -> Option<Vec2> {
        let mut node = self.nodes.get(&id)?;
        let mut pos = node.pos;
        while let Some(p) = node.parent {
            node = self.nodes.get(&p)?;
            pos = pos.plus(node.pos);
        }
        Some(pos)
    }

    pub fn world_rect(&self, id: NodeId) -> Option<Rect> {
        Some(Rect::from_origin_size(
            self.world_pos(id)?,
            self.nodes.get(&id)?.size,
        ))
    }

    /// 世界坐标换算到 `parent` 的局部坐标。
    pub fn to_local(&self, world: Vec2, parent: Option<NodeId>) -> Option<Vec2> {
        match parent {
            None => Some(world),
            Some(p) => Some(world.minus(self.world_pos(p)?)),
        }
    }

    /// 所有节点的世界包围盒(fit view 用)。
    pub fn bounds(&self) -> Option<Rect> {
        self.order
            .iter()
            .filter_map(|id| self.world_rect(*id))
            .reduce(|a, b| a.union(b))
    }

    /// 与矩形相交(`fully = false`)或被完全包含(`fully = true`)的节点,按绘制顺序。
    pub fn nodes_in_rect(&self, rect: &Rect, fully: bool) -> Vec<NodeId> {
        self.order
            .iter()
            .copied()
            .filter(|id| {
                self.world_rect(*id).is_some_and(|r| {
                    if fully {
                        rect.contains_rect(&r)
                    } else {
                        rect.intersects(&r)
                    }
                })
            })
            .collect()
    }

    /// 自顶向下命中最上层节点。
    pub fn node_at(&self, p: Vec2) -> Option<NodeId> {
        self.order
            .iter()
            .rev()
            .copied()
            .find(|id| self.world_rect(*id).is_some_and(|r| r.contains(p)))
    }

    /// 节点级拓扑序;有环时返回参与环的任一节点。
    pub fn topo_order(&self) -> Result<Vec<NodeId>, NodeId> {
        let mut indeg: HashMap<NodeId, usize> = self.order.iter().map(|id| (*id, 0)).collect();
        let mut succ: HashMap<NodeId, Vec<NodeId>> = HashMap::new();
        for e in self.edges.values() {
            if let Some((a, b)) = self.edge_nodes(e) {
                succ.entry(a).or_default().push(b);
                *indeg.entry(b).or_default() += 1;
            }
        }
        let mut queue: VecDeque<NodeId> = self
            .order
            .iter()
            .copied()
            .filter(|id| indeg[id] == 0)
            .collect();
        let mut out = Vec::with_capacity(self.order.len());
        while let Some(n) = queue.pop_front() {
            out.push(n);
            for m in succ.get(&n).into_iter().flatten() {
                let d = indeg.get_mut(m).expect("indegree entry");
                *d -= 1;
                if *d == 0 {
                    queue.push_back(*m);
                }
            }
        }
        if out.len() == self.order.len() {
            Ok(out)
        } else {
            let done: HashSet<NodeId> = out.into_iter().collect();
            Err(*self
                .order
                .iter()
                .find(|id| !done.contains(id))
                .expect("cycle member"))
        }
    }

    pub fn has_cycle(&self) -> bool {
        self.topo_order().is_err()
    }

    /// 新增 `from → to` 是否会成环(`to` 能否到达 `from`)。
    pub fn would_create_cycle(&self, from: NodeId, to: NodeId) -> bool {
        if from == to {
            return true;
        }
        let mut seen = HashSet::new();
        let mut stack = vec![to];
        while let Some(n) = stack.pop() {
            if n == from {
                return true;
            }
            if seen.insert(n) {
                stack.extend(self.outgoers(n));
            }
        }
        false
    }

    // ---------- 非历史修改(运行态 / 视图态) ----------

    /// 运行状态不进入撤销历史。
    pub fn set_status(&mut self, id: NodeId, status: NodeStatus) -> bool {
        match self.nodes.get_mut(&id) {
            Some(n) if n.status != status => {
                n.status = status;
                self.bump();
                true
            }
            _ => false,
        }
    }

    pub fn set_edge_state(&mut self, id: EdgeId, state: crate::edge::EdgeState) -> bool {
        match self.edges.get_mut(&id) {
            Some(e) if e.state != state => {
                e.state = state;
                self.bump();
                true
            }
            _ => false,
        }
    }

    /// 置顶(含子树,保证子节点仍画在父节点之上)。
    pub fn bring_to_front(&mut self, id: NodeId) {
        let tree = self.subtree(id);
        let set: HashSet<NodeId> = tree.iter().copied().collect();
        let mut moved: Vec<NodeId> = self
            .order
            .iter()
            .copied()
            .filter(|n| set.contains(n))
            .collect();
        self.order.retain(|n| !set.contains(n));
        self.order.append(&mut moved);
        self.bump();
    }

    // ---------- 底层原语(由 op 调用,保持不变量) ----------

    pub(crate) fn insert_node(
        &mut self,
        mut node: Node,
        ports: Vec<Port>,
    ) -> Result<(), GraphError> {
        if self.nodes.contains_key(&node.id) {
            return Err(GraphError::DuplicateId(node.id.0));
        }
        if let Some(p) = node.parent
            && !self.nodes.contains_key(&p)
        {
            return Err(GraphError::MissingNode(p));
        }
        for p in &ports {
            if self.ports.contains_key(&p.id) {
                return Err(GraphError::DuplicateId(p.id.0));
            }
        }
        self.reserve(node.id.0);
        node.inputs.clear();
        node.outputs.clear();
        for mut p in ports {
            self.reserve(p.id.0);
            p.node = node.id;
            match p.direction {
                PortDirection::Input => node.inputs.push(p.id),
                PortDirection::Output => node.outputs.push(p.id),
            }
            self.ports.insert(p.id, p);
        }
        if let Some(p) = node.parent {
            self.children.entry(p).or_default().push(node.id);
        }
        self.order.push(node.id);
        self.nodes.insert(node.id, node);
        self.bump();
        Ok(())
    }

    pub(crate) fn take_node(&mut self, id: NodeId) -> Result<(Node, Vec<Port>), GraphError> {
        if !self.nodes.contains_key(&id) {
            return Err(GraphError::MissingNode(id));
        }
        if !self.children_of(id).is_empty() || !self.connected_edges(id).is_empty() {
            return Err(GraphError::NodeInUse(id));
        }
        let node = self.nodes.remove(&id).expect("checked");
        let ports = node
            .inputs
            .iter()
            .chain(node.outputs.iter())
            .filter_map(|p| {
                self.port_edges.remove(p);
                self.ports.remove(p)
            })
            .collect();
        if let Some(p) = node.parent
            && let Some(list) = self.children.get_mut(&p)
        {
            list.retain(|c| *c != id);
        }
        self.children.remove(&id);
        self.order.retain(|n| *n != id);
        self.bump();
        Ok((node, ports))
    }

    pub(crate) fn insert_edge(&mut self, edge: Edge) -> Result<(), GraphError> {
        if self.edges.contains_key(&edge.id) {
            return Err(GraphError::DuplicateId(edge.id.0));
        }
        for p in [edge.from, edge.to] {
            if !self.ports.contains_key(&p) {
                return Err(GraphError::MissingPort(p));
            }
        }
        self.reserve(edge.id.0);
        self.port_edges.entry(edge.from).or_default().push(edge.id);
        self.port_edges.entry(edge.to).or_default().push(edge.id);
        self.edges.insert(edge.id, edge);
        self.bump();
        Ok(())
    }

    pub(crate) fn take_edge(&mut self, id: EdgeId) -> Result<Edge, GraphError> {
        let edge = self.edges.remove(&id).ok_or(GraphError::MissingEdge(id))?;
        for p in [edge.from, edge.to] {
            if let Some(list) = self.port_edges.get_mut(&p) {
                list.retain(|e| *e != id);
            }
        }
        self.bump();
        Ok(edge)
    }

    pub(crate) fn move_in_order(&mut self, id: NodeId, index: usize) {
        if let Some(cur) = self.order.iter().position(|n| *n == id) {
            self.order.remove(cur);
            let i = index.min(self.order.len());
            self.order.insert(i, id);
        }
    }

    pub(crate) fn node_mut(&mut self, id: NodeId) -> Result<&mut Node, GraphError> {
        self.nodes.get_mut(&id).ok_or(GraphError::MissingNode(id))
    }

    pub(crate) fn set_parent(
        &mut self,
        id: NodeId,
        parent: Option<NodeId>,
    ) -> Result<(), GraphError> {
        if let Some(p) = parent {
            if !self.nodes.contains_key(&p) {
                return Err(GraphError::MissingNode(p));
            }
            if p == id || self.is_ancestor(id, p) {
                return Err(GraphError::WouldCreateCycle {
                    parent: p,
                    child: id,
                });
            }
        }
        let old = self.node_mut(id)?.parent;
        if let Some(o) = old
            && let Some(list) = self.children.get_mut(&o)
        {
            list.retain(|c| *c != id);
        }
        if let Some(p) = parent {
            self.children.entry(p).or_default().push(id);
        }
        self.node_mut(id)?.parent = parent;
        Ok(())
    }

    // ---------- 便捷构建 ----------

    /// 创建一个节点(不进历史,适合初始化)。返回节点 ID 与 (输入端口, 输出端口)。
    pub fn add_node_with(
        &mut self,
        kind: &str,
        pos: Vec2,
        size: Size2,
        inputs: usize,
        outputs: usize,
    ) -> (NodeId, Vec<PortId>, Vec<PortId>) {
        let id = self.alloc_node_id();
        let mut ports = Vec::new();
        let mut ins = Vec::new();
        let mut outs = Vec::new();
        for _ in 0..inputs {
            let pid = self.alloc_port_id();
            ins.push(pid);
            ports.push(Port::new(pid, id, PortDirection::Input));
        }
        for _ in 0..outputs {
            let pid = self.alloc_port_id();
            outs.push(pid);
            ports.push(Port::new(pid, id, PortDirection::Output));
        }
        self.insert_node(Node::new(id, kind, pos, size), ports)
            .expect("fresh ids");
        (id, ins, outs)
    }

    /// 直接连线(不校验、不进历史,适合初始化)。
    pub fn connect(&mut self, from: PortId, to: PortId) -> Result<EdgeId, GraphError> {
        let id = self.alloc_edge_id();
        self.insert_edge(Edge::new(id, from, to))?;
        Ok(id)
    }

    // ---------- 序列化 ----------

    pub fn to_json(&self) -> serde_json::Value {
        let mut edges: Vec<Edge> = self.edges.values().cloned().collect();
        edges.sort_by_key(|e| e.id);
        let mut ports: Vec<Port> = self.ports.values().cloned().collect();
        ports.sort_by_key(|p| p.id);
        let doc = GraphDoc {
            version: crate::FORMAT_VERSION,
            next_id: self.next_id,
            nodes: self.nodes().cloned().collect(),
            ports,
            edges,
        };
        serde_json::to_value(doc).expect("graph is serialisable")
    }

    pub fn from_json(value: serde_json::Value) -> Result<Self, GraphError> {
        let doc: GraphDoc =
            serde_json::from_value(value).map_err(|e| GraphError::Format(e.to_string()))?;
        if doc.version > crate::FORMAT_VERSION {
            return Err(GraphError::Format(format!(
                "unsupported version {}",
                doc.version
            )));
        }
        let mut g = Graph::new();
        let mut ports_by_node: HashMap<NodeId, Vec<Port>> = HashMap::new();
        for p in doc.ports {
            ports_by_node.entry(p.node).or_default().push(p);
        }
        // 父节点必须先于子节点插入;文档按绘制顺序保存,子节点总在父节点之后,
        // 但为容错仍做一次按深度的稳定排序。
        let parents: HashMap<NodeId, Option<NodeId>> =
            doc.nodes.iter().map(|n| (n.id, n.parent)).collect();
        let depth = |mut id: NodeId| {
            let mut d = 0usize;
            while let Some(Some(p)) = parents.get(&id) {
                d += 1;
                id = *p;
                if d > parents.len() {
                    break;
                }
            }
            d
        };
        let mut nodes = doc.nodes;
        let order: Vec<NodeId> = nodes.iter().map(|n| n.id).collect();
        nodes.sort_by_key(|n| depth(n.id));
        for n in nodes {
            // 按文档里的端口顺序还原。
            let mut ports = ports_by_node.remove(&n.id).unwrap_or_default();
            let rank: HashMap<PortId, usize> = n
                .inputs
                .iter()
                .chain(n.outputs.iter())
                .enumerate()
                .map(|(i, p)| (*p, i))
                .collect();
            ports.sort_by_key(|p| rank.get(&p.id).copied().unwrap_or(usize::MAX));
            g.insert_node(n, ports)?;
        }
        g.order = order;
        for e in doc.edges {
            g.insert_edge(e)?;
        }
        g.next_id = g.next_id.max(doc.next_id);
        Ok(g)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn chain() -> (Graph, Vec<NodeId>) {
        let mut g = Graph::new();
        let sz = Size2::new(100.0, 40.0);
        let (a, _, ao) = g.add_node_with("a", Vec2::new(0.0, 0.0), sz, 0, 1);
        let (b, bi, bo) = g.add_node_with("b", Vec2::new(200.0, 0.0), sz, 1, 1);
        let (c, ci, _) = g.add_node_with("c", Vec2::new(400.0, 0.0), sz, 1, 0);
        g.connect(ao[0], bi[0]).unwrap();
        g.connect(bo[0], ci[0]).unwrap();
        (g, vec![a, b, c])
    }

    #[test]
    fn neighbours_and_topology() {
        let (g, n) = chain();
        assert_eq!(g.incomers(n[1]), vec![n[0]]);
        assert_eq!(g.outgoers(n[1]), vec![n[2]]);
        assert_eq!(g.connected_edges(n[1]).len(), 2);
        assert_eq!(g.topo_order().unwrap(), n);
        assert!(g.would_create_cycle(n[2], n[0]));
        assert!(!g.would_create_cycle(n[0], n[2]));
    }

    #[test]
    fn nested_world_positions() {
        let mut g = Graph::new();
        let (group, _, _) = g.add_node_with(
            "group",
            Vec2::new(100.0, 50.0),
            Size2::new(300.0, 200.0),
            0,
            0,
        );
        let (child, _, _) =
            g.add_node_with("c", Vec2::new(10.0, 20.0), Size2::new(50.0, 20.0), 0, 0);
        g.set_parent(child, Some(group)).unwrap();
        assert_eq!(g.world_pos(child), Some(Vec2::new(110.0, 70.0)));
        assert_eq!(g.children_of(group), &[child]);
        assert_eq!(
            g.set_parent(group, Some(child)),
            Err(GraphError::WouldCreateCycle {
                parent: child,
                child: group
            })
        );
        assert_eq!(g.node_at(Vec2::new(115.0, 75.0)), Some(child));
    }

    #[test]
    fn remove_requires_detached() {
        let (mut g, n) = chain();
        assert_eq!(g.take_node(n[1]).unwrap_err(), GraphError::NodeInUse(n[1]));
    }

    #[test]
    fn json_round_trip() {
        let (mut g, n) = chain();
        g.set_parent(n[2], Some(n[1])).unwrap();
        let json = g.to_json();
        let back = Graph::from_json(json.clone()).unwrap();
        assert_eq!(back.to_json(), json);
        assert_eq!(back.topo_order().unwrap(), n);
        assert_eq!(back.children_of(n[1]), &[n[2]]);
    }

    #[test]
    fn rect_queries() {
        let (g, n) = chain();
        let r = Rect::from_corners(Vec2::new(-10.0, -10.0), Vec2::new(250.0, 50.0));
        assert_eq!(g.nodes_in_rect(&r, false), vec![n[0], n[1]]);
        assert_eq!(g.nodes_in_rect(&r, true), vec![n[0]]);
        assert_eq!(g.bounds().unwrap().max, Vec2::new(500.0, 40.0));
    }
}