arc-ui 0.4.0

Physics-first native Rust desktop UI component library & charts for GPUI (120+ interactive components ported from Arc).
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
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: registry/components/notification-center/{notification-center.tsx,notification-center.module.css}.
//! 浮层用 `deferred` 提升到独立绘制层(等价于 Portal 的分层),开合由 `ArcPresence` 控制,
//! 因此关闭时面板整体淡出/上移,而不是立即消失。
use super::{child_id, text};
use crate::{Avatar, Button, ButtonSize, ButtonVariant};
use arc_motion::{ArcPresence, ArcPresenceConfig, arc_spring};
use arc_tokens::{
    ActiveArcTheme as _, BlockTokens, NotificationTokens as N, Radii, Shadows, Spacing, Typography,
};
use gpui_kit::base::{ElementExt as _, StyledExt as _};
use gpui_kit::{
    Anchor, App, Bounds, ElementId, Entity, FocusHandle, Hsla, IntoElement, KeyDownEvent,
    MouseDownEvent, ParentElement, Pixels, RenderOnce, Role, SharedString, Size, Styled,
    TestSupportExt as _, Transformation, Window, anchored,
    assets::IconName,
    base::{Button as BaseButton, MotionReveal},
    canvas, deferred, div, point,
    prelude::*,
    px, size, svg,
};
use std::{
    cell::RefCell,
    collections::{HashMap, HashSet},
    rc::Rc,
};

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum NotificationTone {
    #[default]
    Info,
    Success,
    Warning,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct NotificationActor {
    pub name: SharedString,
    pub photo: SharedString,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct NotificationItem {
    pub id: SharedString,
    pub title: SharedString,
    pub description: Option<SharedString>,
    pub time: SharedString,
    pub read: bool,
    pub tone: NotificationTone,
    pub actor: Option<NotificationActor>,
}
impl NotificationItem {
    pub fn new(
        id: impl Into<SharedString>,
        title: impl Into<SharedString>,
        time: impl Into<SharedString>,
    ) -> Self {
        Self {
            id: id.into(),
            title: title.into(),
            time: time.into(),
            description: None,
            read: false,
            tone: NotificationTone::Info,
            actor: None,
        }
    }
    pub fn description(mut self, value: impl Into<SharedString>) -> Self {
        self.description = Some(value.into());
        self
    }
    pub fn read(mut self, value: bool) -> Self {
        self.read = value;
        self
    }
    pub fn tone(mut self, value: NotificationTone) -> Self {
        self.tone = value;
        self
    }
    pub fn actor(mut self, name: impl Into<SharedString>, photo: impl Into<SharedString>) -> Self {
        self.actor = Some(NotificationActor {
            name: name.into(),
            photo: photo.into(),
        });
        self
    }
    /// 折叠时的摘要:上游优先描述,其次作者,最后是通用提示。
    fn preview(&self) -> SharedString {
        self.description
            .clone()
            .unwrap_or_else(|| match &self.actor {
                Some(actor) => format!("From {}", actor.name).into(),
                None => "View update details".into(),
            })
    }
    /// 展开后的正文,比摘要更完整。
    fn body(&self) -> SharedString {
        self.description
            .clone()
            .unwrap_or_else(|| match &self.actor {
                Some(actor) => format!("{} shared an update with you.", actor.name).into(),
                None => "This update is ready to review.".into(),
            })
    }
}
#[derive(Clone)]
struct State {
    items: Vec<NotificationItem>,
    unread_only: bool,
    expanded: Option<SharedString>,
    retained: Vec<NotificationItem>,
    focus: HashMap<SharedString, FocusHandle>,
    tabs: [FocusHandle; 2],
    open: bool,
    was_open: bool,
    panel_focus: FocusHandle,
    trigger_focus: FocusHandle,
    trigger_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
    panel_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
}
type ReadHandler = Rc<dyn Fn(&NotificationItem, bool, &mut Window, &mut App)>;
type DismissHandler = Rc<dyn Fn(&NotificationItem, &mut Window, &mut App)>;
type OpenHandler = Rc<dyn Fn(bool, &mut Window, &mut App)>;
type CloseHandler = Rc<dyn Fn(&mut Window, &mut App)>;
#[derive(Clone)]
struct PanelHandlers {
    read: Option<ReadHandler>,
    dismiss: Option<DismissHandler>,
    close: CloseHandler,
}
#[derive(IntoElement)]
pub struct NotificationCenter {
    id: ElementId,
    notifications: Vec<NotificationItem>,
    label: SharedString,
    open: Option<bool>,
    on_read_change: Option<ReadHandler>,
    on_dismiss: Option<DismissHandler>,
    on_open_change: Option<OpenHandler>,
    avoid_collisions: bool,
}
impl NotificationCenter {
    pub fn new(id: impl Into<ElementId>) -> Self {
        Self {
            id: id.into(),
            notifications: vec![],
            label: "Notifications".into(),
            open: None,
            on_read_change: None,
            on_dismiss: None,
            on_open_change: None,
            avoid_collisions: true,
        }
    }
    pub fn notifications(mut self, items: impl IntoIterator<Item = NotificationItem>) -> Self {
        self.notifications = items.into_iter().collect();
        self
    }
    pub fn label(mut self, v: impl Into<SharedString>) -> Self {
        self.label = v.into();
        self
    }
    pub fn open(mut self, v: bool) -> Self {
        self.open = Some(v);
        self
    }
    /// 上游 `avoidCollisions`:开启时按视口空间自动翻转面板(下方放不下翻上方、
    /// 靠近视口左缘时改左对齐);关闭则固定下方右对齐。
    pub fn avoid_collisions(mut self, v: bool) -> Self {
        self.avoid_collisions = v;
        self
    }
    pub fn on_read_change(
        mut self,
        f: impl Fn(&NotificationItem, bool, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_read_change = Some(Rc::new(f));
        self
    }
    pub fn on_dismiss(
        mut self,
        f: impl Fn(&NotificationItem, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_dismiss = Some(Rc::new(f));
        self
    }
    pub fn on_open_change(mut self, f: impl Fn(bool, &mut Window, &mut App) + 'static) -> Self {
        self.on_open_change = Some(Rc::new(f));
        self
    }
}
/// GPUI 的原始 Svg 不解析父级 currentColor;必须把主题色写在图元本身。
/// 通知中心所有独立 SVG 统一由此构造,避免按钮可点击却没有图标。
fn notification_icon(name: IconName, size: Pixels, color: Hsla) -> gpui_kit::Svg {
    svg()
        .path(name.path())
        .size(size)
        .flex_none()
        .text_color(color)
}

impl RenderOnce for NotificationCenter {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let initial = self.notifications;
        // 与上游一致:notifications 是首次挂载的初值,后续读/删除由内部维护。
        let state = window.use_keyed_state(child_id(&self.id, "state"), cx, |_, cx| State {
            retained: initial.clone(),
            items: initial,
            unread_only: false,
            expanded: None,
            focus: HashMap::new(),
            tabs: [cx.focus_handle(), cx.focus_handle()],
            open: false,
            was_open: false,
            panel_focus: cx.focus_handle(),
            trigger_focus: cx.focus_handle(),
            trigger_bounds: Rc::new(RefCell::new(None)),
            panel_bounds: Rc::new(RefCell::new(None)),
        });
        let unread = state.read(cx).items.iter().filter(|i| !i.read).count();
        let label = self.label.clone();
        let id = self.id.clone();
        let read = self.on_read_change;
        let dismiss = self.on_dismiss;
        let open_change = self.on_open_change;
        let controlled = self.open;
        let is_open = controlled.unwrap_or(state.read(cx).open);
        let motion = cx.arc_theme().motion;
        // 关闭时面板继续留在 deferred 层,直到退场曲线结束。
        let presence = ArcPresence::new((child_id(&self.id, "presence"), "panel"), is_open)
            .animate_initial(false)
            .config(ArcPresenceConfig {
                enter_duration: motion.duration.standard,
                exit_duration: motion.duration.instant,
                enter_ease: motion.ease.enter,
                exit_ease: motion.ease.standard,
                fade_on_reduced_motion: true,
            })
            .sample(window, cx);
        let close: CloseHandler = {
            let st = state.clone();
            let cb = open_change.clone();
            Rc::new(move |w: &mut Window, cx: &mut App| {
                close_panel(&st, cb.as_ref(), w, cx);
            })
        };
        let was_open = state.read(cx).was_open;
        if is_open && !was_open {
            let handle = state.read(cx).panel_focus.clone();
            window.focus(&handle, cx);
            state.update(cx, |s, _| s.was_open = true);
        } else if !is_open && was_open {
            state.update(cx, |s, _| s.was_open = false);
        }
        let trigger_focus = state.read(cx).trigger_focus.clone();
        let panel_focus = state.read(cx).panel_focus.clone();
        let trigger_bounds = state.read(cx).trigger_bounds.clone();
        let panel_bounds = state.read(cx).panel_bounds.clone();
        let toggle_state = state.clone();
        let toggle_cb = open_change.clone();
        let colors = cx.arc_theme().colors;
        let tilt = arc_spring(
            (self.id.clone(), "bell-tilt"),
            if is_open && !arc_motion::is_reduced_motion(cx) {
                N::BELL_TILT_DEG
            } else {
                0.0
            },
            motion.spring.snappy,
            window,
            cx,
        );
        let badge = ArcPresence::new((self.id.clone(), "badge"), unread > 0)
            .animate_initial(false)
            .sample(window, cx);
        let mut trigger = BaseButton::new(child_id(&self.id, "trigger"))
            .relative()
            .flex_none()
            .size(N::TRIGGER)
            .rounded(N::TRIGGER_RADIUS)
            .border_1()
            .border_color(colors.border)
            .bg(if is_open {
                colors.surface_muted
            } else {
                colors.surface
            })
            .text_color(colors.foreground)
            .flex()
            .items_center()
            .justify_center()
            .hover(|s| {
                s.bg(colors.surface_muted)
                    .border_color(colors.border_strong)
            })
            .child(
                notification_icon(IconName::Bell, N::BELL, colors.foreground)
                    .with_transformation(Transformation::rotate(gpui_kit::Radians(
                        tilt.to_radians(),
                    )))
                    .id(child_id(&self.id, "bell"))
                    .test_support(),
            )
            .accessibility_label(if unread == 0 {
                label.to_string()
            } else {
                format!("{label}, {unread} unread")
            })
            .track_focus(&trigger_focus)
            .on_click(move |_, w, cx| {
                let next = !is_open;
                if controlled.is_none() {
                    toggle_state.update(cx, |s, _| s.open = next);
                }
                if let Some(cb) = &toggle_cb {
                    cb(next, w, cx)
                }
                w.refresh();
            });
        if badge.should_render() {
            trigger = trigger.child(
                div()
                    .id(child_id(&self.id, "badge"))
                    .test_support()
                    .absolute()
                    .top(N::BADGE_OFFSET)
                    .right(N::BADGE_OFFSET)
                    .min_w(N::BADGE)
                    .h(N::BADGE)
                    .px(Spacing::S1)
                    .border_2()
                    .border_color(colors.surface)
                    .rounded_full()
                    .bg(colors.foreground)
                    .text_color(colors.background)
                    .text_size(Typography::TEXT_XS)
                    .font_medium()
                    .flex()
                    .items_center()
                    .justify_center()
                    .opacity(badge.progress)
                    .child(rolling_count(
                        child_id(&self.id, "badge-roll"),
                        unread,
                        true,
                        window,
                        cx,
                    )),
            );
        }
        let escape_close = close.clone();
        let bounds_state = trigger_bounds.clone();
        let mut root = div()
            .id(self.id.clone())
            .relative()
            .flex_none()
            .size(N::TRIGGER)
            .track_focus(&panel_focus)
            .on_prepaint(move |bounds, _, _| {
                *bounds_state.borrow_mut() = Some(bounds);
            })
            .on_key_down(move |event: &KeyDownEvent, w, cx| {
                if is_open && event.keystroke.key == "escape" {
                    escape_close(w, cx);
                }
            })
            .child(
                canvas(|_, _, _| {}, {
                    let trigger_bounds = trigger_bounds.clone();
                    let panel_bounds = panel_bounds.clone();
                    let close = close.clone();
                    move |_, _, window, _| {
                        if !is_open {
                            return;
                        }
                        let trigger_bounds = trigger_bounds.clone();
                        let panel_bounds = panel_bounds.clone();
                        let close = close.clone();
                        window.on_mouse_event(move |event: &MouseDownEvent, phase, w, cx| {
                            if !phase.bubble() {
                                return;
                            }
                            let inside_trigger = trigger_bounds
                                .borrow()
                                .is_some_and(|b| b.contains(&event.position));
                            let inside_panel = panel_bounds
                                .borrow()
                                .is_some_and(|b| b.contains(&event.position));
                            if !inside_trigger && !inside_panel {
                                close(w, cx);
                            }
                        });
                    }
                })
                .absolute()
                .inset_0(),
            )
            .child(trigger);
        if presence.should_render() {
            let p = presence.progress.clamp(0.0, 1.0);
            let lift = if arc_motion::is_reduced_motion(cx) {
                0.0
            } else {
                -N::PANEL_TRAVEL * (1.0 - p)
            };
            let panel = render_panel(
                &id,
                &label,
                &state,
                PanelHandlers {
                    read: read.clone(),
                    dismiss: dismiss.clone(),
                    close: close.clone(),
                },
                window,
                cx,
            );
            // Radix 式防碰撞:用上一帧记录的触发器/面板几何决定翻转;首帧用默认定位。
            let viewport = window.viewport_size();
            let (place_above, align_left) = {
                let trigger_snapshot = trigger_bounds.borrow();
                let panel_snapshot = panel_bounds.borrow();
                let panel_estimate = panel_snapshot.map(|b| b.size).unwrap_or_else(|| {
                    size(
                        BlockTokens::NOTIFICATIONS_WIDTH,
                        BlockTokens::NOTIFICATIONS_HEIGHT,
                    )
                });
                trigger_snapshot
                    .map(|t| resolve_placement(t, panel_estimate, viewport, self.avoid_collisions))
                    .unwrap_or((false, false))
            };
            // 使用窗口坐标锚点,避免把 flex 拉宽的故事容器误当触发器;
            // anchored 的窗口边缘吸附负责水平 shift,翻转仍由实测空间决定。
            let trigger_rect = *trigger_bounds.borrow();
            let anchor = match (place_above, align_left) {
                (true, true) => Anchor::BottomLeft,
                (true, false) => Anchor::BottomCenter,
                (false, true) => Anchor::TopLeft,
                (false, false) => Anchor::TopCenter,
            };
            let mut layer = anchored().anchor(anchor);
            if let Some(t) = trigger_rect {
                let x = if align_left {
                    t.origin.x
                } else {
                    t.origin.x + t.size.width / 2.0
                };
                let y = if place_above {
                    t.origin.y - N::PANEL_GAP - px(lift)
                } else {
                    t.origin.y + t.size.height + N::PANEL_GAP + px(lift)
                };
                layer = layer.position(point(x, y));
            }
            if self.avoid_collisions {
                layer = layer.snap_to_window_with_margin(N::PANEL_GAP);
            }
            root =
                root.child(deferred(layer.child(div().opacity(p).child(panel))).with_priority(1));
        }
        root
    }
}
/// 与上游 Radix `avoidCollisions` 等价的纯决策函数:
/// 返回 `(翻转到触发器上方, 改为左对齐)`。
fn resolve_placement(
    trigger: Bounds<Pixels>,
    panel: Size<Pixels>,
    viewport: Size<Pixels>,
    avoid_collisions: bool,
) -> (bool, bool) {
    if !avoid_collisions {
        return (false, false);
    }
    let gap = 12.0f32;
    let below = f32::from(viewport.height) - f32::from(trigger.origin.y + trigger.size.height);
    let above = f32::from(trigger.origin.y);
    let place_above = f32::from(panel.height) + gap > below && above > below;
    let margin = f32::from(Spacing::S6);
    let align_left =
        f32::from(trigger.origin.x + trigger.size.width) < f32::from(panel.width) + margin;
    (place_above, align_left)
}
fn close_panel(state: &Entity<State>, cb: Option<&OpenHandler>, w: &mut Window, cx: &mut App) {
    state.update(cx, |s, _| s.open = false);
    if let Some(cb) = cb {
        cb(false, w, cx)
    }
    let handle = state.read(cx).trigger_focus.clone();
    w.focus(&handle, cx);
    w.refresh();
}
/// 上游 RollingCount:按增减方向滚动整份计数,避免用字符补间产生中间假计数。
fn rolling_count(
    id: ElementId,
    value: usize,
    capped: bool,
    window: &mut Window,
    cx: &mut App,
) -> gpui_kit::AnyElement {
    let pitch = f32::from(Typography::TEXT_XS) * Typography::LEADING_BODY;
    let position = arc_spring(
        (id.clone(), "roll"),
        value as f32 * pitch,
        cx.arc_theme().motion.spring.snappy,
        window,
        cx,
    );
    let display = if capped && value > 9 {
        "9+".to_owned()
    } else {
        value.to_string()
    };
    div()
        .relative()
        .overflow_hidden()
        .h(px(pitch))
        .min_w(Spacing::S2)
        .child(
            div()
                .relative()
                .top(px((value as f32 * pitch - position).clamp(-pitch, pitch)))
                .text_size(Typography::TEXT_XS)
                .child(display),
        )
        .into_any_element()
}

fn visual(item: &NotificationItem, id: &ElementId, cx: &App) -> gpui_kit::AnyElement {
    if let Some(actor) = item.actor.as_ref() {
        return Avatar::new(child_id(id, "avatar"), actor.name.clone())
            .src(actor.photo.clone())
            .into_any_element();
    }
    let colors = cx.arc_theme().colors;
    let (glyph, color) = match item.tone {
        NotificationTone::Warning => (IconName::TriangleAlert, colors.warning),
        NotificationTone::Success => (IconName::CircleCheck, colors.success),
        NotificationTone::Info => (IconName::MessageCircle, colors.accent),
    };
    div()
        .flex_none()
        .size(N::VISUAL)
        .flex()
        .items_center()
        .justify_center()
        .text_color(color)
        .child(
            notification_icon(glyph, N::EVENT_ICON, color)
                .id(child_id(id, "event-icon"))
                .test_support(),
        )
        .into_any_element()
}
fn render_panel(
    id: &ElementId,
    label: &SharedString,
    state: &Entity<State>,
    handlers: PanelHandlers,
    window: &mut Window,
    cx: &mut App,
) -> gpui_kit::AnyElement {
    let PanelHandlers {
        read,
        dismiss,
        close,
    } = handlers;
    let motion = cx.arc_theme().motion;
    let colors = cx.arc_theme().colors;
    let snap = state.read(cx).clone();
    let unread = snap.items.iter().filter(|i| !i.read).count();
    let read_count = snap.items.len() - unread;
    let visible: Vec<_> = snap
        .items
        .iter()
        .filter(|i| !snap.unread_only || !i.read)
        .cloned()
        .collect();
    let visible_ids: Vec<SharedString> = visible.iter().map(|i| i.id.clone()).collect();
    let ids: HashSet<_> = visible_ids.iter().cloned().collect();
    let mut focus = snap.focus.clone();
    for item in &snap.items {
        focus
            .entry(item.id.clone())
            .or_insert_with(|| cx.focus_handle());
    }
    if focus.len() != snap.focus.len() {
        let next = focus.clone();
        state.update(cx, |s, _| s.focus = next);
    }
    let (all_tab, unread_tab) = (snap.tabs[0].clone(), snap.tabs[1].clone());
    let mut retained = snap.retained;
    for item in &snap.items {
        if let Some(old) = retained.iter_mut().find(|i| i.id == item.id) {
            *old = item.clone()
        } else {
            retained.push(item.clone())
        }
    }
    let close_button = close.clone();
    let panel_bounds = state.read(cx).panel_bounds.clone();
    let summary = match unread {
        0 => "You’re all caught up".to_owned(),
        1 => "1 update waiting for you".to_owned(),
        n => format!("{n} updates waiting for you"),
    };
    let narrow = f32::from(window.viewport_size().width) < N::NARROW;
    let panel_height = BlockTokens::NOTIFICATIONS_HEIGHT
        .min((window.viewport_size().height - N::PANEL_GAP * 2.0).max(px(0.0)));
    let reserved_height = N::HEADER_TOP
        + N::HEADER_BOTTOM
        + Typography::TEXT_XL * 1.2
        + Spacing::S1
        + Typography::TEXT_XS * Typography::LEADING_BODY
        + N::TOOLBAR
        + if read_count > 0 { N::FOOTER } else { px(0.0) };
    let mut root = div()
        .flex()
        .flex_col()
        .min_w(px(0.0))
        .rounded(N::PANEL_RADIUS)
        .border_1()
        .border_color(colors.border)
        .bg(colors.surface_raised)
        .text_color(colors.foreground)
        .text_size(Typography::TEXT_SM)
        .shadow(Shadows::floating(cx.arc_theme().mode))
        .id(child_id(id, "panel"))
        .test_support()
        .on_prepaint(move |bounds, _, _| {
            *panel_bounds.borrow_mut() = Some(bounds);
        })
        .role(Role::Dialog)
        .aria_label(label.clone())
        .w(BlockTokens::NOTIFICATIONS_WIDTH)
        .max_w(window.viewport_size().width - Spacing::S6)
        .max_h(panel_height)
        .child(
            div()
                .flex_none()
                .flex()
                .items_start()
                .justify_between()
                .gap(Spacing::S3)
                .px(if narrow { Spacing::S4 } else { Spacing::S6 })
                .pt(N::HEADER_TOP)
                .pb(N::HEADER_BOTTOM)
                .child(
                    div()
                        .min_w(px(0.0))
                        .flex_1()
                        .child(
                            div()
                                .flex()
                                .items_center()
                                .gap(Spacing::S2)
                                .child(
                                    div()
                                        .text_size(if narrow {
                                            Typography::TEXT_LG
                                        } else {
                                            Typography::TEXT_XL
                                        })
                                        .font_medium()
                                        .child(label.clone()),
                                )
                                .child(
                                    div()
                                        .id(child_id(id, "count"))
                                        .test_support()
                                        .min_w(N::COUNT)
                                        .h(N::COUNT)
                                        .px(Spacing::S1)
                                        .rounded(N::COUNT_RADIUS)
                                        .bg(colors.surface_muted)
                                        .text_size(Typography::TEXT_XS)
                                        .text_color(colors.text_secondary)
                                        .flex()
                                        .items_center()
                                        .justify_center()
                                        .child(rolling_count(
                                            child_id(id, "heading-roll"),
                                            unread,
                                            false,
                                            window,
                                            cx,
                                        )),
                                ),
                        )
                        .child(
                            div()
                                .id(child_id(id, "summary"))
                                .role(Role::Status)
                                .aria_label(summary.clone())
                                .mt(Spacing::S1)
                                .text_size(Typography::TEXT_XS)
                                .text_color(colors.text_secondary)
                                .child(summary),
                        ),
                )
                .child(
                    BaseButton::new(child_id(id, "close"))
                        .accessibility_label("Close notifications")
                        .size(N::CLOSE)
                        .flex_none()
                        .rounded(Radii::CONTROL)
                        .flex()
                        .items_center()
                        .justify_center()
                        .text_color(colors.text_muted)
                        .hover(|s| s.bg(colors.surface_muted).text_color(colors.foreground))
                        .child(notification_icon(
                            IconName::Close,
                            Spacing::S4,
                            colors.text_muted,
                        ))
                        .on_click(move |_, w, cx| close_button(w, cx)),
                ),
        );
    let mut toolbar = div()
        .flex_none()
        .flex()
        .items_center()
        .justify_between()
        .gap(Spacing::S3)
        .min_h(N::TOOLBAR)
        .px(if narrow { Spacing::S3 } else { Spacing::S5 })
        .pb(N::TOOLBAR_BOTTOM)
        .border_b_1()
        .border_color(colors.border_subtle);
    let tab_x = arc_spring(
        (id.clone(), "view-highlight"),
        if snap.unread_only {
            f32::from(N::TAB_WIDTH + N::TAB_GAP)
        } else {
            0.0
        },
        motion.spring.morph,
        window,
        cx,
    );
    let mut switch = div().relative().flex().gap(N::TAB_GAP).child(
        div()
            .absolute()
            .left(px(tab_x))
            .top_0()
            .w(N::TAB_WIDTH)
            .h(N::TAB)
            .rounded(N::TAB_RADIUS)
            .bg(colors.surface_muted),
    );
    for (key, title, unread_only, handle) in [
        ("all", "All", false, all_tab.clone()),
        ("unread", "Unread", true, unread_tab.clone()),
    ] {
        let state = state.clone();
        switch = switch.child(
            BaseButton::new(child_id(id, key))
                .accessibility_label(title)
                .relative()
                .w(N::TAB_WIDTH)
                .h(N::TAB)
                .rounded(N::TAB_RADIUS)
                .text_size(Typography::TEXT_XS)
                .text_color(if snap.unread_only == unread_only {
                    colors.foreground
                } else {
                    colors.text_secondary
                })
                .flex()
                .items_center()
                .justify_center()
                .child(title)
                .track_focus(&handle)
                .on_click(move |_, w, cx| {
                    state.update(cx, |s, _| {
                        s.unread_only = unread_only;
                        s.expanded = None
                    });
                    w.refresh()
                }),
        );
    }
    toolbar = toolbar.child(switch);
    if unread > 0 {
        let state = state.clone();
        let read = read.clone();
        let focus_target = if snap.unread_only {
            unread_tab.clone()
        } else {
            all_tab.clone()
        };
        toolbar = toolbar.child(
            BaseButton::new(child_id(id, "mark-all"))
                .accessibility_label("Mark all read")
                .flex_none()
                .flex()
                .items_center()
                .gap(N::DOT)
                .text_size(Typography::TEXT_XS)
                .text_color(colors.text_secondary)
                .py(N::DOT)
                .child(notification_icon(
                    IconName::CheckCheck,
                    Spacing::S4,
                    colors.text_secondary,
                ))
                .when(!narrow, |d| d.child("Mark all read"))
                .on_click(move |_, w, cx| {
                    let changed = state
                        .read(cx)
                        .items
                        .iter()
                        .filter(|i| !i.read)
                        .cloned()
                        .collect::<Vec<_>>();
                    state.update(cx, |s, _| {
                        for i in &mut s.items {
                            i.read = true
                        }
                        s.expanded = None;
                    });
                    if let Some(cb) = &read {
                        for i in &changed {
                            cb(i, true, w, cx)
                        }
                    }
                    w.focus(&focus_target, cx);
                    w.refresh();
                }),
        );
    }
    root = root.child(toolbar);
    let mut rows = div()
        .id(child_id(id, "list"))
        .test_support()
        .role(Role::List)
        .aria_label(if snap.unread_only {
            "Unread notifications"
        } else {
            "All notifications"
        })
        .min_h(px(0.0))
        .flex_shrink(1.0)
        .max_h((panel_height - reserved_height).max(px(0.0)))
        .px(if narrow { Spacing::S1 } else { N::LIST_X })
        .pt(N::LIST_TOP)
        .pb(N::ITEM_PAD)
        .overflow_y_scroll();
    let mut keep = vec![];
    for item in retained {
        let present = ids.contains(&item.id);
        let presence = ArcPresence::new((child_id(id, item.id.clone()), "row"), present)
            .animate_initial(false)
            .sample(window, cx);
        if !presence.should_render() {
            continue;
        }
        keep.push(item.clone());
        let expanded = present && snap.expanded.as_ref() == Some(&item.id);
        let item_id = child_id(id, format!("item-{}", item.id));
        let st = state.clone();
        let key = item.id.clone();
        let position = visible_ids.iter().position(|v| v == &item.id);
        let neighbor = position
            .and_then(|i| {
                visible_ids
                    .get(i + 1)
                    .or_else(|| i.checked_sub(1).and_then(|p| visible_ids.get(p)))
            })
            .and_then(|next| focus.get(next))
            .cloned();
        let handle = focus.get(&item.id).cloned();
        let mut toggle = BaseButton::new(child_id(&item_id, "toggle"))
            .accessibility_label(format!(
                "{}{}{}",
                item.title,
                if item.read { "" } else { ", unread" },
                if expanded {
                    ". Hide details"
                } else {
                    ". Show details"
                }
            ))
            .flex_1()
            .min_w(px(0.0))
            .flex()
            .flex_col()
            .gap(Spacing::S1)
            .pt(px(2.0))
            .text_color(colors.foreground)
            .child(
                div()
                    .w_full()
                    .flex()
                    .items_center()
                    .gap(N::DOT)
                    .child(
                        div()
                            .flex_1()
                            .min_w(px(0.0))
                            .truncate()
                            .text_size(Typography::TEXT_SM)
                            .font_medium()
                            .text_color(if item.read {
                                colors.text_secondary
                            } else {
                                colors.foreground
                            })
                            .child(item.title.clone()),
                    )
                    .when(!item.read, |d| {
                        d.child(
                            div()
                                .flex_none()
                                .size(N::DOT)
                                .rounded_full()
                                .bg(colors.foreground),
                        )
                    }),
            )
            .child(
                div()
                    .w_full()
                    .truncate()
                    .text_size(Typography::TEXT_XS)
                    .text_color(colors.text_secondary)
                    .child(item.preview()),
            )
            .disabled(!present)
            .on_click(move |_, w, cx| {
                st.update(cx, |s, _| {
                    s.expanded = if s.expanded.as_ref() == Some(&key) {
                        None
                    } else {
                        Some(key.clone())
                    }
                });
                w.refresh()
            });
        if let Some(handle) = &handle {
            toggle = toggle.track_focus(handle);
        }
        let mut row = div()
            .id(item_id.clone())
            .test_support()
            .role(Role::ListItem)
            .overflow_hidden()
            .opacity(presence.progress)
            .rounded(N::ITEM_RADIUS)
            .p(N::ITEM_PAD)
            .flex_none()
            .w_full()
            .flex()
            .flex_col()
            .when(expanded, |d| d.bg(colors.surface_muted))
            .hover(|s| s.bg(colors.surface_muted))
            .child(
                div()
                    .id(child_id(&item_id, "main"))
                    .test_support()
                    .w_full()
                    .min_w(px(0.0))
                    .flex()
                    .items_start()
                    .gap(N::VISUAL_GAP)
                    .child(visual(&item, &item_id, cx))
                    .child(toggle)
                    .child(
                        div()
                            .flex_none()
                            .pt(Spacing::S1)
                            .text_size(Typography::TEXT_XS)
                            .text_color(colors.text_muted)
                            .child(item.time.clone()),
                    ),
            );
        let detail_h = arc_spring(
            (item_id.clone(), "details-height"),
            if expanded { 1.0 } else { 0.0 },
            motion.spring.smooth,
            window,
            cx,
        )
        .clamp(0.0, 1.0);
        if detail_h > 0.001 {
            let st = state.clone();
            let entry = item.clone();
            let cb = read.clone();
            let st_remove = state.clone();
            let removed = item.clone();
            let on_dismiss = dismiss.clone();
            let after_read = neighbor.clone().unwrap_or_else(|| unread_tab.clone());
            let after_remove = neighbor.clone().unwrap_or_else(|| unread_tab.clone());
            let details = div()
                .id(child_id(&item_id, "details"))
                .test_support()
                .w_full()
                .pl(N::DETAILS_INDENT)
                .overflow_hidden()
                .opacity(detail_h)
                .child(text(item.body(), cx).my(Spacing::S3))
                .child(
                    div()
                        .flex()
                        .flex_wrap()
                        .gap(N::DOT)
                        .pb(Spacing::S1)
                        .child(
                            Button::new(child_id(&item_id, "read"))
                                .label(if item.read {
                                    "Mark unread"
                                } else {
                                    "Mark read"
                                })
                                .size(ButtonSize::Sm)
                                .variant(ButtonVariant::Secondary)
                                .icon(if item.read {
                                    IconName::CircleDot
                                } else {
                                    IconName::Check
                                })
                                .disabled(!present || !expanded)
                                .on_click(move |_, w, cx| {
                                    st.update(cx, |s, _| {
                                        if let Some(i) =
                                            s.items.iter_mut().find(|i| i.id == entry.id)
                                        {
                                            i.read = !entry.read
                                        }
                                        if s.unread_only {
                                            s.expanded = None
                                        }
                                    });
                                    if let Some(cb) = &cb {
                                        cb(&entry, !entry.read, w, cx)
                                    }
                                    // 仅取消未读时需要把焦点交给下一条,避免落回文档。
                                    if !entry.read {
                                        w.focus(&after_read, cx);
                                    }
                                    w.refresh();
                                }),
                        )
                        .child(
                            Button::new(child_id(&item_id, "dismiss"))
                                .label("Dismiss")
                                .icon(IconName::Close)
                                .accessibility_label(format!("Dismiss {}", item.title))
                                .size(ButtonSize::Sm)
                                .variant(ButtonVariant::Secondary)
                                .disabled(!present || !expanded)
                                .on_click(move |_, w, cx| {
                                    st_remove.update(cx, |s, _| {
                                        s.items.retain(|i| i.id != removed.id);
                                        s.expanded = None
                                    });
                                    if let Some(cb) = &on_dismiss {
                                        cb(&removed, w, cx)
                                    }
                                    w.focus(&after_remove, cx);
                                    w.refresh();
                                }),
                        ),
                );
            row = row.child(MotionReveal::new(
                child_id(&item_id, "details-reveal"),
                detail_h,
                details.into_any_element(),
            ));
        }
        rows = rows.child(MotionReveal::new(
            child_id(&item_id, "reveal"),
            presence.progress,
            row.into_any_element(),
        ));
    }
    state.update(cx, |s, _| s.retained = keep);
    if visible.is_empty() {
        let st = state.clone();
        rows = rows.child(
            div()
                .id(child_id(id, "empty"))
                .test_support()
                .flex()
                .flex_col()
                .items_center()
                .gap(Spacing::S2)
                .min_h(N::EMPTY)
                .justify_center()
                .p(Spacing::S6)
                .child(notification_icon(
                    IconName::CircleCheck,
                    Spacing::S6,
                    colors.text_muted,
                ))
                .child(div().text_size(Typography::TEXT_SM).font_medium().child(
                    if snap.unread_only {
                        "Nothing unread"
                    } else {
                        "All clear"
                    },
                ))
                .child(
                    div()
                        .text_color(colors.text_muted)
                        .child(if snap.unread_only {
                            "You’ve seen every update."
                        } else {
                            "New updates will appear here."
                        }),
                )
                .when(snap.unread_only && !snap.items.is_empty(), |d| {
                    d.child(
                        Button::new(child_id(id, "view-all"))
                            .label("View all updates")
                            .size(ButtonSize::Sm)
                            .variant(ButtonVariant::Secondary)
                            .on_click(move |_, w, cx| {
                                st.update(cx, |s, _| s.unread_only = false);
                                w.refresh()
                            }),
                    )
                }),
        );
    }
    root = root.child(rows);
    if read_count > 0 {
        let st = state.clone();
        let cb = dismiss;
        let focus_target = all_tab;
        root = root.child(
            div()
                .flex_none()
                .min_h(N::FOOTER)
                .px(N::FOOTER_X)
                .py(Spacing::S2)
                .border_t_1()
                .border_color(colors.border_subtle)
                .text_size(Typography::TEXT_XS)
                .flex()
                .justify_between()
                .items_center()
                .child(
                    div()
                        .flex()
                        .items_center()
                        .gap(Spacing::S1)
                        .text_color(colors.text_muted)
                        .child(rolling_count(
                            child_id(id, "read-roll"),
                            read_count,
                            false,
                            window,
                            cx,
                        ))
                        .child("read"),
                )
                .child(
                    BaseButton::new(child_id(id, "clear-read"))
                        .accessibility_label("Clear read")
                        .py(Spacing::S1)
                        .text_size(Typography::TEXT_XS)
                        .text_color(colors.text_secondary)
                        .hover(|s| s.text_color(colors.foreground))
                        .child("Clear read")
                        .on_click(move |_, w, cx| {
                            let removed = st
                                .read(cx)
                                .items
                                .iter()
                                .filter(|i| i.read)
                                .cloned()
                                .collect::<Vec<_>>();
                            st.update(cx, |s, _| {
                                s.items.retain(|i| !i.read);
                                s.expanded = None
                            });
                            if let Some(cb) = &cb {
                                for i in &removed {
                                    cb(i, w, cx)
                                }
                            }
                            w.focus(&focus_target, cx);
                            w.refresh();
                        }),
                ),
        );
    }
    root.into_any_element()
}
#[cfg(test)]
mod tests {
    use super::*;
    use gpui_kit::point;

    fn bounds(x: f32, y: f32, w: f32, h: f32) -> Bounds<Pixels> {
        Bounds {
            origin: point(px(x), px(y)),
            size: size(px(w), px(h)),
        }
    }
    #[test]
    fn svg_icons_have_explicit_theme_color_and_fixed_size() {
        for mode in [arc_tokens::ThemeMode::Light, arc_tokens::ThemeMode::Dark] {
            let colors = arc_tokens::ArcTheme::new(mode, arc_tokens::Accent::Violet).colors;
            for (name, size, color) in [
                (IconName::Bell, N::BELL, colors.foreground),
                (IconName::MessageCircle, N::EVENT_ICON, colors.accent),
                (IconName::TriangleAlert, N::EVENT_ICON, colors.warning),
                (IconName::CircleCheck, N::EVENT_ICON, colors.success),
                (IconName::Close, Spacing::S4, colors.text_muted),
                (IconName::CheckCheck, Spacing::S4, colors.text_secondary),
            ] {
                let mut icon = notification_icon(name, size, color);
                let style = icon.style();
                // 原始 Svg::paint 直接读取此字段,不会回退到父级 text_style。
                assert_eq!(style.text.color, Some(color));
                assert!(color.a > 0.0);
                assert_eq!(style.size.width, Some(size.into()));
                assert_eq!(style.size.height, Some(size.into()));
            }
        }
    }

    #[test]
    fn defaults_match_upstream() {
        let i = NotificationItem::new("a", "Ready", "now");
        assert!(!i.read);
        assert_eq!(i.tone, NotificationTone::Info);
        assert!(i.actor.is_none());
        assert_eq!(i.preview(), "View update details");
        assert_eq!(i.body(), "This update is ready to review.");
    }
    #[test]
    fn actor_copy_matches_upstream() {
        let i = NotificationItem::new("a", "Ready", "now").actor("Emma", "/emma.svg");
        assert_eq!(i.preview(), "From Emma");
        assert_eq!(i.body(), "Emma shared an update with you.");
        let described = i.description("Full text");
        assert_eq!(described.preview(), "Full text");
        assert_eq!(described.body(), "Full text");
    }
    #[test]
    fn placement_stays_below_right_when_space_is_enough() {
        let trigger = bounds(400.0, 40.0, 120.0, 32.0);
        let panel = size(px(424.0), px(300.0));
        let viewport = size(px(1024.0), px(768.0));
        assert_eq!(
            resolve_placement(trigger, panel, viewport, true),
            (false, false)
        );
    }
    #[test]
    fn placement_flips_above_when_bottom_space_is_tight() {
        // 下方仅剩 200px,面板 300px 放不下;上方 620px 更宽裕 → 翻到上方。
        let trigger = bounds(400.0, 568.0, 120.0, 32.0);
        let panel = size(px(424.0), px(300.0));
        let viewport = size(px(1024.0), px(800.0));
        assert_eq!(
            resolve_placement(trigger, panel, viewport, true),
            (true, false)
        );
    }
    #[test]
    fn placement_keeps_below_when_top_space_is_not_better() {
        // 下方放不下(278px < 312px),但上方 100px 并不更大,保持下方由 max_h 兜底。
        let trigger = bounds(400.0, 100.0, 120.0, 32.0);
        let panel = size(px(424.0), px(300.0));
        let viewport = size(px(1024.0), px(410.0));
        assert_eq!(
            resolve_placement(trigger, panel, viewport, true),
            (false, false)
        );
    }
    #[test]
    fn placement_aligns_left_when_trigger_hugs_the_left_edge() {
        let trigger = bounds(0.0, 40.0, 120.0, 32.0);
        let panel = size(px(424.0), px(300.0));
        let viewport = size(px(1024.0), px(768.0));
        assert_eq!(
            resolve_placement(trigger, panel, viewport, true),
            (false, true)
        );
    }
    #[test]
    fn placement_respects_avoid_collisions_disabled() {
        let trigger = bounds(400.0, 568.0, 120.0, 32.0);
        let panel = size(px(424.0), px(300.0));
        let viewport = size(px(1024.0), px(800.0));
        assert_eq!(
            resolve_placement(trigger, panel, viewport, false),
            (false, false)
        );
    }
}