arc-flow 0.4.0

GPUI node & workflow editor canvas built on arc-flow-core, arc-tokens, arc-motion, and arc-ui.
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
//! F6 Arc 动效(方案 `docs/flow/arc-flow-plan.md` 第 7 节)。本地设计。
//!
//! 画布直接用 canvas 绘制边与端口,没法挂 GPUI 的 `with_transition`,所以这里把每个场景
//! 做成以时间为输入的纯状态机:画布每帧用 `motion_now` 取样,有动画在跑就请求下一帧。
//! 时长、缓动、弹簧全部取自 `arc-tokens`,求解器来自 `arc-motion`。
//!
//! | 场景 | 实现 |
//! |---|---|
//! | 拖拽松手落位 | 拖拽中节点跟手(偏移 = 指针位置 − 吸附位置,不做动画),松手后偏移以 `spring.responsive` 归零 |
//! | 新增 / 删除节点 | 缩放 0.96→1 + 透明度,`ease.enter` / `duration.standard`;删除留残影,`ease.exit` / `duration.exit` |
//! | 新建连线 | 按弧长绘入 0→1,`ease.standard` / `duration.standard` |
//! | 连线吸附 | 目标端口以 `spring.snappy` 放大,并有一圈光晕在 `duration.considered` 内淡出 |
//! | 非法连接 | 目标端口水平抖动,`duration.fast` 关键帧 |
//! | 运行中边 | 虚线沿边流动(自行切段,见 `core::dash_polyline`) |
//! | 执行高亮 | Running 节点边框呼吸(`NodeRenderCtx::pulse`) |
//! | 适配视图 / 键盘与按钮缩放 | 视口以 `spring.smooth` 过渡:中心线性插值、缩放按对数插值 |
//!
//! reduced motion:位移、视口、绘入、抖动、放大全部瞬时;进出场只保留 `duration.instant` 的透明度;
//! 虚线不流动,边框不呼吸。

use std::collections::HashMap;
use std::f64::consts::TAU;

use arc_flow_core::{EdgeId, Node, NodeId, PortId, Rect, Vec2, Viewport};
use arc_motion::{CubicBezier, SpringSolver};
use arc_tokens::{ArcMotionTokens, SpringSpec};

use crate::metrics::*;

const T: ArcMotionTokens = ArcMotionTokens::DEFAULT;

/// 节点进场起始缩放、退场结束缩放。
pub const NODE_ENTER_SCALE: f32 = 0.96;

#[derive(Clone, Copy, Debug)]
struct Tween {
    start: f64,
    dur: f64,
    ease: CubicBezier,
}

impl Tween {
    fn new(start: f64, dur: std::time::Duration, ease: arc_tokens::CubicBezierSpec) -> Self {
        Self {
            start,
            dur: dur.as_secs_f64(),
            ease: ease.into(),
        }
    }

    fn linear_t(&self, now: f64) -> f32 {
        if self.dur <= 0.0 {
            return 1.0;
        }
        ((now - self.start) / self.dur).clamp(0.0, 1.0) as f32
    }

    fn progress(&self, now: f64) -> f32 {
        self.ease.sample(self.linear_t(now))
    }

    fn done(&self, now: f64) -> bool {
        now - self.start >= self.dur
    }
}

#[derive(Clone, Copy, Debug)]
struct Spring {
    solver: SpringSolver,
    start: f64,
}

impl Spring {
    fn new(spec: SpringSpec, from: f32, to: f32, now: f64) -> Self {
        Self {
            solver: SpringSolver::new(spec, f64::from(from), f64::from(to), 0.0),
            start: now,
        }
    }

    fn sample(&self, now: f64) -> (f32, bool) {
        let s = self.solver.sample(now - self.start);
        (s.value, s.settled)
    }
}

#[derive(Clone, Copy, Debug)]
struct Spring2 {
    x: Spring,
    y: Spring,
}

