rgpui 1.3.0

GUI UI framework
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
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
//! 一次性密码(OTP)输入:多位数字格子输入。

use std::sync::Arc;

use crate::{prelude::FluentBuilder as _, *};

actions!(
    otp_input,
    [
        OTPBackspace,
        OTPDelete,
        OTPLeft,
        OTPRight,
        OTPHome,
        OTPEnd,
        OTPPaste,
        OTPEscape,
    ]
);

/// 注册 OTP 输入的键盘绑定。
pub fn init(cx: &mut App) {
    cx.bind_keys([
        KeyBinding::new("backspace", OTPBackspace, Some("OTPInput")),
        KeyBinding::new("delete", OTPDelete, Some("OTPInput")),
        KeyBinding::new("left", OTPLeft, Some("OTPInput")),
        KeyBinding::new("right", OTPRight, Some("OTPInput")),
        KeyBinding::new("home", OTPHome, Some("OTPInput")),
        KeyBinding::new("end", OTPEnd, Some("OTPInput")),
        #[cfg(target_os = "macos")]
        KeyBinding::new("cmd-v", OTPPaste, Some("OTPInput")),
        #[cfg(not(target_os = "macos"))]
        KeyBinding::new("ctrl-v", OTPPaste, Some("OTPInput")),
        KeyBinding::new("escape", OTPEscape, Some("OTPInput")),
    ]);
}

/// OTP 输入事件。
#[derive(Clone, Debug)]
pub enum OTPInputEvent {
    /// 值变化。
    Change(String),
    /// 输入完整。
    Complete(String),
    /// 获得焦点。
    Focus,
    /// 失去焦点。
    Blur,
}

/// OTP 输入尺寸。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum OTPInputSize {
    /// 小尺寸。
    Sm,
    /// 中尺寸(默认)。
    #[default]
    Md,
    /// 大尺寸。
    Lg,
}

/// OTP 输入状态。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum OTPInputState {
    /// 默认状态。
    #[default]
    Default,
    /// 错误状态(红色高亮)。
    Error,
    /// 成功状态(绿色高亮)。
    Success,
}

/// OTP 状态实体:管理各格子的焦点与数字。
pub struct OTPState {
    /// 每个格子的焦点句柄。
    focus_handles: Vec<FocusHandle>,
    /// 各格子数字。
    digits: Vec<Option<char>>,
    /// 当前聚焦下标。
    focused_index: usize,
    /// 格子数量。
    digit_count: usize,
    /// 是否掩码显示。
    masked: bool,
    /// 是否禁用。
    disabled: bool,
    /// 输入状态。
    state: OTPInputState,
}

impl EventEmitter<OTPInputEvent> for OTPState {}

impl OTPState {
    /// 创建 OTP 状态,格子数限制在 4~8。
    pub fn new(cx: &mut Context<Self>, digit_count: usize) -> Self {
        let digit_count = digit_count.clamp(4, 8);
        let focus_handles: Vec<FocusHandle> = (0..digit_count).map(|_| cx.focus_handle()).collect();

        Self {
            focus_handles,
            digits: vec![None; digit_count],
            focused_index: 0,
            digit_count,
            masked: false,
            disabled: false,
            state: OTPInputState::Default,
        }
    }

    /// 设置格子数量(4~8)。
    pub fn digit_count(mut self, count: usize) -> Self {
        let count = count.clamp(4, 8);
        self.digit_count = count;
        self.digits.resize(count, None);
        self
    }

    /// 设置是否掩码显示。
    pub fn masked(mut self, masked: bool) -> Self {
        self.masked = masked;
        self
    }

    /// 获取当前输入的完整字符串。
    pub fn value(&self) -> String {
        self.digits.iter().filter_map(|d| *d).collect()
    }

    /// 是否已填满。
    pub fn is_complete(&self) -> bool {
        self.digits.iter().all(|d| d.is_some())
    }

    /// 以字符串设置数字(仅接受 ASCII 数字)。
    pub fn set_value(&mut self, value: &str, cx: &mut Context<Self>) {
        self.digits.fill(None);

        for (i, ch) in value.chars().take(self.digit_count).enumerate() {
            if ch.is_ascii_digit() {
                self.digits[i] = Some(ch);
            }
        }

        cx.emit(OTPInputEvent::Change(self.value()));

        if self.is_complete() {
            cx.emit(OTPInputEvent::Complete(self.value()));
        }

        cx.notify();
    }

