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
211thread_local! {
212    /// 自上次取走后有任意 Signal::set/update 发生(与订阅无关)。
213    /// 宿主(如 showcase)以 peek 读 Signal 进 Widget,不建立订阅 —— 值变化后
214    /// dirty 集合为空,需要这个标记让 drain 返回非零,宿主据此触发 rebuild。
215    static ANY_SIGNAL_SET: Cell<bool> = const { Cell::new(false) };
216    /// peek 信号变化的全局 epoch:每棵 ElementTree 各自记录已消费版本,
217    /// 避免多窗口共用 bool 时“一个窗口消费后其他窗口漏掉全树重建”。
218    static ANY_SIGNAL_EPOCH: Cell<u64> = const { Cell::new(0) };
219}
220
221/// 自上次取走后有任意 Signal::set/update 发生(取出即复位)
222pub fn take_any_signal_set() -> bool {
223    ANY_SIGNAL_SET.with(|c| c.replace(false))
224}
225
226/// 当前 peek 信号变化 epoch(只增不减)
227pub fn any_signal_epoch() -> u64 {
228    ANY_SIGNAL_EPOCH.with(|c| c.get())
229}
230
231/// 标记"有 Signal 值已变化"(batch 内也置位:值已变,宿主下帧 rebuild 即可)
232fn mark_any_signal_set() {
233    ANY_SIGNAL_SET.with(|c| c.set(true));
234    ANY_SIGNAL_EPOCH.with(|c| c.set(c.get().wrapping_add(1)));
235}
236
237/// 标记某个 subscriber 为 dirty
238pub fn mark_dirty(sub_id: SubscriberId) {
239    REACTIVE.with(|s| {
240        let mut s = s.borrow_mut();
241        if s.batch_depth > 0 {
242            s.pending_dirty.insert(sub_id);
243        } else {
244            s.dirty.insert(sub_id);
245        }
246    });
247}
248
249/// 分配新的 SubscriberId
250pub fn new_subscriber_id() -> SubscriberId {
251    REACTIVE.with(|s| {
252        let mut s = s.borrow_mut();
253        let id = SubscriberId(s.next_subscriber_id);
254        s.next_subscriber_id += 1;
255        id
256    })
257}
258
259/// 分配新的 SignalId
260pub fn new_signal_id() -> SignalId {
261    REACTIVE.with(|s| {
262        let mut s = s.borrow_mut();
263        let id = SignalId(s.next_signal_id);
264        s.next_signal_id += 1;
265        id
266    })
267}
268
269/// 当前订阅者(内部用)
270fn current_subscriber() -> Option<SubscriberId> {
271    REACTIVE.with(|s| s.borrow().subscriber_stack.last().map(|(id, _)| *id))
272}
273
274/// 追踪是否启用(untracked 块内为 false)
275fn tracking_enabled() -> bool {
276    TRACKING_PAUSED.with(|c| c.get() == 0)
277}
278
279/// 在 `f` 内的 `Signal::get()` 不建立依赖订阅
280pub fn untracked<T>(f: impl FnOnce() -> T) -> T {
281    struct TrackingGuard;
282    impl Drop for TrackingGuard {
283        fn drop(&mut self) {
284            TRACKING_PAUSED.with(|c| c.set(c.get().saturating_sub(1)));
285        }
286    }
287    TRACKING_PAUSED.with(|c| c.set(c.get() + 1));
288    let _guard = TrackingGuard;
289    f()
290}
291
292/// 批量更新。batch 内的 `Signal::set` 不立即通知订阅者,
293/// 退出时把累积的 dirty / effect 重跑一次性 flush。
294pub fn batch<T>(f: impl FnOnce() -> T) -> T {
295    struct BatchGuard {
296        completed: bool,
297    }
298    impl Drop for BatchGuard {
299        fn drop(&mut self) {
300            let depth = REACTIVE.with(|s| {
301                let mut s = s.borrow_mut();
302                s.batch_depth = s.batch_depth.saturating_sub(1);
303                s.batch_depth
304            });
305            if depth == 0 {
306                REACTIVE.with(|s| {
307                    let mut s = s.borrow_mut();
308                    let pending = std::mem::take(&mut s.pending_dirty);
309                    s.dirty.extend(pending);
310                    if !self.completed {
311                        // 块内 panic:不在这里跑 effect(可能二次 panic)
312                        s.pending_effects.clear();
313                    }
314                });
315            }
316        }
317    }
318
319    REACTIVE.with(|s| s.borrow_mut().batch_depth += 1);
320    let mut guard = BatchGuard { completed: false };
321    let out = f();
322    guard.completed = true;
323    drop(guard);
324    let effects = REACTIVE.with(|s| std::mem::take(&mut s.borrow_mut().pending_effects));
325    for core in effects {
326        run_effect_core(&core);
327    }
328    out
329}
330
331// ============================================================
332// 通知链
333// ============================================================
334
335/// memo 核心(非泛型 — 注册表按 SubscriberId 索引)
336struct MemoCore {
337    /// true = 依赖已变化,下次 get 重算
338    stale: Cell<bool>,
339    /// 重算中(循环依赖检测)
340    computing: Cell<bool>,
341    /// 下游订阅者(带订阅代数与依赖 generation,失效后通知时剔除)
342    subscribers: RefCell<HashSet<(SubscriberId, u64, u64)>>,
343}
344
345/// effect 核心
346struct EffectCore {
347    run: Box<dyn Fn()>,
348    /// 重入防护
349    running: Cell<bool>,
350    pending: Cell<bool>,
351}
352
353/// Signal::set/update 的统一通知入口
354fn notify_subscribers(subs: &[SubscriberId]) {
355    let mut memo_cores = Vec::new();
356    let mut effect_cores = Vec::new();
357    REACTIVE.with(|s| {
358        let mut s = s.borrow_mut();
359        for sub in subs {
360            if s.batch_depth > 0 {
361                s.pending_dirty.insert(*sub);
362            } else {
363                s.dirty.insert(*sub);
364            }
365            if let Some(c) = s.memo_registry.get(sub).cloned() {
366                memo_cores.push(c);
367            }
368            if let Some(c) = s.effect_registry.get(sub).cloned() {
369                effect_cores.push(c);
370            }
371        }
372    });
373    for c in memo_cores {
374        notify_memo_stale(&c);
375    }
376    for c in effect_cores {
377        schedule_effect(c);
378    }
379}
380
381/// memo 置 stale 并向下游传播(递归;stale 剪枝保证循环依赖终止)
382fn notify_memo_stale(core: &Rc<MemoCore>) {
383    if core.stale.get() {
384        return;
385    }
386    core.stale.set(true);
387    // 剔除已失效的 element 订阅(池复用/卸载后),避免脏集合和 Set 无限增长
388    core.subscribers
389        .borrow_mut()
390        .retain(|(id, epoch, generation)| *epoch == subscriber_epoch(*id) && *generation == subscriber_generation(*id));
391    let downstream: Vec<SubscriberId> = core.subscribers.borrow().iter().map(|(id, _, _)| *id).collect();
392    for d in downstream {
393        mark_dirty(d);
394        let next = REACTIVE.with(|s| s.borrow().memo_registry.get(&d).cloned());
395        if let Some(c) = next {
396            notify_memo_stale(&c);
397        }
398    }
399}
400
401/// effect 调度重跑(batch 感知)
402fn schedule_effect(core: Rc<EffectCore>) {
403    let in_batch = REACTIVE.with(|s| s.borrow().batch_depth > 0);
404    if in_batch {
405        REACTIVE.with(|s| {
406            let mut s = s.borrow_mut();
407            if !s.pending_effects.iter().any(|c| Rc::ptr_eq(c, &core)) {
408                s.pending_effects.push(core);
409            }
410        });
411    } else {
412        run_effect_core(&core);
413    }
414}
415
416/// 立即重跑 effect(重入防护)
417fn run_effect_core(core: &Rc<EffectCore>) {
418    if core.running.get() {
419        core.pending.set(true);
420        return;
421    }
422    let id = REACTIVE.with(|s| s.borrow().effect_registry.iter().find(|(_, c)| Rc::ptr_eq(c, core)).map(|(k, _)| *k));
423    let Some(id) = id else { return };
424    struct RunningGuard<'a>(&'a Cell<bool>);
425    impl Drop for RunningGuard<'_> {
426        fn drop(&mut self) {
427            self.0.set(false);
428        }
429    }
430    core.running.set(true);
431    let _running = RunningGuard(&core.running);
432    // 每次重跑使用新的依赖 generation:本轮没读到的旧 Signal 依赖会在
433    // 下一次通知时被剔除(条件分支不再造成幽灵重跑)。
434    let generation = bump_subscriber_generation(id);
435    let _scope = SubscriberScope::enter_generation(id, generation);
436    (core.run)();
437    drop(_scope);
438    drop(_running);
439    if core.pending.replace(false) {
440        run_effect_core(core);
441    }
442}
443
444// ============================================================
445// Signal
446// ============================================================
447
448struct SignalInner<T> {
449    value: T,
450    /// (订阅者, 订阅时的代数, 依赖 generation)。失效/旧 generation 在下一次 set 时剔除。
451    subscribers: HashSet<(SubscriberId, u64, u64)>,
452    /// 是否被 `peek()` 读过(宿主/应用级读取)。
453    /// 只有这种 Signal 变化才置位全局 ANY_SIGNAL_SET,触发宿主全树 rebuild;
454    /// 仅被 element build `get()` 的 Signal 走 scoped dirty → 选择性重建。
455    peeked: bool,
456}
457
458/// 细粒度响应式值
459pub struct Signal<T> {
460    id: SignalId,
461    inner: Rc<RefCell<SignalInner<T>>>,
462}
463
464impl<T: Clone + 'static> Signal<T> {
465    pub fn new(initial: T) -> Self {
466        Self {
467            id: new_signal_id(),
468            inner: Rc::new(RefCell::new(SignalInner { value: initial, subscribers: HashSet::new(), peeked: false })),
469        }
470    }
471
472    pub fn id(&self) -> SignalId {
473        self.id
474    }
475
476    /// 读取值,并把当前 subscriber 加入依赖集合
477    pub fn get(&self) -> T {
478        if tracking_enabled() {
479            if let Some(sub) = current_subscriber() {
480                let epoch = subscriber_epoch(sub);
481                let generation = current_generation();
482                self.inner.borrow_mut().subscribers.insert((sub, epoch, generation));
483            }
484        }
485        self.inner.borrow().value.clone()
486    }
487
488    /// 借用值执行闭包(不 clone),同时按 `get` 语义登记订阅。
489    ///
490    /// 大值(Vec/字符串/Store 列表)只读计算时应优先用它,避免每次 build 复制。
491    pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
492        if tracking_enabled() {
493            if let Some(sub) = current_subscriber() {
494                let epoch = subscriber_epoch(sub);
495                let generation = current_generation();
496                self.inner.borrow_mut().subscribers.insert((sub, epoch, generation));
497            }
498        }
499        f(&self.inner.borrow().value)
500    }
501
502    /// 读取值但不建立订阅。
503    ///
504    /// 宿主/应用级读取会标记为 `peeked`:该 Signal 变化时触发全树 rebuild
505    /// (因为宿主可能在 build 前半段用 peek 生成了 widget props)。
506    pub fn peek(&self) -> T {
507        let mut inner = self.inner.borrow_mut();
508        inner.peeked = true;
509        inner.value.clone()
510    }
511
512    /// `peek` 的零拷贝版本:借用值执行闭包,并标记宿主级读取。
513    pub fn peek_with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
514        let mut inner = self.inner.borrow_mut();
515        inner.peeked = true;
516        f(&inner.value)
517    }
518
519    /// 读取值但不建立订阅、**也不标记宿主全树重建**。
520    ///
521    /// 仅用于 Debug/统计等纯展示路径;UI build 需要使用 `peek()`(宿主级读取)
522    /// 或 `get()`(组件 build 内订阅)。
523    pub fn peek_silent(&self) -> T {
524        self.inner.borrow().value.clone()
525    }
526
527    /// `peek_silent` 的零拷贝版本(Debug/统计等纯展示路径)。
528    pub fn peek_silent_with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
529        f(&self.inner.borrow().value)
530    }
531
532    /// 直接设值并触发 dirty
533    pub fn set(&self, value: T) {
534        let (subs, peeked) = {
535            let mut inner = self.inner.borrow_mut();
536            inner.value = value;
537            inner.subscribers.retain(|(id, epoch, generation)| {
538                *epoch == subscriber_epoch(*id) && *generation == subscriber_generation(*id)
539            });
540            (inner.subscribers.iter().map(|(id, _, _)| *id).collect::<Vec<_>>(), inner.peeked)
541        };
542        if peeked {
543            mark_any_signal_set();
544        }
545        notify_subscribers(&subs);
546    }
547
548    /// 仅当值真正变化时设值并通知;返回是否发生变化。
549    ///
550    /// 高频路径(hover/滚动/主题同值写回)用它跳过无意义的 dirty 传播。
551    pub fn set_if_changed(&self, value: T) -> bool
552    where
553        T: PartialEq,
554    {
555        if self.inner.borrow().value == value {
556            return false;
557        }
558        self.set(value);
559        true
560    }
561
562    /// 仅当 `f` 产生的新值与原值不同时通知;返回是否发生变化。
563    pub fn update_if_changed(&self, f: impl FnOnce(&mut T)) -> bool
564    where
565        T: PartialEq,
566    {
567        let mut next = self.inner.borrow().value.clone();
568        f(&mut next);
569        if self.inner.borrow().value == next {
570            return false;
571        }
572        self.set(next);
573        true
574    }
575
576    /// 修改值并触发 dirty
577    pub fn update(&self, f: impl FnOnce(&mut T)) {
578        let (subs, peeked) = {
579            let mut inner = self.inner.borrow_mut();
580            f(&mut inner.value);
581            inner.subscribers.retain(|(id, epoch, generation)| {
582                *epoch == subscriber_epoch(*id) && *generation == subscriber_generation(*id)
583            });
584            (inner.subscribers.iter().map(|(id, _, _)| *id).collect::<Vec<_>>(), inner.peeked)
585        };
586        if peeked {
587            mark_any_signal_set();
588        }
589        notify_subscribers(&subs);
590    }
591
592    /// 当前订阅者数量(测试用)
593    pub fn subscriber_count(&self) -> usize {
594        self.inner.borrow().subscribers.len()
595    }
596}
597
598impl<T: 'static> Clone for Signal<T> {
599    fn clone(&self) -> Self {
600        Self { id: self.id, inner: self.inner.clone() }
601    }
602}
603
604impl<T: 'static> std::fmt::Debug for Signal<T> {
605    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
606        f.debug_struct("Signal").field("id", &self.id).field("value_type", &std::any::type_name::<T>()).finish()
607    }
608}
609
610// ============================================================
611// Memo
612// ============================================================
613
614/// 惰性派生值:依赖自动收集,上游变化 → stale → 下次 `get()` 重算。
615pub struct Memo<T> {
616    id: SubscriberId,
617    core: Rc<MemoCore>,
618    inner: Rc<RefCell<MemoInner<T>>>,
619    /// 注册令牌:所有 clone 共享,最后一个 drop 时才从 registry 注销
620    _registration: Rc<MemoRegistration>,
621}
622
623struct MemoInner<T> {
624    compute: Box<dyn Fn() -> T>,
625    cached: Option<T>,
626}
627
628/// Memo 在全局 registry 中的注册生命周期。
629///
630/// **不能**在 `Memo::drop` 里直接 remove:Clone 共享同一 id/core,
631/// 任意一个 clone 析构都会注销整条依赖链,剩余 clone 永远收不到 stale。
632struct MemoRegistration {
633    id: SubscriberId,
634}
635
636impl Drop for MemoRegistration {
637    fn drop(&mut self) {
638        REACTIVE.with(|s| {
639            s.borrow_mut().memo_registry.remove(&self.id);
640        });
641    }
642}
643
644impl<T: Clone + 'static> Memo<T> {
645    pub fn new(compute: impl Fn() -> T + 'static) -> Self {
646        let id = new_subscriber_id();
647        let memo = Self {
648            id,
649            core: Rc::new(MemoCore {
650                stale: Cell::new(false),
651                computing: Cell::new(false),
652                subscribers: RefCell::new(HashSet::new()),
653            }),
654            inner: Rc::new(RefCell::new(MemoInner { compute: Box::new(compute), cached: None })),
655            _registration: Rc::new(MemoRegistration { id }),
656        };
657        REACTIVE.with(|s| {
658            s.borrow_mut().memo_registry.insert(id, memo.core.clone());
659        });
660        memo.recompute();
661        memo
662    }
663
664    fn recompute(&self) {
665        if self.core.computing.get() {
666            panic!("Memo: circular dependency detected");
667        }
668        struct ComputeGuard<'a> {
669            core: &'a MemoCore,
670            completed: bool,
671        }
672        impl Drop for ComputeGuard<'_> {
673            fn drop(&mut self) {
674                self.core.computing.set(false);
675                if !self.completed {
676                    // 计算 panic:保留 stale,下次 get 必须重算,
677                    // 不能把旧 cached 当新值返回。
678                    self.core.stale.set(true);
679                }
680            }
681        }
682
683        self.core.computing.set(true);
684        self.core.stale.set(false);
685        let mut guard = ComputeGuard { core: &self.core, completed: false };
686        // 每次重算换 generation:上游 Signal/Memo 里上一轮的依赖会被标记为陈旧,
687        // 下一次通知时剔除(条件分支依赖不再永久残留)。
688        let generation = bump_subscriber_generation(self.id);
689        let value = {
690            let _scope = SubscriberScope::enter_generation(self.id, generation);
691            (self.inner.borrow().compute)()
692        };
693        self.inner.borrow_mut().cached = Some(value);
694        guard.completed = true;
695    }
696
697    pub fn get(&self) -> T {
698        if tracking_enabled() {
699            if let Some(sub) = current_subscriber() {
700                if sub != self.id {
701                    let epoch = subscriber_epoch(sub);
702                    let generation = current_generation();
703                    self.core.subscribers.borrow_mut().insert((sub, epoch, generation));
704                }
705            }
706        }
707        if self.core.stale.replace(false) || self.inner.borrow().cached.is_none() {
708            self.recompute();
709        }
710        self.inner.borrow().cached.clone().expect("Memo: cached after recompute")
711    }
712
713    pub fn peek(&self) -> Option<T> {
714        self.inner.borrow().cached.clone()
715    }
716}
717
718impl<T: 'static> Clone for Memo<T> {
719    fn clone(&self) -> Self {
720        Self {
721            id: self.id,
722            core: self.core.clone(),
723            inner: self.inner.clone(),
724            _registration: self._registration.clone(),
725        }
726    }
727}
728
729impl<T: 'static> std::fmt::Debug for Memo<T> {
730    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
731        f.debug_struct("Memo").field("id", &self.id).field("value_type", &std::any::type_name::<T>()).finish()
732    }
733}
734
735// ============================================================
736// Effect
737// ============================================================
738
739/// 自动追踪副作用:创建时立即运行一次,依赖的 signal 变化时重跑。
740pub struct Effect {
741    id: SubscriberId,
742    core: Rc<EffectCore>,
743}
744
745impl Effect {
746    pub fn new(run: impl Fn() + 'static) -> Self {
747        let id = new_subscriber_id();
748        let effect = Self {
749            id,
750            core: Rc::new(EffectCore { run: Box::new(run), running: Cell::new(false), pending: Cell::new(false) }),
751        };
752        REACTIVE.with(|s| {
753            s.borrow_mut().effect_registry.insert(id, effect.core.clone());
754        });
755        // 走统一入口:分配 generation + 重入防护 + 依赖清理
756        run_effect_core(&effect.core);
757        effect
758    }
759
760    pub fn rerun(&self) {
761        run_effect_core(&self.core);
762    }
763}
764
765impl Drop for Effect {
766    fn drop(&mut self) {
767        REACTIVE.with(|s| {
768            s.borrow_mut().effect_registry.remove(&self.id);
769        });
770    }
771}
772
773impl std::fmt::Debug for Effect {
774    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
775        f.debug_struct("Effect").field("id", &self.id).finish()
776    }
777}
778
779#[cfg(test)]
780mod tests {
781    use super::*;
782    use std::panic::{self, AssertUnwindSafe};
783
784    /// 捕获 panic 并临时静音默认 hook,避免测试输出被预期 panic 污染
785    fn quietly<R>(f: impl FnOnce() -> R) -> std::thread::Result<R> {
786        let prev = panic::take_hook();
787        panic::set_hook(Box::new(|_| {}));
788        let out = panic::catch_unwind(AssertUnwindSafe(f));
789        panic::set_hook(prev);
790        out
791    }
792
793    #[test]
794    fn dropping_memo_clone_keeps_shared_registration() {
795        let sig = Signal::new(1);
796        let s = sig.clone();
797        let memo = Memo::new(move || s.get() * 2);
798        assert_eq!(memo.get(), 2);
799
800        let clone = memo.clone();
801        drop(clone);
802
803        sig.set(7);
804        assert_eq!(memo.get(), 14, "clone 析构不应注销原 Memo 的依赖注册");
805    }
806
807    #[test]
808    fn memo_panic_keeps_stale_and_recomputes() {
809        let sig = Signal::new(1);
810        let fail = Rc::new(Cell::new(false));
811        let (s, f) = (sig.clone(), fail.clone());
812        let memo = Memo::new(move || {
813            let v = s.get();
814            if f.get() {
815                panic!("memo boom");
816            }
817            v * 2
818        });
819        assert_eq!(memo.get(), 2);
820
821        fail.set(true);
822        sig.set(5);
823        assert!(quietly(|| memo.get()).is_err());
824
825        fail.set(false);
826        assert_eq!(memo.get(), 10, "panic 后必须保留 stale 并重新计算");
827    }
828
829    #[test]
830    fn effect_panic_resets_running_guard() {
831        let sig = Signal::new(0);
832        let fail = Rc::new(Cell::new(false));
833        let runs = Rc::new(Cell::new(0usize));
834        let (s, f, r) = (sig.clone(), fail.clone(), runs.clone());
835        let effect = Effect::new(move || {
836            let _ = s.get();
837            r.set(r.get() + 1);
838            if f.get() {
839                panic!("effect boom");
840            }
841        });
842        assert_eq!(runs.get(), 1);
843
844        fail.set(true);
845        assert!(quietly(|| sig.set(1)).is_err());
846        fail.set(false);
847
848        sig.set(2);
849        assert_eq!(runs.get(), 3, "panic 后 effect 应能继续响应依赖变化");
850        drop(effect);
851    }
852
853    #[test]
854    fn batch_panic_restores_depth() {
855        let sig = Signal::new(0);
856        assert!(quietly(|| batch(|| {
857            sig.set(1);
858            panic!("batch boom");
859        }))
860        .is_err());
861
862        let runs = Rc::new(Cell::new(0usize));
863        let (s, r) = (sig.clone(), runs.clone());
864        let effect = Effect::new(move || {
865            let _ = s.get();
866            r.set(r.get() + 1);
867        });
868        assert_eq!(runs.get(), 1);
869
870        sig.set(2);
871        assert_eq!(runs.get(), 2, "batch panic 后 depth 必须归零,set 应立即通知");
872        drop(effect);
873    }
874
875    #[test]
876    fn untracked_panic_restores_tracking() {
877        let sig = Signal::new(0);
878        assert!(quietly(|| untracked(|| {
879            let _ = sig.get();
880            panic!("untracked boom");
881        }))
882        .is_err());
883
884        let runs = Rc::new(Cell::new(0usize));
885        let (s, r) = (sig.clone(), runs.clone());
886        let effect = Effect::new(move || {
887            let _ = s.get();
888            r.set(r.get() + 1);
889        });
890        sig.set(1);
891        assert_eq!(runs.get(), 2, "untracked panic 后必须恢复依赖追踪");
892        drop(effect);
893    }
894
895    #[test]
896    fn only_peeked_signals_mark_global_rebuild() {
897        let _ = take_any_signal_set();
898        let scoped = Signal::new(0);
899        let id = new_subscriber_id();
900        with_subscriber(id, || {
901            let _ = scoped.get();
902        });
903        scoped.set(1);
904        assert!(!take_any_signal_set(), "仅 build 内 get 的 Signal 不应触发全树 rebuild");
905
906        let peeked = Signal::new(0);
907        let _ = peeked.peek();
908        peeked.set(1);
909        assert!(take_any_signal_set(), "peek 过的 Signal 变化应触发全树 rebuild");
910    }
911
912    #[test]
913    fn invalidated_subscriber_is_pruned_on_next_set() {
914        let sig = Signal::new(0);
915        let id = new_subscriber_id();
916        with_subscriber(id, || {
917            let _ = sig.get();
918        });
919        assert_eq!(sig.subscriber_count(), 1);
920        invalidate_subscriber(id);
921        sig.set(1);
922        assert_eq!(sig.subscriber_count(), 0, "失效订阅应在下一次 set 时被剔除");
923    }
924
925    #[test]
926    fn effect_rerun_drops_stale_dependencies() {
927        let sig = Signal::new(0);
928        let gate = Signal::new(true);
929        let runs = Rc::new(Cell::new(0usize));
930        let (s, g, r) = (sig.clone(), gate.clone(), runs.clone());
931        let effect = Effect::new(move || {
932            r.set(r.get() + 1);
933            if g.get() {
934                let _ = s.get();
935            }
936        });
937        assert_eq!(runs.get(), 1);
938
939        gate.set(false);
940        assert_eq!(runs.get(), 2, "gate 变化应重跑");
941        sig.set(1);
942        assert_eq!(runs.get(), 2, "gate=false 后旧 Signal 依赖必须被剔除");
943        drop(effect);
944    }
945
946    #[test]
947    fn memo_recompute_drops_stale_dependencies() {
948        let sig = Signal::new(0);
949        let gate = Signal::new(true);
950        let computes = Rc::new(Cell::new(0usize));
951        let (s, g, c) = (sig.clone(), gate.clone(), computes.clone());
952        let memo = Memo::new(move || {
953            c.set(c.get() + 1);
954            if g.get() {
955                s.get()
956            } else {
957                0
958            }
959        });
960        assert_eq!(memo.get(), 0);
961        assert_eq!(computes.get(), 1);
962
963        gate.set(false);
964        assert_eq!(memo.get(), 0);
965        assert_eq!(computes.get(), 2, "gate 变化后应重算");
966
967        sig.set(1);
968        assert_eq!(memo.get(), 0);
969        assert_eq!(computes.get(), 2, "gate=false 后旧 Signal 依赖必须被剔除");
970    }
971}