impl Spring2 {
    fn sample(&self, now: f64) -> (Vec2, bool) {
        let (x, sx) = self.x.sample(now);
        let (y, sy) = self.y.sample(now);
        (Vec2::new(x, y), sx && sy)
    }
}

#[derive(Clone, Copy, Debug)]
struct ViewAnim {
    from_center: Vec2,
    from_zoom: f32,
    to_center: Vec2,
    to_zoom: f32,
    spring: Spring,
}

/// 删除后仍在淡出的节点。
#[derive(Clone, Debug)]
pub struct Ghost {
    pub node: Node,
    /// 删除时的世界矩形。
    pub rect: Rect,
    tween: Tween,
}

/// 进出场的取样:缩放与不透明度。
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Appear {
    pub scale: f32,
    pub opacity: f32,
}

impl Appear {
    pub const FULL: Self = Self {
        scale: 1.0,
        opacity: 1.0,
    };
}

#[derive(Debug, Default)]
pub struct FlowMotion {
    reduced: bool,
    live: HashMap<NodeId, Vec2>,
    settle: HashMap<NodeId, Spring2>,
    enter: HashMap<NodeId, Tween>,
    ghosts: Vec<Ghost>,
    draw_in: HashMap<EdgeId, Tween>,
    shake: Option<(PortId, Tween)>,
    target: Option<(PortId, Spring, Tween)>,
    view: Option<ViewAnim>,
}

impl FlowMotion {
    pub fn set_reduced(&mut self, reduced: bool) {
        self.reduced = reduced;
    }

    pub fn reduced(&self) -> bool {
        self.reduced
    }

    // ---------- 拖拽落位 ----------

    /// 拖拽中:节点显示位置相对模型位置的偏移(跟手,无动画)。
    pub fn set_live_offset(&mut self, id: NodeId, offset: Vec2) {
        if offset == Vec2::ZERO {
            self.live.remove(&id);
        } else {
            self.live.insert(id, offset);
            self.settle.remove(&id);
        }
    }

    /// 松手:把拖拽中的偏移交给弹簧归零。
    pub fn release(&mut self, now: f64) {
        let live = std::mem::take(&mut self.live);
        if self.reduced {
            return;
        }
        let spec = T.spring.responsive;
        for (id, off) in live {
            self.settle.insert(
                id,
                Spring2 {
                    x: Spring::new(spec, off.x, 0.0, now),
                    y: Spring::new(spec, off.y, 0.0, now),
                },
            );
        }
    }

    /// 取消拖拽:偏移立即清零。
    pub fn cancel_live(&mut self) {
        self.live.clear();
    }

    /// 节点自身(不含祖先)的显示偏移。
    pub fn own_offset(&self, id: NodeId, now: f64) -> Vec2 {
        if let Some(v) = self.live.get(&id) {
            return *v;
        }
        self.settle.get(&id).map_or(Vec2::ZERO, |s| s.sample(now).0)
    }

    pub fn has_offsets(&self) -> bool {
        !self.live.is_empty() || !self.settle.is_empty()
    }

    // ---------- 进出场 ----------

    pub fn node_entered(&mut self, id: NodeId, now: f64) {
        let tw = if self.reduced {
            Tween::new(now, T.duration.instant, T.ease.standard)
        } else {
            Tween::new(now, T.duration.standard, T.ease.enter)
        };
        self.enter.insert(id, tw);
    }

    pub fn enter_sample(&self, id: NodeId, now: f64) -> Appear {
        let Some(tw) = self.enter.get(&id) else {
            return Appear::FULL;
        };
        let p = tw.progress(now);
        Appear {
            scale: if self.reduced {
                1.0
            } else {
                NODE_ENTER_SCALE + (1.0 - NODE_ENTER_SCALE) * p
            },
            opacity: p,
        }
    }