    /// 清空所有数字。
    pub fn clear(&mut self, cx: &mut Context<Self>) {
        self.digits.fill(None);
        self.focused_index = 0;
        cx.emit(OTPInputEvent::Change(String::new()));
        cx.notify();
    }

    /// 设置输入状态(默认/错误/成功)。
    pub fn set_state(&mut self, state: OTPInputState, cx: &mut Context<Self>) {
        self.state = state;
        cx.notify();
    }

    /// 设为错误状态。
    pub fn set_error(&mut self, cx: &mut Context<Self>) {
        self.state = OTPInputState::Error;
        cx.notify();
    }

    /// 设为成功状态。
    pub fn set_success(&mut self, cx: &mut Context<Self>) {
        self.state = OTPInputState::Success;
        cx.notify();
    }

    /// 聚焦第一个格子。
    pub fn focus_first(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        self.focused_index = 0;
        if let Some(handle) = self.focus_handles.first() {
            window.focus(handle, cx);
        }
        cx.notify();
    }

    /// 在指定格子写入数字并自动推进焦点。
    fn set_digit(
        &mut self,
        index: usize,
        digit: char,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        if index >= self.digit_count || !digit.is_ascii_digit() {
            return;
        }

        self.digits[index] = Some(digit);
        cx.emit(OTPInputEvent::Change(self.value()));

        if self.is_complete() {
            cx.emit(OTPInputEvent::Complete(self.value()));
        } else if index + 1 < self.digit_count {
            self.focused_index = index + 1;
            window.focus(&self.focus_handles[index + 1], cx);
        }

        cx.notify();
    }

    /// 清除指定格子的数字。
    fn clear_digit(&mut self, index: usize, cx: &mut Context<Self>) {
        if index >= self.digit_count {
            return;
        }

        self.digits[index] = None;
        cx.emit(OTPInputEvent::Change(self.value()));
        cx.notify();
    }

    /// 焦点左移。
    fn move_left(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        if self.focused_index > 0 {
            self.focused_index -= 1;
            window.focus(&self.focus_handles[self.focused_index], cx);
            cx.notify();
        }
    }

    /// 焦点右移。
    fn move_right(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        if self.focused_index + 1 < self.digit_count {
            self.focused_index += 1;
            window.focus(&self.focus_handles[self.focused_index], cx);
            cx.notify();
        }
    }

    /// 焦点移到开头。
    fn move_home(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        self.focused_index = 0;
        window.focus(&self.focus_handles[0], cx);
        cx.notify();
    }

    /// 焦点移到末尾。
    fn move_end(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        self.focused_index = self.digit_count - 1;
        window.focus(&self.focus_handles[self.focused_index], cx);
        cx.notify();
    }

    /// 退格:清除当前格子或回退到前一格清除。
    pub fn backspace(&mut self, _: &OTPBackspace, window: &mut Window, cx: &mut Context<Self>) {
        if self.disabled {
            return;
        }

        if self.digits[self.focused_index].is_some() {
            self.clear_digit(self.focused_index, cx);
        } else if self.focused_index > 0 {
            self.focused_index -= 1;
            self.clear_digit(self.focused_index, cx);
            window.focus(&self.focus_handles[self.focused_index], cx);
        }
    }

    /// 删除当前格子数字。
    pub fn delete(&mut self, _: &OTPDelete, _window: &mut Window, cx: &mut Context<Self>) {
        if self.disabled {
            return;
        }

        self.clear_digit(self.focused_index, cx);
    }

    /// 左移。
    pub fn left(&mut self, _: &OTPLeft, window: &mut Window, cx: &mut Context<Self>) {
        self.move_left(window, cx);
    }

    /// 右移。
    pub fn right(&mut self, _: &OTPRight, window: &mut Window, cx: &mut Context<Self>) {
        self.move_right(window, cx);
    }

    /// 移到开头。
    pub fn home(&mut self, _: &OTPHome, window: &mut Window, cx: &mut Context<Self>) {
        self.move_home(window, cx);
    }

    /// 移到末尾。
    pub fn end(&mut self, _: &OTPEnd, window: &mut Window, cx: &mut Context<Self>) {
        self.move_end(window, cx);
    }

    /// 从剪贴板粘贴数字。
    pub fn paste(&mut self, _: &OTPPaste, _window: &mut Window, cx: &mut Context<Self>) {
        if self.disabled {
            return;
        }

        if let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) {
            let digits: String = text.chars().filter(|c| c.is_ascii_digit()).collect();
            self.set_value(&digits, cx);
        }
    }

    /// 退出焦点。
    pub fn escape(&mut self, _: &OTPEscape, window: &mut Window, cx: &mut Context<Self>) {
        window.blur();
        cx.emit(OTPInputEvent::Blur);
        cx.notify();
    }

    /// 获取指定格子的焦点句柄。
    pub fn focus_handle(&self, index: usize, _: &App) -> Option<FocusHandle> {
        self.focus_handles.get(index).cloned()
    }
}

