Skip to main content

mgui_core/
reactive.rs

1//! 响应式系统 —— 原 mgui-reactive crate,已合入 mgui-core
2//!
3//! 设计文档 § 7 + § 22:
4//! - `Signal<T>` 细粒度可观察值
5//! - 依赖追踪:thread_local 记录"当前正在 build 的 Element",
6//!   `Signal::get()` 时把当前 element 注册为该 signal 的订阅者
7//! - `Signal::set()` 时把订阅者标记为 dirty
8//! - 主循环把 dirty 集合取出,rebuild 这些 element
9//!
10//! 阶段 4-A7 追加:
11//! - `Memo<T>` 惰性派生值:依赖自动收集,上游变化 → stale → 下次 get 重算
12//! - `Effect` 自动追踪副作用:创建即运行一次收集依赖,依赖 signal 变化时重跑
13//! - `batch(f)` 批量更新:batch 内的 set 合并通知,退出时 dirty/effect 一次 flush
14//! - `untracked(f)` 无追踪读取:块内 `Signal::get()` 不建立订阅
15//!
16//! 范围限定:
17//! - 假定单线程 UI(不跨线程)
18//! - Effect 重跑不清除旧依赖(增量式)
19//! - Memo 循环依赖:重算中再次 get 自身 → panic
20
21use std::cell::{Cell, RefCell};
22use std::collections::{HashMap, HashSet};
23use std::rc::Rc;
24
25#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
26pub struct SubscriberId(pub u64);
27
28#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
29pub struct SignalId(pub u64);
30
31/// 全局响应式状态(thread_local,只在 UI 线程访问)
32#[derive(Default)]
33struct ReactiveState {
34    /// 订阅者栈(栈式 — Memo::get 嵌套在 element build 内)
35    /// 每项 = (订阅者, 本次运行 generation)。Effect/Memo 每次重跑 generation 自增,
36    /// 旧的依赖在下一次通知/重跑时被剔除(修复条件分支依赖残留)。
37    subscriber_stack: Vec<(SubscriberId, u64)>,
38    /// 被标记为 dirty 的订阅者
39    dirty: HashSet<SubscriberId>,
40    /// 下一个 SubscriberId
41    next_subscriber_id: u64,
42    /// 下一个 SignalId
43    next_signal_id: u64,
44    /// subscriber 失效代数:deactivate/remount 后自增,通知时按代数剔除陈旧订阅。
45    /// 只记录被失效过的 id(正常订阅者缺省为 0)。
46    subscriber_epoch: HashMap<SubscriberId, u64>,
47    /// 下一个失效代数
48    next_subscriber_epoch: u64,
49    /// Effect/Memo 当前依赖 generation(每次重跑自增)。element subscriber 缺省 0。
50    subscriber_generation: HashMap<SubscriberId, u64>,
51    /// 下一个依赖 generation
52    next_subscriber_generation: u64,
53    /// element subscriber 所属窗口/树的 reactive scope。
54    /// drain 时只消费本 scope 的 dirty,避免多窗口互相吞掉更新。
55    subscriber_scope: HashMap<SubscriberId, u64>,
56    /// batch 深度(>0 = 正在 batch)
57    batch_depth: usize,
58    /// batch 期间暂存的 dirty(退出时一次性并入 dirty)
59    pending_dirty: HashSet<SubscriberId>,
60    /// memo 注册表:SubscriberId → memo core
61    memo_registry: HashMap<SubscriberId, Rc<MemoCore>>,
62    /// effect 注册表:SubscriberId → effect core
63    effect_registry: HashMap<SubscriberId, Rc<EffectCore>>,
64    /// batch 期间暂存的待重跑 effect
65    pending_effects: Vec<Rc<EffectCore>>,
66}
67
68thread_local! {
69    static REACTIVE: RefCell<ReactiveState> = RefCell::new(ReactiveState::default());
70    /// untracked 深度(>0 = 当前读取不建立依赖)
71    static TRACKING_PAUSED: Cell<usize> = const { Cell::new(0) };
72}
73
74/// 进入"订阅者"上下文
75pub fn enter_subscriber(sub_id: SubscriberId) {
76    let generation = subscriber_generation(sub_id);
77    enter_subscriber_generation(sub_id, generation);
78}
79
80fn enter_subscriber_generation(sub_id: SubscriberId, generation: u64) {
81    REACTIVE.with(|s| s.borrow_mut().subscriber_stack.push((sub_id, generation)));
82}
83
84/// 退出"订阅者"上下文(回到外层订阅者,若有)
85pub fn exit_subscriber() {
86    REACTIVE.with(|s| {
87        s.borrow_mut().subscriber_stack.pop();
88    });
89}
90
91/// RAII 订阅者作用域:compute/effect 内部 panic 时也能弹栈,
92/// 否则后续所有 `Signal::get` 都会挂到已失败的订阅者上。
93struct SubscriberScope;
94
95impl SubscriberScope {
96    fn enter(id: SubscriberId) -> Self {
97        enter_subscriber(id);
98        Self
99    }
100
101    /// Effect/Memo 每次重跑使用新的 generation:旧依赖在下一次通知时被剔除。
102    fn enter_generation(id: SubscriberId, generation: u64) -> Self {
103        enter_subscriber_generation(id, generation);
104        Self
105    }
106}
107
108impl Drop for SubscriberScope {
109    fn drop(&mut self) {
110        exit_subscriber();
111    }
112}
113
114/// 在指定订阅者上下文中执行 `f`。
115///
116/// Element 树在 `State::build` / `Widget::children` 期间用它把 `Signal::get`
117/// 的依赖归属到当前 element;panic 时由 RAII 保证弹栈。
118pub fn with_subscriber<T>(id: SubscriberId, f: impl FnOnce() -> T) -> T {
119    let _scope = SubscriberScope::enter(id);
120    f()
121}
122
123/// 当前订阅者代数(未失效 = 0)
124fn subscriber_epoch(id: SubscriberId) -> u64 {
125    REACTIVE.with(|s| s.borrow().subscriber_epoch.get(&id).copied().unwrap_or(0))
126}
127
128/// 当前 Effect/Memo 依赖 generation(element 缺省 0)
129fn subscriber_generation(id: SubscriberId) -> u64 {
130    REACTIVE.with(|s| s.borrow().subscriber_generation.get(&id).copied().unwrap_or(0))
131}
132
133/// 为 Effect/Memo 分配新的依赖 generation
134fn bump_subscriber_generation(id: SubscriberId) -> u64 {
135    REACTIVE.with(|s| {
136        let mut s = s.borrow_mut();
137        let next = s.next_subscriber_generation.wrapping_add(1);
138        s.next_subscriber_generation = next;
139        s.subscriber_generation.insert(id, next);
140        next
141    })
142}
143
144/// 当前栈顶订阅者的 generation(element 为 0)
145fn current_generation() -> u64 {
146    REACTIVE.with(|s| s.borrow().subscriber_stack.last().map(|(_, generation)| *generation).unwrap_or(0))
147}
148
149/// 使订阅者失效:deactivate / remount 后调用。
150///
151/// 不直接遍历所有 Signal 删除订阅(框架无法枚举 Signal),而是在下一次
152/// `Signal::set/update` 通知时按代数剔除陈旧项;这样既避免长会话内存增长,
153/// 也避免池复用后的旧依赖误触发新 element。
154pub(crate) fn invalidate_subscriber(id: SubscriberId) {
155    REACTIVE.with(|s| {
156        let mut s = s.borrow_mut();
157        let next = s.next_subscriber_epoch.wrapping_add(1);
158        s.next_subscriber_epoch = next;
159        s.subscriber_epoch.insert(id, next);
160    });
161}
162
163/// 取走当前 dirty 集合(兼容/测试用;ElementTree 主循环请用 `take_dirty_for_scope`)
164pub fn take_dirty() -> HashSet<SubscriberId> {
165    REACTIVE.with(|s| std::mem::take(&mut s.borrow_mut().dirty))
166}
167
168/// 登记 element subscriber 所属的树/窗口 scope。
169pub(crate) fn register_subscriber_scope(id: SubscriberId, scope: u64) {
170    REACTIVE.with(|s| {
171        s.borrow_mut().subscriber_scope.insert(id, scope);
172    });
173}
174
175/// 释放 scope(元素卸载/整树 remount)。未登记的 subscriber 视为全局(scope 0)。
176pub(crate) fn release_subscriber_scope(id: SubscriberId) {
177    REACTIVE.with(|s| {
178        let mut state = s.borrow_mut();
179        state.subscriber_scope.remove(&id);
180        // 已卸载 element 的 pending dirty 直接丢弃,避免被其他窗口消费后
181        // 产生无意义的重建计数。
182        state.dirty.remove(&id);
183        state.pending_dirty.remove(&id);
184    });
185}
186
187/// 只取走属于 `scope`(或全局 scope 0)的 dirty,其他树的 id 留在集合里。
188///
189/// 多窗口共用 UI 线程时,`Signal::set` 会把所有窗口的 subscriber 放进同一个
190/// 全局 dirty set;若任一窗口 `take_dirty()` 全取,其他窗口的 element dirty
191/// 就被吞掉。这里按 scope 分区。
192pub(crate) fn take_dirty_for_scope(scope: u64) -> HashSet<SubscriberId> {
193    REACTIVE.with(|s| {
194        let mut state = s.borrow_mut();
195        let dirty = std::mem::take(&mut state.dirty);
196        let mut mine = HashSet::new();
197        let mut keep = HashSet::new();
198        for id in dirty {
199            let owner = state.subscriber_scope.get(&id).copied().unwrap_or(0);
200            if owner == 0 || owner == scope {
201                mine.insert(id);
202            } else {
203                keep.insert(id);
204            }
205        }
206        state.dirty = keep;
207        mine
208    })
209}
210
211/// DT-02:只读 peek 当前属于 `scope` 的 dirty subscriber(不 drain)。
212pub fn peek_dirty_for_scope(scope: u64) -> HashSet<SubscriberId> {
213    REACTIVE.with(|s| {
214        let state = s.borrow();
215        let mut mine = HashSet::new();
216        for id in state.dirty.iter().copied() {
217            let owner = state.subscriber_scope.get(&id).copied().unwrap_or(0);
218            if owner == 0 || owner == scope {
219                mine.insert(id);
220            }
221        }
222        mine
223    })
224}
225
226thread_local! {
227    /// 自上次取走后有任意 Signal::set/update 发生(与订阅无关)。
228    /// 宿主(如 showcase)以 peek 读 Signal 进 Widget,不建立订阅 —— 值变化后
229    /// dirty 集合为空,需要这个标记让 drain 返回非零,宿主据此触发 rebuild。
230    static ANY_SIGNAL_SET: Cell<bool> = const { Cell::new(false) };
231    /// peek 信号变化的全局 epoch:每棵 ElementTree 各自记录已消费版本,
232    /// 避免多窗口共用 bool 时"一个窗口消费后其他窗口漏掉全树重建"。
233    static ANY_SIGNAL_EPOCH: Cell<u64> = const { Cell::new(0) };
234    /// DT-02:Signal trace 开关镜像。关闭时入口只读它,不拿 SIG_TRACE 锁。
235    static SIGNAL_TRACE_ENABLED: Cell<bool> = const { Cell::new(false) };
236}
237
238/// DT-02:Signal trace 线程局部实例(复用 DevtoolsTrace 基础设施,CAP=256)。
239/// 与 Reactive 状态本身同线程口径;进程全局会让测试线程互相污染开关。
240fn with_signal_trace<R>(f: impl FnOnce(&crate::devtools_trace::DevtoolsTrace<SignalTraceEntry>) -> R) -> R {
241    use std::sync::Mutex;
242    thread_local! {
243        static SIG_TRACE: Mutex<crate::devtools_trace::DevtoolsTrace<SignalTraceEntry>> =
244            Mutex::new(crate::devtools_trace::DevtoolsTrace::new(256));
245    }
246    SIG_TRACE.with(|t| {
247        let guard = t.lock().unwrap_or_else(|e| e.into_inner());
248        f(&guard)
249    })
250}
251
252/// 自上次取走后有任意 Signal::set/update 发生(取出即复位)
253pub fn take_any_signal_set() -> bool {
254    ANY_SIGNAL_SET.with(|c| c.replace(false))
255}
256
257/// 当前 peek 信号变化 epoch(只增不减)
258pub fn any_signal_epoch() -> u64 {
259    ANY_SIGNAL_EPOCH.with(|c| c.get())
260}
261
262/// 标记"有 Signal 值已变化"(batch 内也置位:值已变,宿主下帧 rebuild 即可)
263fn mark_any_signal_set() {
264    ANY_SIGNAL_SET.with(|c| c.set(true));
265    ANY_SIGNAL_EPOCH.with(|c| c.set(c.get().wrapping_add(1)));
266}
267
268// ============================================================
269// DT-02:Signal trace API
270// ============================================================
271
272/// DT-02:一次 Signal.set/update 的追踪条目
273#[derive(Clone, Debug)]
274pub struct SignalTraceEntry {
275    pub signal_id: SignalId,
276    /// 这次变化直接影响到的 subscriber(epoch/generation retain 后剩余)
277    pub subscribers: Vec<SubscriberId>,
278    /// 是否被 peek() 读过(→ 触发宿主级全树 rebuild)
279    pub peeked: bool,
280    /// 自进程启动的毫秒数
281    pub timestamp_ms: u64,
282}
283
284/// DT-02:开启/关闭 Signal trace 采集。默认关闭(零开销)。
285pub fn set_signal_trace_enabled(on: bool) {
286    SIGNAL_TRACE_ENABLED.with(|c| c.set(on));
287    with_signal_trace(|t| t.set_enabled(on));
288}
289
290/// DT-02:是否正在采集 Signal trace。只读 thread-local 镜像,不拿锁。
291pub fn signal_trace_enabled() -> bool {
292    SIGNAL_TRACE_ENABLED.with(|c| c.get())
293}
294
295/// DT-02:追加一次 Signal 触发事件(trace 关闭时立即返回,零开销)。
296fn push_signal_trace(signal_id: SignalId, subscribers: &[SubscriberId], peeked: bool) {
297    if !signal_trace_enabled() {
298        return;
299    }
300    use crate::devtools_trace::now_ms;
301    with_signal_trace(|t| {
302        // 关闭时必须先返回,避免 to_vec / now_ms 仍然发生。
303        if !t.enabled() {
304            return;
305        }
306        t.push(SignalTraceEntry { signal_id, subscribers: subscribers.to_vec(), peeked, timestamp_ms: now_ms() })
307    });
308}
309
310/// DT-02:取最近 N 条 Signal trace(不 drain,可重复调用)。关闭时返回空,不拿锁。
311pub fn peek_signal_trace(max: usize) -> Vec<SignalTraceEntry> {
312    if !signal_trace_enabled() {
313        return Vec::new();
314    }
315    with_signal_trace(|t| {
316        if !t.enabled() {
317            return Vec::new();
318        }
319        t.peek(max)
320    })
321}
322
323/// DT-02:清空 Signal trace(切换窗口会话时)。
324pub fn clear_signal_trace() {
325    with_signal_trace(|t| t.clear());
326}
327
328/// 标记某个 subscriber 为 dirty
329pub fn mark_dirty(sub_id: SubscriberId) {
330    REACTIVE.with(|s| {
331        let mut s = s.borrow_mut();
332        if s.batch_depth > 0 {
333            s.pending_dirty.insert(sub_id);
334        } else {
335            s.dirty.insert(sub_id);
336        }
337    });
338}
339
340/// 分配新的 SubscriberId
341pub fn new_subscriber_id() -> SubscriberId {
342    REACTIVE.with(|s| {
343        let mut s = s.borrow_mut();
344        let id = SubscriberId(s.next_subscriber_id);
345        s.next_subscriber_id += 1;
346        id
347    })
348}
349
350/// 分配新的 SignalId
351pub fn new_signal_id() -> SignalId {
352    REACTIVE.with(|s| {
353        let mut s = s.borrow_mut();
354        let id = SignalId(s.next_signal_id);
355        s.next_signal_id += 1;
356        id
357    })
358}
359
360/// 当前订阅者(内部用)
361fn current_subscriber() -> Option<SubscriberId> {
362    REACTIVE.with(|s| s.borrow().subscriber_stack.last().map(|(id, _)| *id))
363}
364
365/// 追踪是否启用(untracked 块内为 false)
366fn tracking_enabled() -> bool {
367    TRACKING_PAUSED.with(|c| c.get() == 0)
368}
369
370/// 在 `f` 内的 `Signal::get()` 不建立依赖订阅
371pub fn untracked<T>(f: impl FnOnce() -> T) -> T {
372    struct TrackingGuard;
373    impl Drop for TrackingGuard {
374        fn drop(&mut self) {
375            TRACKING_PAUSED.with(|c| c.set(c.get().saturating_sub(1)));
376        }
377    }
378    TRACKING_PAUSED.with(|c| c.set(c.get() + 1));
379    let _guard = TrackingGuard;
380    f()
381}
382
383/// 批量更新。batch 内的 `Signal::set` 不立即通知订阅者,
384/// 退出时把累积的 dirty / effect 重跑一次性 flush。
385pub fn batch<T>(f: impl FnOnce() -> T) -> T {
386    struct BatchGuard {
387        completed: bool,
388    }
389    impl Drop for BatchGuard {
390        fn drop(&mut self) {
391            let depth = REACTIVE.with(|s| {
392                let mut s = s.borrow_mut();
393                s.batch_depth = s.batch_depth.saturating_sub(1);
394                s.batch_depth
395            });
396            if depth == 0 {
397                REACTIVE.with(|s| {
398                    let mut s = s.borrow_mut();
399                    let pending = std::mem::take(&mut s.pending_dirty);
400                    s.dirty.extend(pending);
401                    if !self.completed {
402                        // 块内 panic:不在这里跑 effect(可能二次 panic)
403                        s.pending_effects.clear();
404                    }
405                });
406            }
407        }
408    }
409
410    REACTIVE.with(|s| s.borrow_mut().batch_depth += 1);
411    let mut guard = BatchGuard { completed: false };
412    let out = f();
413    guard.completed = true;
414    drop(guard);
415    let effects = REACTIVE.with(|s| std::mem::take(&mut s.borrow_mut().pending_effects));
416    for core in effects {
417        run_effect_core(&core);
418    }
419    out
420}
421
422// ============================================================
423// 通知链
424// ============================================================
425
426/// memo 核心(非泛型 — 注册表按 SubscriberId 索引)
427struct MemoCore {
428    /// true = 依赖已变化,下次 get 重算
429    stale: Cell<bool>,
430    /// 重算中(循环依赖检测)
431    computing: Cell<bool>,
432    /// 下游订阅者(带订阅代数与依赖 generation,失效后通知时剔除)
433    subscribers: RefCell<HashSet<(SubscriberId, u64, u64)>>,
434}
435
436/// effect 核心
437struct EffectCore {
438    run: Box<dyn Fn()>,
439    /// 重入防护
440    running: Cell<bool>,
441    pending: Cell<bool>,
442}
443
444/// Signal::set/update 的统一通知入口
445fn notify_subscribers(subs: &[SubscriberId]) {
446    let mut memo_cores = Vec::new();
447    let mut effect_cores = Vec::new();
448    REACTIVE.with(|s| {
449        let mut s = s.borrow_mut();
450        for sub in subs {
451            if s.batch_depth > 0 {
452                s.pending_dirty.insert(*sub);
453            } else {
454                s.dirty.insert(*sub);
455            }
456            if let Some(c) = s.memo_registry.get(sub).cloned() {
457                memo_cores.push(c);
458            }
459            if let Some(c) = s.effect_registry.get(sub).cloned() {
460                effect_cores.push(c);
461            }
462        }
463    });
464    for c in memo_cores {
465        notify_memo_stale(&c);
466    }
467    for c in effect_cores {
468        schedule_effect(c);
469    }
470}
471
472/// memo 置 stale 并向下游传播(递归;stale 剪枝保证循环依赖终止)
473fn notify_memo_stale(core: &Rc<MemoCore>) {
474    if core.stale.get() {
475        return;
476    }
477    core.stale.set(true);
478    // 剔除已失效的 element 订阅(池复用/卸载后),避免脏集合和 Set 无限增长
479    core.subscribers
480        .borrow_mut()
481        .retain(|(id, epoch, generation)| *epoch == subscriber_epoch(*id) && *generation == subscriber_generation(*id));
482    let downstream: Vec<SubscriberId> = core.subscribers.borrow().iter().map(|(id, _, _)| *id).collect();
483    for d in downstream {
484        mark_dirty(d);
485        let next = REACTIVE.with(|s| s.borrow().memo_registry.get(&d).cloned());
486        if let Some(c) = next {
487            notify_memo_stale(&c);
488        }
489    }
490}
491
492/// effect 调度重跑(batch 感知)
493fn schedule_effect(core: Rc<EffectCore>) {
494    let in_batch = REACTIVE.with(|s| s.borrow().batch_depth > 0);
495    if in_batch {
496        REACTIVE.with(|s| {
497            let mut s = s.borrow_mut();
498            if !s.pending_effects.iter().any(|c| Rc::ptr_eq(c, &core)) {
499                s.pending_effects.push(core);
500            }
501        });
502    } else {
503        run_effect_core(&core);
504    }
505}
506
507/// 立即重跑 effect(重入防护)
508fn run_effect_core(core: &Rc<EffectCore>) {
509    if core.running.get() {
510        core.pending.set(true);
511        return;
512    }
513    let id = REACTIVE.with(|s| s.borrow().effect_registry.iter().find(|(_, c)| Rc::ptr_eq(c, core)).map(|(k, _)| *k));
514    let Some(id) = id else { return };
515    struct RunningGuard<'a>(&'a Cell<bool>);
516    impl Drop for RunningGuard<'_> {
517        fn drop(&mut self) {
518            self.0.set(false);
519        }
520    }
521    core.running.set(true);
522    let _running = RunningGuard(&core.running);
523    // 每次重跑使用新的依赖 generation:本轮没读到的旧 Signal 依赖会在
524    // 下一次通知时被剔除(条件分支不再造成幽灵重跑)。
525    let generation = bump_subscriber_generation(id);
526    let _scope = SubscriberScope::enter_generation(id, generation);
527    (core.run)();
528    drop(_scope);
529    drop(_running);
530    if core.pending.replace(false) {
531        run_effect_core(core);
532    }
533}
534
535// ============================================================
536// Signal
537// ============================================================
538
539struct SignalInner<T> {
540    value: T,
541    /// (订阅者, 订阅时的代数, 依赖 generation)。失效/旧 generation 在下一次 set 时剔除。
542    subscribers: HashSet<(SubscriberId, u64, u64)>,
543    /// 是否被 `peek()` 读过(宿主/应用级读取)。
544    /// 只有这种 Signal 变化才置位全局 ANY_SIGNAL_SET,触发宿主全树 rebuild;
545    /// 仅被 element build `get()` 的 Signal 走 scoped dirty → 选择性重建。
546    peeked: bool,
547}
548
549/// 细粒度响应式值
550pub struct Signal<T> {
551    id: SignalId,
552    inner: Rc<RefCell<SignalInner<T>>>,
553}
554
555impl<T: Clone + 'static> Signal<T> {
556    pub fn new(initial: T) -> Self {
557        Self {
558            id: new_signal_id(),
559            inner: Rc::new(RefCell::new(SignalInner { value: initial, subscribers: HashSet::new(), peeked: false })),
560        }
561    }
562
563    pub fn id(&self) -> SignalId {
564        self.id
565    }
566
567    /// 读取值,并把当前 subscriber 加入依赖集合
568    pub fn get(&self) -> T {
569        if tracking_enabled() {
570            if let Some(sub) = current_subscriber() {
571                let epoch = subscriber_epoch(sub);
572                let generation = current_generation();
573                self.inner.borrow_mut().subscribers.insert((sub, epoch, generation));
574            }
575        }
576        self.inner.borrow().value.clone()
577    }
578
579    /// 借用值执行闭包(不 clone),同时按 `get` 语义登记订阅。
580    ///
581    /// 大值(Vec/字符串/Store 列表)只读计算时应优先用它,避免每次 build 复制。
582    pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
583        if tracking_enabled() {
584            if let Some(sub) = current_subscriber() {
585                let epoch = subscriber_epoch(sub);
586                let generation = current_generation();
587                self.inner.borrow_mut().subscribers.insert((sub, epoch, generation));
588            }
589        }
590        f(&self.inner.borrow().value)
591    }
592
593    /// 读取值但不建立订阅。
594    ///
595    /// 宿主/应用级读取会标记为 `peeked`:该 Signal 变化时触发全树 rebuild
596    /// (因为宿主可能在 build 前半段用 peek 生成了 widget props)。
597    pub fn peek(&self) -> T {
598        let mut inner = self.inner.borrow_mut();
599        inner.peeked = true;
600        inner.value.clone()
601    }
602
603    /// `peek` 的零拷贝版本:借用值执行闭包,并标记宿主级读取。
604    pub fn peek_with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
605        let mut inner = self.inner.borrow_mut();
606        inner.peeked = true;
607        f(&inner.value)
608    }
609
610    /// 读取值但不建立订阅、**也不标记宿主全树重建**。
611    ///
612    /// 仅用于 Debug/统计等纯展示路径;UI build 需要使用 `peek()`(宿主级读取)
613    /// 或 `get()`(组件 build 内订阅)。
614    pub fn peek_silent(&self) -> T {
615        self.inner.borrow().value.clone()
616    }
617
618    /// `peek_silent` 的零拷贝版本(Debug/统计等纯展示路径)。
619    pub fn peek_silent_with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
620        f(&self.inner.borrow().value)
621    }
622
623    /// 直接设值并触发 dirty
624    pub fn set(&self, value: T) {
625        let (subs, peeked) = {
626            let mut inner = self.inner.borrow_mut();
627            inner.value = value;
628            inner.subscribers.retain(|(id, epoch, generation)| {
629                *epoch == subscriber_epoch(*id) && *generation == subscriber_generation(*id)
630            });
631            (inner.subscribers.iter().map(|(id, _, _)| *id).collect::<Vec<_>>(), inner.peeked)
632        };
633        if peeked {
634            mark_any_signal_set();
635        }
636        push_signal_trace(self.id, &subs, peeked);
637        notify_subscribers(&subs);
638    }
639
640    /// 仅当值真正变化时设值并通知;返回是否发生变化。
641    ///
642    /// 高频路径(hover/滚动/主题同值写回)用它跳过无意义的 dirty 传播。
643    pub fn set_if_changed(&self, value: T) -> bool
644    where
645        T: PartialEq,
646    {
647        if self.inner.borrow().value == value {
648            return false;
649        }
650        self.set(value);
651        true
652    }
653
654    /// 仅当 `f` 产生的新值与原值不同时通知;返回是否发生变化。
655    pub fn update_if_changed(&self, f: impl FnOnce(&mut T)) -> bool
656    where
657        T: PartialEq,
658    {
659        let mut next = self.inner.borrow().value.clone();
660        f(&mut next);
661        if self.inner.borrow().value == next {
662            return false;
663        }
664        self.set(next);
665        true
666    }
667
668    /// 修改值并触发 dirty
669    pub fn update(&self, f: impl FnOnce(&mut T)) {
670        let (subs, peeked) = {
671            let mut inner = self.inner.borrow_mut();
672            f(&mut inner.value);
673            inner.subscribers.retain(|(id, epoch, generation)| {
674                *epoch == subscriber_epoch(*id) && *generation == subscriber_generation(*id)
675            });
676            (inner.subscribers.iter().map(|(id, _, _)| *id).collect::<Vec<_>>(), inner.peeked)
677        };
678        if peeked {
679            mark_any_signal_set();
680        }
681        push_signal_trace(self.id, &subs, peeked);
682        notify_subscribers(&subs);
683    }
684
685    /// 当前订阅者数量(测试用)
686    pub fn subscriber_count(&self) -> usize {
687        self.inner.borrow().subscribers.len()
688    }
689}
690
691impl<T: 'static> Clone for Signal<T> {
692    fn clone(&self) -> Self {
693        Self { id: self.id, inner: self.inner.clone() }
694    }
695}
696
697impl<T: 'static> std::fmt::Debug for Signal<T> {
698    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
699        f.debug_struct("Signal").field("id", &self.id).field("value_type", &std::any::type_name::<T>()).finish()
700    }
701}
702
703// ============================================================
704// Memo
705// ============================================================
706
707/// 惰性派生值:依赖自动收集,上游变化 → stale → 下次 `get()` 重算。
708pub struct Memo<T> {
709    id: SubscriberId,
710    core: Rc<MemoCore>,
711    inner: Rc<RefCell<MemoInner<T>>>,
712    /// 注册令牌:所有 clone 共享,最后一个 drop 时才从 registry 注销
713    _registration: Rc<MemoRegistration>,
714}
715
716struct MemoInner<T> {
717    compute: Box<dyn Fn() -> T>,
718    cached: Option<T>,
719}
720
721/// Memo 在全局 registry 中的注册生命周期。
722///
723/// **不能**在 `Memo::drop` 里直接 remove:Clone 共享同一 id/core,
724/// 任意一个 clone 析构都会注销整条依赖链,剩余 clone 永远收不到 stale。
725struct MemoRegistration {
726    id: SubscriberId,
727}
728
729impl Drop for MemoRegistration {
730    fn drop(&mut self) {
731        REACTIVE.with(|s| {
732            s.borrow_mut().memo_registry.remove(&self.id);
733        });
734    }
735}
736
737impl<T: Clone + 'static> Memo<T> {
738    pub fn new(compute: impl Fn() -> T + 'static) -> Self {
739        let id = new_subscriber_id();
740        let memo = Self {
741            id,
742            core: Rc::new(MemoCore {
743                stale: Cell::new(false),
744                computing: Cell::new(false),
745                subscribers: RefCell::new(HashSet::new()),
746            }),
747            inner: Rc::new(RefCell::new(MemoInner { compute: Box::new(compute), cached: None })),
748            _registration: Rc::new(MemoRegistration { id }),
749        };
750        REACTIVE.with(|s| {
751            s.borrow_mut().memo_registry.insert(id, memo.core.clone());
752        });
753        memo.recompute();
754        memo
755    }
756
757    fn recompute(&self) {
758        if self.core.computing.get() {
759            panic!("Memo: circular dependency detected");
760        }
761        struct ComputeGuard<'a> {
762            core: &'a MemoCore,
763            completed: bool,
764        }
765        impl Drop for ComputeGuard<'_> {
766            fn drop(&mut self) {
767                self.core.computing.set(false);
768                if !self.completed {
769                    // 计算 panic:保留 stale,下次 get 必须重算,
770                    // 不能把旧 cached 当新值返回。
771                    self.core.stale.set(true);
772                }
773            }
774        }
775
776        self.core.computing.set(true);
777        self.core.stale.set(false);
778        let mut guard = ComputeGuard { core: &self.core, completed: false };
779        // 每次重算换 generation:上游 Signal/Memo 里上一轮的依赖会被标记为陈旧,
780        // 下一次通知时剔除(条件分支依赖不再永久残留)。
781        let generation = bump_subscriber_generation(self.id);
782        let value = {
783            let _scope = SubscriberScope::enter_generation(self.id, generation);
784            (self.inner.borrow().compute)()
785        };
786        self.inner.borrow_mut().cached = Some(value);
787        guard.completed = true;
788    }
789
790    pub fn get(&self) -> T {
791        if tracking_enabled() {
792            if let Some(sub) = current_subscriber() {
793                if sub != self.id {
794                    let epoch = subscriber_epoch(sub);
795                    let generation = current_generation();
796                    self.core.subscribers.borrow_mut().insert((sub, epoch, generation));
797                }
798            }
799        }
800        if self.core.stale.replace(false) || self.inner.borrow().cached.is_none() {
801            self.recompute();
802        }
803        self.inner.borrow().cached.clone().expect("Memo: cached after recompute")
804    }
805
806    pub fn peek(&self) -> Option<T> {
807        self.inner.borrow().cached.clone()
808    }
809}
810
811impl<T: 'static> Clone for Memo<T> {
812    fn clone(&self) -> Self {
813        Self {
814            id: self.id,
815            core: self.core.clone(),
816            inner: self.inner.clone(),
817            _registration: self._registration.clone(),
818        }
819    }
820}
821
822impl<T: 'static> std::fmt::Debug for Memo<T> {
823    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
824        f.debug_struct("Memo").field("id", &self.id).field("value_type", &std::any::type_name::<T>()).finish()
825    }
826}
827
828// ============================================================
829// Effect
830// ============================================================
831
832/// 自动追踪副作用:创建时立即运行一次,依赖的 signal 变化时重跑。
833pub struct Effect {
834    id: SubscriberId,
835    core: Rc<EffectCore>,
836}
837
838impl Effect {
839    pub fn new(run: impl Fn() + 'static) -> Self {
840        let id = new_subscriber_id();
841        let effect = Self {
842            id,
843            core: Rc::new(EffectCore { run: Box::new(run), running: Cell::new(false), pending: Cell::new(false) }),
844        };
845        REACTIVE.with(|s| {
846            s.borrow_mut().effect_registry.insert(id, effect.core.clone());
847        });
848        // 走统一入口:分配 generation + 重入防护 + 依赖清理
849        run_effect_core(&effect.core);
850        effect
851    }
852
853    pub fn rerun(&self) {
854        run_effect_core(&self.core);
855    }
856}
857
858impl Drop for Effect {
859    fn drop(&mut self) {
860        REACTIVE.with(|s| {
861            s.borrow_mut().effect_registry.remove(&self.id);
862        });
863    }
864}
865
866impl std::fmt::Debug for Effect {
867    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
868        f.debug_struct("Effect").field("id", &self.id).finish()
869    }
870}
871
872#[cfg(test)]
873mod tests {
874    use super::*;
875    use std::panic::{self, AssertUnwindSafe};
876
877    /// 捕获 panic 并临时静音默认 hook,避免测试输出被预期 panic 污染
878    fn quietly<R>(f: impl FnOnce() -> R) -> std::thread::Result<R> {
879        let prev = panic::take_hook();
880        panic::set_hook(Box::new(|_| {}));
881        let out = panic::catch_unwind(AssertUnwindSafe(f));
882        panic::set_hook(prev);
883        out
884    }
885
886    #[test]
887    fn signal_trace_records_only_while_enabled() {
888        clear_signal_trace();
889        set_signal_trace_enabled(false);
890        assert!(!signal_trace_enabled());
891
892        let sig = Signal::new(0);
893        let _ = sig.peek();
894        sig.set(1);
895        assert!(peek_signal_trace(0).is_empty(), "关闭时快照也应为空");
896
897        set_signal_trace_enabled(true);
898        sig.set(2);
899        let snap = peek_signal_trace(0);
900        assert_eq!(snap.len(), 1);
901        assert_eq!(snap[0].signal_id, sig.id);
902        assert!(snap[0].peeked, "peek 读过的 Signal 必须带宿主级标记");
903
904        clear_signal_trace();
905        set_signal_trace_enabled(false);
906    }
907
908    #[test]
909    fn signal_trace_clear_works_while_disabled() {
910        clear_signal_trace();
911        set_signal_trace_enabled(true);
912        let sig = Signal::new(0);
913        sig.set(1);
914        assert_eq!(peek_signal_trace(0).len(), 1);
915
916        set_signal_trace_enabled(false);
917        clear_signal_trace();
918        set_signal_trace_enabled(true);
919        assert!(peek_signal_trace(0).is_empty(), "关闭期间的显式 clear 必须生效");
920        set_signal_trace_enabled(false);
921    }
922
923    #[test]
924    fn dropping_memo_clone_keeps_shared_registration() {
925        let sig = Signal::new(1);
926        let s = sig.clone();
927        let memo = Memo::new(move || s.get() * 2);
928        assert_eq!(memo.get(), 2);
929
930        let clone = memo.clone();
931        drop(clone);
932
933        sig.set(7);
934        assert_eq!(memo.get(), 14, "clone 析构不应注销原 Memo 的依赖注册");
935    }
936
937    #[test]
938    fn memo_panic_keeps_stale_and_recomputes() {
939        let sig = Signal::new(1);
940        let fail = Rc::new(Cell::new(false));
941        let (s, f) = (sig.clone(), fail.clone());
942        let memo = Memo::new(move || {
943            let v = s.get();
944            if f.get() {
945                panic!("memo boom");
946            }
947            v * 2
948        });
949        assert_eq!(memo.get(), 2);
950
951        fail.set(true);
952        sig.set(5);
953        assert!(quietly(|| memo.get()).is_err());
954
955        fail.set(false);
956        assert_eq!(memo.get(), 10, "panic 后必须保留 stale 并重新计算");
957    }
958
959    #[test]
960    fn effect_panic_resets_running_guard() {
961        let sig = Signal::new(0);
962        let fail = Rc::new(Cell::new(false));
963        let runs = Rc::new(Cell::new(0usize));
964        let (s, f, r) = (sig.clone(), fail.clone(), runs.clone());
965        let effect = Effect::new(move || {
966            let _ = s.get();
967            r.set(r.get() + 1);
968            if f.get() {
969                panic!("effect boom");
970            }
971        });
972        assert_eq!(runs.get(), 1);
973
974        fail.set(true);
975        assert!(quietly(|| sig.set(1)).is_err());
976        fail.set(false);
977
978        sig.set(2);
979        assert_eq!(runs.get(), 3, "panic 后 effect 应能继续响应依赖变化");
980        drop(effect);
981    }
982
983    #[test]
984    fn batch_panic_restores_depth() {
985        let sig = Signal::new(0);
986        assert!(quietly(|| batch(|| {
987            sig.set(1);
988            panic!("batch boom");
989        }))
990        .is_err());
991
992        let runs = Rc::new(Cell::new(0usize));
993        let (s, r) = (sig.clone(), runs.clone());
994        let effect = Effect::new(move || {
995            let _ = s.get();
996            r.set(r.get() + 1);
997        });
998        assert_eq!(runs.get(), 1);
999
1000        sig.set(2);
1001        assert_eq!(runs.get(), 2, "batch panic 后 depth 必须归零,set 应立即通知");
1002        drop(effect);
1003    }
1004
1005    #[test]
1006    fn untracked_panic_restores_tracking() {
1007        let sig = Signal::new(0);
1008        assert!(quietly(|| untracked(|| {
1009            let _ = sig.get();
1010            panic!("untracked boom");
1011        }))
1012        .is_err());
1013
1014        let runs = Rc::new(Cell::new(0usize));
1015        let (s, r) = (sig.clone(), runs.clone());
1016        let effect = Effect::new(move || {
1017            let _ = s.get();
1018            r.set(r.get() + 1);
1019        });
1020        sig.set(1);
1021        assert_eq!(runs.get(), 2, "untracked panic 后必须恢复依赖追踪");
1022        drop(effect);
1023    }
1024
1025    #[test]
1026    fn only_peeked_signals_mark_global_rebuild() {
1027        let _ = take_any_signal_set();
1028        let scoped = Signal::new(0);
1029        let id = new_subscriber_id();
1030        with_subscriber(id, || {
1031            let _ = scoped.get();
1032        });
1033        scoped.set(1);
1034        assert!(!take_any_signal_set(), "仅 build 内 get 的 Signal 不应触发全树 rebuild");
1035
1036        let peeked = Signal::new(0);
1037        let _ = peeked.peek();
1038        peeked.set(1);
1039        assert!(take_any_signal_set(), "peek 过的 Signal 变化应触发全树 rebuild");
1040    }
1041
1042    #[test]
1043    fn invalidated_subscriber_is_pruned_on_next_set() {
1044        let sig = Signal::new(0);
1045        let id = new_subscriber_id();
1046        with_subscriber(id, || {
1047            let _ = sig.get();
1048        });
1049        assert_eq!(sig.subscriber_count(), 1);
1050        invalidate_subscriber(id);
1051        sig.set(1);
1052        assert_eq!(sig.subscriber_count(), 0, "失效订阅应在下一次 set 时被剔除");
1053    }
1054
1055    #[test]
1056    fn effect_rerun_drops_stale_dependencies() {
1057        let sig = Signal::new(0);
1058        let gate = Signal::new(true);
1059        let runs = Rc::new(Cell::new(0usize));
1060        let (s, g, r) = (sig.clone(), gate.clone(), runs.clone());
1061        let effect = Effect::new(move || {
1062            r.set(r.get() + 1);
1063            if g.get() {
1064                let _ = s.get();
1065            }
1066        });
1067        assert_eq!(runs.get(), 1);
1068
1069        gate.set(false);
1070        assert_eq!(runs.get(), 2, "gate 变化应重跑");
1071        sig.set(1);
1072        assert_eq!(runs.get(), 2, "gate=false 后旧 Signal 依赖必须被剔除");
1073        drop(effect);
1074    }
1075
1076    #[test]
1077    fn memo_recompute_drops_stale_dependencies() {
1078        let sig = Signal::new(0);
1079        let gate = Signal::new(true);
1080        let computes = Rc::new(Cell::new(0usize));
1081        let (s, g, c) = (sig.clone(), gate.clone(), computes.clone());
1082        let memo = Memo::new(move || {
1083            c.set(c.get() + 1);
1084            if g.get() {
1085                s.get()
1086            } else {
1087                0
1088            }
1089        });
1090        assert_eq!(memo.get(), 0);
1091        assert_eq!(computes.get(), 1);
1092
1093        gate.set(false);
1094        assert_eq!(memo.get(), 0);
1095        assert_eq!(computes.get(), 2, "gate 变化后应重算");
1096
1097        sig.set(1);
1098        assert_eq!(memo.get(), 0);
1099        assert_eq!(computes.get(), 2, "gate=false 后旧 Signal 依赖必须被剔除");
1100    }
1101}