    pub fn node_removed(&mut self, node: Node, rect: Rect, now: f64) {
        self.enter.remove(&node.id);
        self.settle.remove(&node.id);
        let tween = if self.reduced {
            Tween::new(now, T.duration.instant, T.ease.standard)
        } else {
            Tween::new(now, T.duration.exit, T.ease.exit)
        };
        self.ghosts.push(Ghost { node, rect, tween });
    }

    /// 正在淡出的节点及其取样。
    pub fn ghosts(&self, now: f64) -> impl Iterator<Item = (&Ghost, Appear)> {
        let reduced = self.reduced;
        self.ghosts.iter().map(move |g| {
            let p = g.tween.progress(now);
            let a = Appear {
                scale: if reduced {
                    1.0
                } else {
                    1.0 - (1.0 - NODE_ENTER_SCALE) * p
                },
                opacity: 1.0 - p,
            };
            (g, a)
        })
    }

    /// 撤销删除时,节点回来就不再画它的残影。
    pub fn drop_ghost(&mut self, id: NodeId) {
        self.ghosts.retain(|g| g.node.id != id);
    }

    // ---------- 连线 ----------

    pub fn edge_added(&mut self, id: EdgeId, now: f64) {
        if !self.reduced {
            self.draw_in
                .insert(id, Tween::new(now, T.duration.standard, T.ease.standard));
        }
    }

    /// 绘入比例 0..=1。
    pub fn draw_progress(&self, id: EdgeId, now: f64) -> f32 {
        self.draw_in.get(&id).map_or(1.0, |tw| tw.progress(now))
    }

    pub fn reject(&mut self, port: PortId, now: f64) {
        if !self.reduced {
            self.shake = Some((port, Tween::new(now, T.duration.fast, T.ease.standard)));
        }
    }

    /// 非法目标端口的水平抖动(屏幕 px):0 → −A → A → −A/2 → A/2 → 0 的线性关键帧。
    pub fn shake(&self, now: f64) -> Option<(PortId, f32)> {
        const KEYS: [f32; 6] = [0.0, -1.0, 1.0, -0.5, 0.5, 0.0];
        let (port, tw) = self.shake?;
        if tw.done(now) {
            return None;
        }
        let t = tw.linear_t(now) * (KEYS.len() - 1) as f32;
        let i = (t.floor() as usize).min(KEYS.len() - 2);
        let f = t - i as f32;
        let k = KEYS[i] + (KEYS[i + 1] - KEYS[i]) * f;
        Some((port, k * SHAKE_AMPLITUDE))
    }

    /// 连线草稿吸附到了新的目标端口。
    pub fn target_changed(&mut self, port: Option<PortId>, now: f64) {
        if port == self.target.as_ref().map(|t| t.0) {
            return;
        }
        self.target = port.map(|p| {
            (
                p,
                Spring::new(T.spring.snappy, 1.0, PORT_TARGET_SCALE, now),
                Tween::new(now, T.duration.considered, T.ease.standard),
            )
        });
    }

    /// 目标端口的放大倍数与光晕进度(0 → 1 淡出)。
    pub fn target_sample(&self, port: PortId, now: f64) -> (f32, Option<f32>) {
        match &self.target {
            Some((p, spring, glow)) if *p == port && !self.reduced => {
                let g = (!glow.done(now)).then(|| glow.progress(now));
                (spring.sample(now).0, g)
            }
            _ => (PORT_TARGET_SCALE, None),
        }
    }

    // ---------- 视口 ----------

    /// 从 `from` 平滑过渡到 `to`;`center` 为视图中心(屏幕坐标)。返回 false 表示应立即跳转。
    pub fn animate_view(&mut self, from: &Viewport, to: &Viewport, center: Vec2, now: f64) -> bool {
        if self.reduced {
            self.view = None;
            return false;
        }
        self.view = Some(ViewAnim {
            from_center: from.screen_to_world(center),
            from_zoom: from.zoom,
            to_center: to.screen_to_world(center),
            to_zoom: to.zoom,
            spring: Spring::new(T.spring.smooth, 0.0, 1.0, now),
        });
        true
    }