impl Focusable for OTPState {
    fn focus_handle(&self, _: &App) -> FocusHandle {
        self.focus_handles
            .first()
            .cloned()
            .expect("OTPState must have at least one focus handle")
    }
}

impl Render for OTPState {
    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
        div()
    }
}

/// 一次性密码输入组件。
#[derive(IntoElement)]
pub struct OTPInput {
    /// 绑定状态实体。
    state: Entity<OTPState>,
    /// 尺寸。
    size: OTPInputSize,
    /// 是否禁用。
    disabled: bool,
    /// 是否掩码显示。
    masked: bool,
    /// 分隔符文本。
    separator: Option<SharedString>,
    /// 分隔符位置(从 1 计)。
    separator_position: Option<usize>,
    /// 值变化回调。
    on_change: Option<Arc<dyn Fn(String, &mut Window, &mut App) + Send + Sync>>,
    /// 输入完成回调。
    on_complete: Option<Arc<dyn Fn(String, &mut Window, &mut App) + Send + Sync>>,
    /// 用户样式。
    style: StyleRefinement,
}

impl OTPInput {
    /// 创建 OTP 输入组件。
    pub fn new(state: &Entity<OTPState>) -> Self {
        Self {
            state: state.clone(),
            size: OTPInputSize::default(),
            disabled: false,
            masked: false,
            separator: None,
            separator_position: None,
            on_change: None,
            on_complete: None,
            style: StyleRefinement::default(),
        }
    }

    /// 设置尺寸。
    pub fn size(mut self, size: OTPInputSize) -> Self {
        self.size = size;
        self
    }

    /// 设置是否禁用。
    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    /// 设置是否掩码显示。
    pub fn masked(mut self, masked: bool) -> Self {
        self.masked = masked;
        self
    }

    /// 设置分隔符。
    pub fn separator(mut self, separator: impl Into<SharedString>) -> Self {
        self.separator = Some(separator.into());
        self
    }

    /// 设置分隔符位置(从 1 计)。
    pub fn separator_position(mut self, position: usize) -> Self {
        self.separator_position = Some(position);
        self
    }

    /// 设置值变化回调。
    pub fn on_change<F>(mut self, callback: F) -> Self
    where
        F: Fn(String, &mut Window, &mut App) + Send + Sync + 'static,
    {
        self.on_change = Some(Arc::new(callback));
        self
    }

    /// 设置输入完成回调。
    pub fn on_complete<F>(mut self, callback: F) -> Self
    where
        F: Fn(String, &mut Window, &mut App) + Send + Sync + 'static,
    {
        self.on_complete = Some(Arc::new(callback));
        self
    }

    /// 获取格子边长。
    fn box_size(&self) -> Pixels {
        match self.size {
            OTPInputSize::Sm => px(36.0),
            OTPInputSize::Md => px(44.0),
            OTPInputSize::Lg => px(52.0),
        }
    }

    /// 获取字号。
    fn font_size(&self) -> Pixels {
        match self.size {
            OTPInputSize::Sm => px(16.0),
            OTPInputSize::Md => px(20.0),
            OTPInputSize::Lg => px(24.0),
        }
    }

    /// 获取格子间隙。
    fn input_gap(&self) -> Pixels {
        match self.size {
            OTPInputSize::Sm => px(6.0),
            OTPInputSize::Md => px(8.0),
            OTPInputSize::Lg => px(10.0),
        }
    }
}

impl Styled for OTPInput {
    fn style(&mut self) -> &mut StyleRefinement {
        &mut self.style
    }
}

impl RenderOnce for OTPInput {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        // 先取出所有需要的主题值,避免 cx 借用与后续实体更新冲突。
        let theme = cx.theme();
        let border = theme.tokens.border;
        let ring = theme.tokens.ring;
        let muted = theme.tokens.muted;
        let background = theme.tokens.background;
        let muted_foreground = theme.tokens.muted_foreground;
        let foreground = theme.tokens.foreground;
        let primary = theme.tokens.primary;
        let radius = theme.radius;
        let mono_font_family = theme.mono_font_family.clone();
        let error_border = theme.highlight_theme.style.status.error_border(cx);