    pub fn cancel_view(&mut self) {
        self.view = None;
    }

    pub fn view_animating(&self) -> bool {
        self.view.is_some()
    }

    /// 视口取样,结束时返回 `(终点, true)`。
    pub fn view_sample(&self, base: &Viewport, center: Vec2, now: f64) -> Option<(Viewport, bool)> {
        let a = self.view?;
        let (p, settled) = a.spring.sample(now);
        let p = if settled { 1.0 } else { p };
        let zoom = (a.from_zoom.ln() + (a.to_zoom.ln() - a.from_zoom.ln()) * p).exp();
        let world = a.from_center.lerp(a.to_center, p);
        let mut vp = *base;
        vp.zoom = zoom;
        vp.offset = center.minus(world.scale(zoom));
        Some((vp, settled))
    }

    // ---------- 持续动画 ----------

    /// 运行中边的虚线相位(屏幕 px)。
    pub fn dash_phase(&self, now: f64) -> f32 {
        if self.reduced {
            0.0
        } else {
            let period = f64::from(ACTIVE_DASH[0] + ACTIVE_DASH[1]);
            (now * f64::from(DASH_FLOW_SPEED)).rem_euclid(period) as f32
        }
    }

    /// Running 节点的边框呼吸 0..=1;reduced motion 下恒为 1(不呼吸)。
    pub fn pulse(&self, now: f64) -> f32 {
        if self.reduced {
            1.0
        } else {
            (0.5 - 0.5 * (now * TAU / f64::from(RUNNING_PULSE_PERIOD)).cos()) as f32
        }
    }

    // ---------- 帧 ----------

    /// 清理已结束的动画;返回是否仍有一次性动画在跑(需要下一帧)。
    pub fn tick(&mut self, now: f64) -> bool {
        self.settle.retain(|_, s| !s.sample(now).1);
        self.enter.retain(|_, tw| !tw.done(now));
        self.ghosts.retain(|g| !g.tween.done(now));
        self.draw_in.retain(|_, tw| !tw.done(now));
        if self.shake.is_some_and(|(_, tw)| tw.done(now)) {
            self.shake = None;
        }
        let target_live = self
            .target
            .as_ref()
            .is_some_and(|(_, s, g)| !s.sample(now).1 || !g.done(now));
        !self.settle.is_empty()
            || !self.enter.is_empty()
            || !self.ghosts.is_empty()
            || !self.draw_in.is_empty()
            || self.shake.is_some()
            || self.view.is_some()
            || (target_live && !self.reduced)
    }