        let box_size = self.box_size();
        let font_size = self.font_size();
        let input_gap = self.input_gap();

        let otp_state = self.state.read(cx);
        let digit_count = otp_state.digit_count;
        let digits = otp_state.digits.clone();
        let _focused_index = otp_state.focused_index;
        let state = otp_state.state;
        let masked = self.masked || otp_state.masked;
        let disabled = self.disabled || otp_state.disabled;
        let focus_handles: Vec<FocusHandle> = otp_state.focus_handles.iter().cloned().collect();

        self.state.update(cx, |state, _| {
            state.disabled = disabled;
            state.masked = masked;
        });

        let on_change_callback = self.on_change.clone();
        let on_complete_callback = self.on_complete.clone();

        if on_change_callback.is_some() || on_complete_callback.is_some() {
            let state_entity = self.state.clone();
            cx.subscribe(
                &state_entity,
                move |_emitter: Entity<OTPState>, event: &OTPInputEvent, cx: &mut App| {
                    // 回调签名含 Window,但订阅触发常在按键分发中(窗口正被 take),
                    // 此时同步 update 必失败(F12 同款教训),故经 spawn 延后分发;
                    // 无活动窗口时静默跳过。
                    let Some(window) = cx.active_window() else {
                        return;
                    };
                    let (callback, value) = match event {
                        OTPInputEvent::Change(value) => (on_change_callback.clone(), value.clone()),
                        OTPInputEvent::Complete(value) => {
                            (on_complete_callback.clone(), value.clone())
                        }
                        _ => return,
                    };
                    if let Some(callback) = callback {
                        cx.spawn(async move |cx| {
                            _ = window.update(cx, |_, window, cx| {
                                callback(value, window, cx);
                            });
                        })
                        .detach();
                    }
                },
            )
            .detach();
        }

        let (border_color, focus_border_color) = match state {
            OTPInputState::Default => (border.color, ring.color),
            OTPInputState::Error => (error_border, error_border),
            OTPInputState::Success => (primary.color, primary.color),
        };

        let user_style = self.style;
        let separator = self.separator.clone();
        let separator_position = self.separator_position.unwrap_or(digit_count / 2);

        let mut root = div()
            .id(("otp-input", self.state.entity_id()))
            .key_context("OTPInput")
            .flex()
            .items_center()
            .gap(input_gap)
            .when(!disabled, |this| {
                this.on_action(window.listener_for(&self.state, OTPState::backspace))
                    .on_action(window.listener_for(&self.state, OTPState::delete))
                    .on_action(window.listener_for(&self.state, OTPState::left))
                    .on_action(window.listener_for(&self.state, OTPState::right))
                    .on_action(window.listener_for(&self.state, OTPState::home))
                    .on_action(window.listener_for(&self.state, OTPState::end))
                    .on_action(window.listener_for(&self.state, OTPState::paste))
                    .on_action(window.listener_for(&self.state, OTPState::escape))
            })
            .children((0..digit_count).flat_map(|i| {
                let state_clone = self.state.clone();
                let focus_handle = focus_handles[i].clone();
                let focus_handle_for_track = focus_handle.clone();
                let focus_handle_for_click = focus_handle.clone();
                let is_focused = focus_handle.is_focused(window);
                let digit = digits[i];

                let display_char = if let Some(d) = digit {
                    if masked {
                        SharedString::from("")
                    } else {
                        SharedString::from(d.to_string())
                    }
                } else {
                    SharedString::from("")
                };

                let digit_box = div()
                    .id(ElementId::NamedInteger("otp-digit".into(), i as u64))
                    .track_focus(&focus_handle_for_track.tab_index(0).tab_stop(true))
                    .size(box_size)
                    .flex()
                    .items_center()
                    .justify_center()
                    .bg(if disabled {
                        muted.opacity(0.5)
                    } else {
                        background.color
                    })
                    .border_1()
                    .border_color(if is_focused && !disabled {
                        focus_border_color
                    } else {
                        border_color
                    })
                    .rounded(radius)
                    .text_size(font_size)
                    .font_weight(FontWeight::SEMIBOLD)
                    .font_family(mono_font_family.clone())
                    .text_color(if disabled {
                        muted_foreground
                    } else {
                        foreground
                    })
                    .when(is_focused && !disabled, |this| {
                        // 聚焦时用主题色外发光代替旧库的 focus_ring 阴影。
                        this.shadow(vec![
                            BoxShadow::new(px(0.0), px(0.0), focus_border_color)
                                .blur_radius(px(6.0)),
                        ])
                    })
                    .when(!disabled, |this| {
                        this.cursor(CursorStyle::IBeam)
                            .hover(|style| style.border_color(focus_border_color))
                    })
                    .on_mouse_down(MouseButton::Left, {
                        let state = state_clone.clone();
                        move |_, window, cx| {
                            window.focus(&focus_handle_for_click, cx);
                            state.update(cx, |s, cx| {
                                s.focused_index = i;
                                cx.notify();
                            });
                        }
                    })
                    .on_key_down({
                        let state = state_clone;
                        move |event, window, cx| {
                            if disabled {
                                return;
                            }

                            let key = &event.keystroke.key;
                            if key.len() == 1 {
                                if let Some(ch) = key.chars().next() {
                                    if ch.is_ascii_digit() {
                                        state.update(cx, |s, cx| {
                                            s.set_digit(i, ch, window, cx);
                                        });
                                        cx.stop_propagation();
                                    }
                                }
                            }
                        }
                    })
                    .child(display_char)
                    .into_any_element();

                let should_show_separator =
                    separator.is_some() && i == separator_position - 1 && i + 1 < digit_count;

                if should_show_separator {
                    vec![
                        digit_box,
                        div()
                            .text_size(font_size)
                            .text_color(muted_foreground)
                            .child(separator.clone().unwrap())
                            .into_any_element(),
                    ]
                } else {
                    vec![digit_box]
                }
            }));

        root.style().refine(&user_style);
        root
    }
}

#[cfg(test)]
mod tests {
    // 注:不能 `use super::*`——本文件有 `use crate::*`,会把根导出的
    // `test` 过程宏引进作用域,遮蔽内置 `#[test]` 导致宏无限递归。
    use super::{OTPInput, OTPState};
    use crate::{AppContext as _, Context, Entity, Render};
    use std::sync::{Arc, Mutex};

    /// 测试宿主视图(渲染带回调的 OTP 输入)。
    struct Probe {
        state: Entity<OTPState>,
        fired: Arc<Mutex<Vec<String>>>,
    }

    impl Probe {
        fn new(
            _window: &mut crate::Window,
            cx: &mut Context<Self>,
            state: Entity<OTPState>,
            fired: Arc<Mutex<Vec<String>>>,
        ) -> Self {
            let _ = cx;
            Self { state, fired }
        }
    }

    impl Render for Probe {
        fn render(
            &mut self,
            _window: &mut crate::Window,
            _cx: &mut Context<Self>,
        ) -> impl crate::IntoElement {
            let fired = self.fired.clone();
            OTPInput::new(&self.state).on_change(move |value: String, _, _| {
                fired.lock().unwrap().push(value);
            })
        }
    }

    /// 分发中触发的订阅也必须送达:订阅回调常在按键分发中运行(窗口正被 take),
    /// 同步 update 窗口必失败,故实现经 spawn 延后;本用例复现该路径并断言送达。
    #[rgpui::test]
    fn otp_callbacks_fire_when_emitted_during_dispatch(cx: &mut crate::TestAppContext) {
        let fired = Arc::new(Mutex::new(Vec::<String>::new()));
        let state = cx.new(|cx| OTPState::new(cx, 4));
        let state_for_probe = state.clone();
        let fired_for_probe = fired.clone();
        let (_view, window_cx) = cx.add_window_view(move |window, cx| {
            Probe::new(window, cx, state_for_probe, fired_for_probe)
        });
        window_cx.update(|window, cx| {
            // 测试平台的 App::activate 是空实现,直接激活窗口以设置 active_window。
            window.activate_window();
            // 首帧绘制注册订阅。
            let _ = window.draw(cx);
        });
        // 在窗口被 take 的上下文中触发(复现按键分发路径)。
        window_cx.update(|_, cx| {
            state.update(cx, |state, cx| state.set_value("12", cx));
        });
        // 泵延后任务再断言(F12 同款:spawn 任务在后续泵送中执行)。
        // 注:不断言精确次数——render 每帧都会 subscribe(预存泄漏,非本项范围),
        // 这里只证明分发中触发的订阅回调有送达(旧同步实现会静默吞掉)。
        window_cx.run_until_parked();
        window_cx.update(|window, cx| {
            let _ = window.draw(cx);
        });
        let fired = fired.lock().unwrap();
        assert!(
            !fired.is_empty(),
            "分发中触发的 OTP 订阅回调被吞(同步 update 窗口必失败)"
        );
        assert!(fired.iter().all(|value| value == "12"));
    }
}