    pub fn finish_view(&mut self) {
        self.view = None;
    }
}

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

    const N: NodeId = NodeId(1);

    #[test]
    fn release_springs_offset_back_to_zero() {
        let mut m = FlowMotion::default();
        m.set_live_offset(N, Vec2::new(4.0, -3.0));
        assert_eq!(m.own_offset(N, 0.0), Vec2::new(4.0, -3.0));
        m.release(10.0);
        assert_eq!(m.own_offset(N, 10.0), Vec2::new(4.0, -3.0));
        let mid = m.own_offset(N, 10.05);
        assert!(mid.x.abs() < 4.0 && mid.x.abs() > 0.0, "{mid:?}");
        assert!(m.tick(10.05));
        assert!(!m.tick(12.0));
        assert_eq!(m.own_offset(N, 12.0), Vec2::ZERO);
    }

    #[test]
    fn reduced_motion_makes_moves_instant_and_keeps_fades_short() {
        let mut m = FlowMotion::default();
        m.set_reduced(true);
        m.set_live_offset(N, Vec2::new(4.0, 0.0));
        m.release(0.0);
        assert_eq!(m.own_offset(N, 0.0), Vec2::ZERO);
        m.node_entered(N, 0.0);
        let a = m.enter_sample(N, 0.06);
        assert_eq!(a.scale, 1.0);
        assert!(a.opacity > 0.0 && a.opacity < 1.0);
        assert_eq!(m.enter_sample(N, 0.13), Appear::FULL);
        m.edge_added(EdgeId(1), 0.0);
        assert_eq!(m.draw_progress(EdgeId(1), 0.0), 1.0);
        m.reject(PortId(1), 0.0);
        assert!(m.shake(0.05).is_none());
        assert_eq!(m.dash_phase(3.0), 0.0);
        assert_eq!(m.pulse(0.3), 1.0);
        let vp = Viewport::default();
        let mut to = vp;
        to.zoom = 2.0;
        assert!(!m.animate_view(&vp, &to, Vec2::new(400.0, 300.0), 0.0));
    }

    #[test]
    fn enter_exit_draw_and_shake_follow_tokens() {
        let mut m = FlowMotion::default();
        m.node_entered(N, 0.0);
        let start = m.enter_sample(N, 0.0);
        assert_eq!(start.scale, NODE_ENTER_SCALE);
        assert_eq!(start.opacity, 0.0);
        assert_eq!(m.enter_sample(N, 0.24), Appear::FULL);

        let node = Node::new(NodeId(2), "x", Vec2::ZERO, Size2::new(10.0, 10.0));
        m.node_removed(node, Rect::default(), 0.0);
        let (_, a) = m.ghosts(0.18).next().unwrap();
        assert_eq!(a.opacity, 0.0);
        assert!(m.tick(0.1));
        m.tick(0.2);
        assert_eq!(m.ghosts(0.2).count(), 0);

        m.edge_added(EdgeId(3), 1.0);
        assert_eq!(m.draw_progress(EdgeId(3), 1.0), 0.0);
        let half = m.draw_progress(EdgeId(3), 1.12);
        assert!(half > 0.5 && half < 1.0, "standard 缓动前快后慢:{half}");
        assert_eq!(m.draw_progress(EdgeId(3), 1.24), 1.0);

        m.reject(PortId(9), 2.0);
        let (p, dx) = m.shake(2.0 + 0.16 * 0.2).unwrap();
        assert_eq!(p, PortId(9));
        assert!(
            (dx + SHAKE_AMPLITUDE).abs() < 1e-3,
            "第一帧关键帧在 −A:{dx}"
        );
        assert!(m.shake(2.2).is_none());
    }

    #[test]
    fn view_transition_interpolates_centre_and_log_zoom() {
        let mut m = FlowMotion::default();
        let center = Vec2::new(400.0, 300.0);
        let from = Viewport::default();
        let mut to = from;
        to.zoom = 4.0;
        to.offset = center.minus(Vec2::new(1000.0, 0.0).scale(4.0));
        assert!(m.animate_view(&from, &to, center, 0.0));
        let (start, _) = m.view_sample(&from, center, 0.0).unwrap();
        assert!((start.zoom - 1.0).abs() < 1e-4);
        let (mid, done) = m.view_sample(&from, center, 0.1).unwrap();
        assert!(!done && mid.zoom > 1.0 && mid.zoom < 4.0);
        let (end, done) = m.view_sample(&from, center, 2.0).unwrap();
        assert!(done);
        assert!((end.zoom - 4.0).abs() < 1e-4);
        assert!(end.screen_to_world(center).distance(Vec2::new(1000.0, 0.0)) < 1e-2);
    }

    #[test]
    fn dash_phase_advances_and_wraps() {
        let m = FlowMotion::default();
        let period = ACTIVE_DASH[0] + ACTIVE_DASH[1];
        let a = m.dash_phase(0.1);
        assert!((a - DASH_FLOW_SPEED * 0.1).abs() < 1e-3);
        let b = m.dash_phase(f64::from(period / DASH_FLOW_SPEED) + 0.1);
        assert!((a - b).abs() < 1e-3);
        assert!(m.pulse(0.0) < 1e-6);
        assert!((m.pulse(f64::from(RUNNING_PULSE_PERIOD) / 2.0) - 1.0).abs() < 1e-6);
    }
}