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
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Source: `Arc源码/arc-library/registry/components/announcement-bar/announcement-bar.tsx` & `announcement-bar.module.css`
//!
//! A slim top-of-page announcement bar (`announcement-bar`):
//! - Rotates multiple messages vertically (next rises from below and leaves upward; previous runs
//!   the reverse), with a `20x20` circular progress ring (`r=8`) that acts as the live auto-play
//!   clock and pauses cleanly on hover, focus, or user pause toggle.
//! - Each announcement supports an optional inline call-to-action button (with right-pointing arrow)
//!   and a live compact `d h:m:s` countdown timer (`announcement_countdown_parts`) that ticks down
//!   every second and fires `on_countdown_end` once at zero.
//! - Supports `AnnouncementBarTone::Neutral` (`surface_muted` + bottom border) and `Inverted`
//!   (`foreground` background + `background` text).
//! - Dismissing collapses the bar smoothly via `motion.spring.smooth` and can remember dismissal
//!   in memory by campaign `storage_id` (clearable via `clear_announcement_dismissal`).

use std::{
    cell::RefCell,
    collections::HashSet,
    rc::Rc,
    sync::{Mutex, OnceLock},
    time::{SystemTime, UNIX_EPOCH},
};

use arc_motion::{arc_spring, is_reduced_motion, motion_now};
use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, SpringSpec, Typography, oklab_mix};
use gpui_kit::{
    AnyElement, App, Bounds, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
    ParentElement, PathBuilder, Pixels, RenderOnce, Role, SharedString, Styled,
    TestSupportExt as _, Window, assets::IconName, base::StyledExt as _, canvas, div, point,
    prelude::*, px, svg,
};

type OpenChangeCallback = Rc<dyn Fn(&bool, &mut Window, &mut App)>;
type IndexChangeCallback = Rc<dyn Fn(&usize, &mut Window, &mut App)>;
type AnnouncementCallback = Rc<dyn Fn(&Announcement, &mut Window, &mut App)>;
type ActionClickCallback = Rc<dyn Fn(&mut Window, &mut App)>;

/// Default auto-rotation interval (`6.0s`, matching `interval = 6000` in `announcement-bar.tsx`).
pub const ANNOUNCEMENT_DEFAULT_INTERVAL_SECS: f64 = 6.0;

fn dismissed_registry() -> &'static Mutex<HashSet<String>> {
    static REGISTRY: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();
    REGISTRY.get_or_init(|| Mutex::new(HashSet::new()))
}

/// Remembers an announcement campaign `id` as dismissed in process storage.
pub fn remember_announcement_dismissal(id: &str) {
    if let Ok(mut set) = dismissed_registry().lock() {
        set.insert(id.to_string());
    }
}

/// Checks whether an announcement campaign `id` was previously dismissed.
pub fn is_announcement_dismissed(id: &str) -> bool {
    dismissed_registry()
        .lock()
        .map(|set| set.contains(id))
        .unwrap_or(false)
}

/// Forgets a remembered dismissal so the bar with `id` shows again (`clearAnnouncementDismissal`).
pub fn clear_announcement_dismissal(id: &str) {
    if let Ok(mut set) = dismissed_registry().lock() {
        set.remove(id);
    }
}

/// Visual surface tone of [`AnnouncementBar`].
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
pub enum AnnouncementBarTone {
    #[default]
    Neutral,
    Inverted,
}

/// Optional call-to-action link/button inside an [`Announcement`].
#[derive(Clone)]
pub struct AnnouncementAction {
    pub label: SharedString,
    pub on_click: Option<ActionClickCallback>,
}

impl AnnouncementAction {
    pub fn new(label: impl Into<SharedString>) -> Self {
        Self {
            label: label.into(),
            on_click: None,
        }
    }

    pub fn on_click(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
        self.on_click = Some(Rc::new(handler));
        self
    }
}

/// Optional countdown attached to an [`Announcement`].
#[derive(Clone, Debug, PartialEq)]
pub struct AnnouncementCountdown {
    /// Target Unix epoch timestamp in seconds.
    pub target_epoch_secs: f64,
    pub label: Option<SharedString>,
}

impl AnnouncementCountdown {
    pub fn from_epoch_secs(target_epoch_secs: f64) -> Self {
        Self {
            target_epoch_secs,
            label: None,
        }
    }

    /// Creates a countdown targeting `remaining_secs` from the current wall clock time.
    pub fn from_remaining_secs(remaining_secs: f64) -> Self {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_secs_f64())
            .unwrap_or(0.0);
        Self {
            target_epoch_secs: now + remaining_secs.max(0.0),
            label: None,
        }
    }

    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
        self.label = Some(label.into());
        self
    }
}

/// Single rotating message entry for [`AnnouncementBar`].
#[derive(Clone)]
pub struct Announcement {
    pub id: SharedString,
    pub message: SharedString,
    pub action: Option<AnnouncementAction>,
    pub countdown: Option<AnnouncementCountdown>,
}

impl Announcement {
    pub fn new(id: impl Into<SharedString>, message: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            message: message.into(),
            action: None,
            countdown: None,
        }
    }

    pub fn action(mut self, action: AnnouncementAction) -> Self {
        self.action = Some(action);
        self
    }

    pub fn countdown(mut self, countdown: AnnouncementCountdown) -> Self {
        self.countdown = Some(countdown);
        self
    }
}

/// Decomposed `(days, hours, minutes, seconds)` returned by [`announcement_countdown_parts`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct AnnouncementCountdownParts {
    pub days: u64,
    pub hours: u64,
    pub minutes: u64,
    pub seconds: u64,
}

/// Splits remaining seconds into `(days, hours, minutes, seconds)` matching `parts(ms)` in
/// `announcement-bar.tsx`.
#[inline]
pub fn announcement_countdown_parts(remaining_secs: f64) -> AnnouncementCountdownParts {
    let total = remaining_secs.max(0.0).floor() as u64;
    AnnouncementCountdownParts {
        days: total / 86_400,
        hours: (total % 86_400) / 3_600,
        minutes: (total % 3_600) / 60,
        seconds: total % 60,
    }
}

/// Wraps a step delta (`+1` or `-1`) cleanly across `0..total`.
#[inline]
pub fn announcement_wrap_index(current: usize, delta: isize, total: usize) -> usize {
    if total == 0 {
        return 0;
    }
    let t = total as isize;
    (((current as isize + delta) % t + t) % t) as usize
}

/// Formats [`AnnouncementCountdownParts`] into compact `2d 04:15:09` or `04:15:09`.
pub fn format_announcement_countdown(parts: AnnouncementCountdownParts) -> String {
    if parts.days > 0 {
        format!(
            "{}d {:02}:{:02}:{:02}",
            parts.days, parts.hours, parts.minutes, parts.seconds
        )
    } else {
        format!(
            "{:02}:{:02}:{:02}",
            parts.hours, parts.minutes, parts.seconds
        )
    }
}

#[derive(Clone)]
struct AnnouncementInternalState {
    open: bool,
    index: usize,
    prev_index: Option<usize>,
    direction: i8,
    user_paused: bool,
    hovered: bool,
    progress: f64,
    last_tick_at: f64,
    slide_started_at: f64,
    ended_countdowns: HashSet<SharedString>,
    measured_viewport_height: Rc<RefCell<Option<f32>>>,
    measured_bar_height: Rc<RefCell<f32>>,
    focus_handle: FocusHandle,
}

/// Slim rotating announcement banner (`announcement-bar`).
#[derive(IntoElement)]
pub struct AnnouncementBar {
    id: ElementId,
    messages: Vec<Announcement>,
    storage_id: Option<SharedString>,
    open_override: Option<bool>,
    default_open: bool,
    index_override: Option<usize>,
    default_index: usize,
    interval_secs: f64,
    auto_play: bool,
    controls: bool,
    dismissible: bool,
    tone: AnnouncementBarTone,
    top_radius: Option<Pixels>,
    radius: Option<Pixels>,
    on_open_change: Option<OpenChangeCallback>,
    on_index_change: Option<IndexChangeCallback>,
    on_action: Option<AnnouncementCallback>,
    on_countdown_end: Option<AnnouncementCallback>,
}

impl AnnouncementBar {
    pub fn new(id: impl Into<ElementId>, messages: impl IntoIterator<Item = Announcement>) -> Self {
        Self {
            id: id.into(),
            messages: messages.into_iter().collect(),
            storage_id: None,
            open_override: None,
            default_open: true,
            index_override: None,
            default_index: 0,
            interval_secs: ANNOUNCEMENT_DEFAULT_INTERVAL_SECS,
            auto_play: true,
            controls: false,
            dismissible: true,
            tone: AnnouncementBarTone::Neutral,
            top_radius: None,
            radius: None,
            on_open_change: None,
            on_index_change: None,
            on_action: None,
            on_countdown_end: None,
        }
    }

    /// Rounds the top-left and top-right corners (useful when embedded at the top of a rounded
    /// surface card in GPUI, where `overflow_hidden` clips to an axis-aligned rectangle).
    pub fn rounded_top(mut self, radius: impl Into<Pixels>) -> Self {
        self.top_radius = Some(radius.into());
        self
    }

    /// Rounds all four corners of the announcement bar (for standalone / floating pill usage).
    pub fn rounded(mut self, radius: impl Into<Pixels>) -> Self {
        self.radius = Some(radius.into());
        self
    }

    pub fn storage_id(mut self, storage_id: impl Into<SharedString>) -> Self {
        self.storage_id = Some(storage_id.into());
        self
    }

    pub fn open(mut self, open: bool) -> Self {
        self.open_override = Some(open);
        self
    }

    pub fn default_open(mut self, default_open: bool) -> Self {
        self.default_open = default_open;
        self
    }

    pub fn index(mut self, index: usize) -> Self {
        self.index_override = Some(index);
        self
    }

    pub fn default_index(mut self, default_index: usize) -> Self {
        self.default_index = default_index;
        self
    }

    pub fn interval_secs(mut self, interval_secs: f64) -> Self {
        self.interval_secs = interval_secs.max(1.0);
        self
    }

    pub fn auto_play(mut self, auto_play: bool) -> Self {
        self.auto_play = auto_play;
        self
    }

    pub fn controls(mut self, controls: bool) -> Self {
        self.controls = controls;
        self
    }

    pub fn dismissible(mut self, dismissible: bool) -> Self {
        self.dismissible = dismissible;
        self
    }

    pub fn tone(mut self, tone: AnnouncementBarTone) -> Self {
        self.tone = tone;
        self
    }

    pub fn on_open_change(
        mut self,
        handler: impl Fn(&bool, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_open_change = Some(Rc::new(handler));
        self
    }

    pub fn on_index_change(
        mut self,
        handler: impl Fn(&usize, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_index_change = Some(Rc::new(handler));
        self
    }

    pub fn on_action(
        mut self,
        handler: impl Fn(&Announcement, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_action = Some(Rc::new(handler));
        self
    }

    pub fn on_countdown_end(
        mut self,
        handler: impl Fn(&Announcement, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_countdown_end = Some(Rc::new(handler));
        self
    }
}

fn paint_timer_ring(
    bounds: Bounds<gpui_kit::Pixels>,
    progress: f32,
    is_paused: bool,
    track_color: Hsla,
    fill_color: Hsla,
    window: &mut Window,
) {
    let cx = bounds.origin.x + bounds.size.width * 0.5;
    let cy = bounds.origin.y + bounds.size.height * 0.5;
    let scale = (bounds.size.width / px(20.0)).min(bounds.size.height / px(20.0));
    let r = 8.0 * scale;
    let stroke_w = px(1.75 * scale);

    let segments = 40;
    let mut track = PathBuilder::stroke(stroke_w);
    for i in 0..=segments {
        let a = (i as f32 / segments as f32) * std::f32::consts::TAU;
        let p = point(cx + px(r * a.cos()), cy + px(r * a.sin()));
        if i == 0 {
            track.move_to(p);
        } else {
            track.line_to(p);
        }
    }
    if let Ok(path) = track.build() {
        window.paint_path(path, track_color);
    }

    let clamped = progress.clamp(0.0, 1.0);
    if clamped > 0.01 {
        let active_segs = ((segments as f32 * clamped).ceil() as usize).max(2);
        let mut fill = PathBuilder::stroke(stroke_w);
        for i in 0..=active_segs {
            let frac = (i as f32 / active_segs as f32) * clamped;
            let a = -std::f32::consts::FRAC_PI_2 + frac * std::f32::consts::TAU;
            let p = point(cx + px(r * a.cos()), cy + px(r * a.sin()));
            if i == 0 {
                fill.move_to(p);
            } else {
                fill.line_to(p);
            }
        }
        if let Ok(path) = fill.build() {
            window.paint_path(path, fill_color);
        }
    }

    // Crisp vector Play / Pause glyph inside the ring (exact center, matches 9x9 lucide icon)
    if is_paused {
        // Right-pointing triangle slightly optically nudged +0.6px right
        let mut play = PathBuilder::fill();
        play.move_to(point(cx - px(2.1 * scale), cy - px(3.0 * scale)));
        play.line_to(point(cx + px(3.2 * scale), cy));
        play.line_to(point(cx - px(2.1 * scale), cy + px(3.0 * scale)));
        play.close();
        if let Ok(path) = play.build() {
            window.paint_path(path, fill_color);
        }
    } else {
        // Two symmetric vertical pause bars
        let bar_w = px(1.5 * scale);
        let bar_h = 2.8 * scale;
        let bar_offset = 1.65 * scale;
        for sign in [-1.0_f32, 1.0_f32] {
            let x = cx + px(sign * bar_offset);
            let mut bar = PathBuilder::stroke(bar_w);
            bar.move_to(point(x, cy - px(bar_h)));
            bar.line_to(point(x, cy + px(bar_h)));
            if let Ok(path) = bar.build() {
                window.paint_path(path, fill_color);
            }
        }
    }
}

impl RenderOnce for AnnouncementBar {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        if self.messages.is_empty() {
            return div().into_any_element();
        }

        let (colors, _motion) = {
            let theme = cx.arc_theme();
            (theme.colors, theme.motion)
        };
        let reduced = is_reduced_motion(cx);
        let now = motion_now(cx);
        let total = self.messages.len();

        let remembered_dismissed = self
            .storage_id
            .as_ref()
            .map(|sid| is_announcement_dismissed(sid.as_ref()))
            .unwrap_or(false);
        let init_open = self.default_open && !remembered_dismissed;
        let init_idx = announcement_wrap_index(self.default_index, 0, total);

        let state_cell = window
            .use_keyed_state((self.id.clone(), "announcement-bar-state"), cx, |_, cx| {
                Rc::new(RefCell::new(AnnouncementInternalState {
                    open: init_open,
                    index: init_idx,
                    prev_index: None,
                    direction: 1,
                    user_paused: false,
                    hovered: false,
                    progress: 0.0,
                    last_tick_at: now,
                    slide_started_at: now - 1.0,
                    ended_countdowns: HashSet::new(),
                    measured_viewport_height: Rc::new(RefCell::new(None)),
                    measured_bar_height: Rc::new(RefCell::new(48.0)),
                    focus_handle: cx.focus_handle(),
                }))
            })
            .read(cx)
            .clone();

        let rotating = self.auto_play && !reduced && total > 1;
        let mut index_advanced_to: Option<usize> = None;
        let mut countdown_ended_item: Option<Announcement> = None;
        let mut request_anim = false;

        let wall_now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_secs_f64())
            .unwrap_or(0.0);

        {
            let mut st = state_cell.borrow_mut();
            if let Some(ext_open) = self.open_override {
                st.open = ext_open;
            } else if remembered_dismissed {
                st.open = false;
            }
            if let Some(ext_idx) = self.index_override {
                let wrapped = announcement_wrap_index(ext_idx, 0, total);
                if st.index != wrapped {
                    st.prev_index = Some(st.index);
                    st.index = wrapped;
                    st.progress = 0.0;
                    st.slide_started_at = now;
                }
            }
            let current_idx = announcement_wrap_index(st.index, 0, total);
            st.index = current_idx;

            let running = rotating && st.open && !st.user_paused && !st.hovered;
            let dt = (now - st.last_tick_at).clamp(0.0, 0.25);
            st.last_tick_at = now;

            if running {
                st.progress += dt / self.interval_secs;
                if st.progress >= 1.0 {
                    st.progress = 0.0;
                    st.direction = 1;
                    let next = announcement_wrap_index(current_idx, 1, total);
                    st.prev_index = Some(current_idx);
                    st.index = next;
                    st.slide_started_at = now;
                    index_advanced_to = Some(next);
                }
                request_anim = true;
            }

            // Check live countdown on current message
            if st.open
                && let Some(current_msg) = self.messages.get(st.index)
                && let Some(ref cd) = current_msg.countdown
            {
                let rem = cd.target_epoch_secs - wall_now;
                if rem <= 0.0 {
                    if !st.ended_countdowns.contains(&current_msg.id) {
                        st.ended_countdowns.insert(current_msg.id.clone());
                        countdown_ended_item = Some(current_msg.clone());
                    }
                } else {
                    request_anim = true;
                }
            }

            if now - st.slide_started_at < 0.48 {
                request_anim = true;
            } else {
                st.prev_index = None;
            }
        }

        if let Some(next_idx) = index_advanced_to
            && let Some(cb) = self.on_index_change.clone()
        {
            window.defer(cx, move |window, cx| {
                cb(&next_idx, window, cx);
            });
        }
        if let Some(ended_msg) = countdown_ended_item
            && let Some(cb) = self.on_countdown_end.clone()
        {
            window.defer(cx, move |window, cx| {
                cb(&ended_msg, window, cx);
            });
        }
        if request_anim {
            window.request_animation_frame();
        }

        let snapshot = state_cell.borrow().clone();
        let open_target = if snapshot.open { 1.0 } else { 0.0 };
        let open_scale = if reduced {
            open_target
        } else {
            arc_spring(
                (self.id.clone(), "open-collapse"),
                open_target,
                SpringSpec::visual(0.44, 0.0),
                window,
                cx,
            )
        };

        if !snapshot.open && open_scale < 0.015 {
            return div().into_any_element();
        }

        let current_msg = &self.messages[snapshot.index];
        let (bar_bg, fg_color, muted_color, border_color, hover_btn_bg) = match self.tone {
            AnnouncementBarTone::Neutral => (
                colors.surface_muted,
                colors.foreground,
                colors.text_secondary,
                colors.border,
                oklab_mix(colors.foreground, colors.surface_muted, 0.10),
            ),
            AnnouncementBarTone::Inverted => (
                colors.foreground,
                colors.background,
                colors.background.opacity(0.68),
                gpui_kit::transparent_black(),
                oklab_mix(colors.background, colors.foreground, 0.14),
            ),
        };

        // Smooth ease-out vertical slide transition for incoming/outgoing announcement faces.
        // Both faces are positioned absolutely inside a height-stabilized `overflow_hidden()`
        // viewport (matching upstream `.viewport` + `.face { position: absolute }`) so vertical
        // motion never alters document flow height or causes jitter below the banner.
        let raw_slide = if reduced {
            1.0_f32
        } else {
            ((now - snapshot.slide_started_at) / 0.36).clamp(0.0, 1.0) as f32
        };
        let eased_slide = 1.0 - (1.0 - raw_slide).powi(3);
        let slide_y = (1.0 - eased_slide) * 16.0 * snapshot.direction as f32;
        let outgoing_y = -eased_slide * 14.0 * snapshot.direction as f32;
        let outgoing_alpha = ((1.0 - eased_slide * 1.4).clamp(0.0, 1.0)) as f32;

        let build_message_row = |msg: &Announcement, interactive: bool| -> AnyElement {
            let countdown_el: Option<AnyElement> = msg.countdown.as_ref().map(|cd| {
                let rem = (cd.target_epoch_secs - wall_now).max(0.0);
                let formatted = format_announcement_countdown(announcement_countdown_parts(rem));
                div()
                    .flex()
                    .items_center()
                    .gap(px(6.0))
                    .text_size(Typography::TEXT_SM)
                    .when_some(cd.label.clone(), |el, lbl| {
                        el.child(div().text_color(muted_color).child(lbl))
                    })
                    .child(div().font_medium().text_color(fg_color).child(formatted))
                    .into_any_element()
            });

            let cta_el: Option<AnyElement> = msg.action.as_ref().map(|act| {
                let label = act.label.clone();
                let act_click = act.on_click.clone();
                let on_action_cb = self.on_action.clone();
                let msg_clone = msg.clone();
                let btn = div()
                    .id((
                        self.id.clone(),
                        format!(
                            "cta-{}-{}",
                            if interactive { "cur" } else { "prev" },
                            msg.id
                        ),
                    ))
                    .flex()
                    .items_center()
                    .gap(px(4.0))
                    .text_size(Typography::TEXT_SM)
                    .font_medium()
                    .text_color(fg_color)
                    .child(label)
                    .child(
                        svg()
                            .path(IconName::ArrowRight.path())
                            .size(px(14.0))
                            .text_color(fg_color),
                    );
                if interactive {
                    btn.cursor_pointer()
                        .hover(|s| s.opacity(0.82))
                        .on_mouse_down(MouseButton::Left, move |_, window, cx| {
                            if let Some(ref f) = act_click {
                                f(window, cx);
                            }
                            if let Some(ref cb) = on_action_cb {
                                cb(&msg_clone, window, cx);
                            }
                        })
                        .into_any_element()
                } else {
                    btn.into_any_element()
                }
            });

            div()
                .w_full()
                .min_h(px(32.0))
                .py(px(4.0))
                .flex()
                .flex_wrap()
                .items_center()
                .justify_center()
                .gap(Spacing::S3)
                .text_size(Typography::TEXT_SM)
                .child(div().child(msg.message.clone()))
                .when_some(countdown_el, |el, cd| el.child(cd))
                .when_some(cta_el, |el, cta| el.child(cta))
                .into_any_element()
        };

        let outgoing_face: Option<AnyElement> = if !reduced && outgoing_alpha > 0.02 {
            snapshot
                .prev_index
                .filter(|&pi| pi != snapshot.index && pi < self.messages.len())
                .map(|pi| {
                    div()
                        .absolute()
                        .left_0()
                        .right_0()
                        .top(px(outgoing_y))
                        .opacity(outgoing_alpha)
                        .flex()
                        .items_center()
                        .justify_center()
                        .child(build_message_row(&self.messages[pi], false))
                        .into_any_element()
                })
        } else {
            None
        };

        // Controls cluster (Prev, Ring Pause/Play, Next, Close)
        let navigable = self.controls && total > 1;
        let mut control_items: Vec<AnyElement> = Vec::new();

        if navigable {
            let state_prev = state_cell.clone();
            let on_idx_prev = self.on_index_change.clone();
            control_items.push(
                div()
                    .id((self.id.clone(), "ctrl-prev"))
                    .w(px(30.0))
                    .h(px(30.0))
                    .rounded_full()
                    .flex()
                    .items_center()
                    .justify_center()
                    .cursor_pointer()
                    .hover(move |s| s.bg(hover_btn_bg))
                    .on_mouse_down(MouseButton::Left, move |_, window, cx| {
                        let t_now = motion_now(cx);
                        let next_idx = {
                            let mut st = state_prev.borrow_mut();
                            let prev = st.index;
                            let next = announcement_wrap_index(prev, -1, total);
                            st.prev_index = Some(prev);
                            st.index = next;
                            st.direction = -1;
                            st.progress = 0.0;
                            st.slide_started_at = t_now;
                            next
                        };
                        if let Some(ref cb) = on_idx_prev {
                            cb(&next_idx, window, cx);
                        }
                        window.refresh();
                    })
                    .child(
                        svg()
                            .path(IconName::ChevronUp.path())
                            .size(px(14.0))
                            .text_color(muted_color),
                    )
                    .into_any_element(),
            );

            if rotating {
                let state_pause = state_cell.clone();
                let ring_progress = snapshot.progress as f32;
                let ring_track = fg_color.opacity(0.22);
                let ring_fill = fg_color;
                let is_paused = snapshot.user_paused;

                control_items.push(
                    div()
                        .id((self.id.clone(), "ctrl-pause"))
                        .w(px(30.0))
                        .h(px(30.0))
                        .rounded_full()
                        .flex()
                        .items_center()
                        .justify_center()
                        .cursor_pointer()
                        .hover(move |s| s.bg(hover_btn_bg))
                        .on_mouse_down(MouseButton::Left, move |_, window, _| {
                            {
                                let mut st = state_pause.borrow_mut();
                                st.user_paused = !st.user_paused;
                            }
                            window.refresh();
                        })
                        .child(
                            div().w(px(20.0)).h(px(20.0)).child(
                                canvas(
                                    move |_, _, _| {},
                                    move |bounds, _, window, _| {
                                        paint_timer_ring(
                                            bounds,
                                            ring_progress,
                                            is_paused,
                                            ring_track,
                                            ring_fill,
                                            window,
                                        );
                                    },
                                )
                                .size_full(),
                            ),
                        )
                        .into_any_element(),
                );
            }

            let state_next = state_cell.clone();
            let on_idx_next = self.on_index_change.clone();
            control_items.push(
                div()
                    .id((self.id.clone(), "ctrl-next"))
                    .w(px(30.0))
                    .h(px(30.0))
                    .rounded_full()
                    .flex()
                    .items_center()
                    .justify_center()
                    .cursor_pointer()
                    .hover(move |s| s.bg(hover_btn_bg))
                    .on_mouse_down(MouseButton::Left, move |_, window, cx| {
                        let t_now = motion_now(cx);
                        let next_idx = {
                            let mut st = state_next.borrow_mut();
                            let prev = st.index;
                            let next = announcement_wrap_index(prev, 1, total);
                            st.prev_index = Some(prev);
                            st.index = next;
                            st.direction = 1;
                            st.progress = 0.0;
                            st.slide_started_at = t_now;
                            next
                        };
                        if let Some(ref cb) = on_idx_next {
                            cb(&next_idx, window, cx);
                        }
                        window.refresh();
                    })
                    .child(
                        svg()
                            .path(IconName::ChevronDown.path())
                            .size(px(14.0))
                            .text_color(muted_color),
                    )
                    .into_any_element(),
            );
        }

        if self.dismissible {
            let state_dismiss = state_cell.clone();
            let sid = self.storage_id.clone();
            let on_open_cb = self.on_open_change.clone();
            control_items.push(
                div()
                    .id((self.id.clone(), "ctrl-dismiss"))
                    .w(px(30.0))
                    .h(px(30.0))
                    .rounded_full()
                    .flex()
                    .items_center()
                    .justify_center()
                    .cursor_pointer()
                    .hover(move |s| s.bg(hover_btn_bg))
                    .on_mouse_down(MouseButton::Left, move |_, window, cx| {
                        if let Some(ref storage_key) = sid {
                            remember_announcement_dismissal(storage_key.as_ref());
                        }
                        {
                            let mut st = state_dismiss.borrow_mut();
                            st.open = false;
                        }
                        if let Some(ref cb) = on_open_cb {
                            cb(&false, window, cx);
                        }
                        window.refresh();
                    })
                    .child(
                        svg()
                            .path(IconName::Close.path())
                            .size(px(14.0))
                            .text_color(muted_color),
                    )
                    .into_any_element(),
            );
        }

        let control_count = control_items.len();
        let mirror_width = if control_count > 0 {
            control_count as f32 * 30.0 + (control_count.saturating_sub(1)) as f32 * 2.0
        } else {
            0.0
        };

        let hover_state = state_cell.clone();
        let key_state = state_cell.clone();
        let on_idx_key = self.on_index_change.clone();
        let focus_handle = snapshot.focus_handle.clone();

        let bar_h_ref = snapshot.measured_bar_height.clone();
        let natural_bar_h = {
            let h = *bar_h_ref.borrow();
            if h > 24.0 { h } else { 48.0 }
        };
        let measure_bar_ref = bar_h_ref.clone();

        let mut bar_surface = div()
            .w_full()
            .bg(bar_bg)
            .text_color(fg_color)
            .border_b_1()
            .border_color(border_color)
            .px(Spacing::S4)
            .py(px(6.0))
            .flex()
            .items_center()
            .justify_between()
            .gap(Spacing::S3);

        if let Some(r) = self.radius {
            bar_surface = bar_surface.rounded(r);
        } else if let Some(tr) = self.top_radius {
            bar_surface = bar_surface.rounded_tl(tr).rounded_tr(tr);
        } else {
            bar_surface = bar_surface
                .rounded_tl(Radii::PANEL)
                .rounded_tr(Radii::PANEL);
        }

        let vp_h_ref = snapshot.measured_viewport_height.clone();
        let target_vp_h = vp_h_ref.borrow().map(|h| h.max(32.0));
        let animated_vp_h = arc_motion::arc_measured_spring(
            (self.id.clone(), "viewport-height"),
            target_vp_h,
            34.0,
            SpringSpec::visual(0.32, 0.0),
            window,
            cx,
        )
        .max(32.0);
        let measure_vp_ref = vp_h_ref.clone();

        let bar_surface = bar_surface
            .child(div().w(px(mirror_width)).flex_shrink_0())
            .child(
                div()
                    .relative()
                    .flex_1()
                    .min_w(px(0.0))
                    .h(px(animated_vp_h))
                    .overflow_hidden()
                    .when_some(outgoing_face, |el, out| el.child(out))
                    .child(
                        div()
                            .absolute()
                            .left_0()
                            .right_0()
                            .top(px(slide_y))
                            .opacity((eased_slide * 1.15).clamp(0.0, 1.0))
                            .flex()
                            .items_center()
                            .justify_center()
                            .child(build_message_row(current_msg, true))
                            .on_children_prepainted(move |children_bounds, window, _| {
                                if let Some(b) = children_bounds.first() {
                                    let h = f32::from(b.size.height).max(32.0);
                                    let prev = *measure_vp_ref.borrow();
                                    if prev.is_none_or(|prev| (prev - h).abs() > 0.5) {
                                        *measure_vp_ref.borrow_mut() = Some(h);
                                        window.request_animation_frame();
                                    }
                                }
                            }),
                    ),
            )
            .child(
                div()
                    .flex()
                    .items_center()
                    .gap(px(2.0))
                    .flex_shrink_0()
                    .children(control_items),
            )
            .on_children_prepainted(move |children_bounds, _, _| {
                let mut max_h = 0.0_f32;
                for b in children_bounds {
                    max_h = max_h.max(f32::from(b.size.height));
                }
                if max_h > 20.0 {
                    *measure_bar_ref.borrow_mut() = max_h + 14.0;
                }
            });

        let open_clamped = open_scale.clamp(0.0, 1.0);
        let mut outer = div()
            .id(self.id)
            .test_support()
            .role(Role::Region)
            .track_focus(&focus_handle)
            .w_full()
            .overflow_hidden()
            .opacity(open_clamped)
            .on_hover(move |hovered: &bool, window, _| {
                let changed = {
                    let mut st = hover_state.borrow_mut();
                    if st.hovered != *hovered {
                        st.hovered = *hovered;
                        true
                    } else {
                        false
                    }
                };
                if changed {
                    window.refresh();
                }
            })
            .on_key_down(move |event: &KeyDownEvent, window, cx| {
                if total < 2 {
                    return;
                }
                let key = event.keystroke.key.as_str();
                let delta = match key {
                    "up" | "arrowup" | "left" | "arrowleft" => -1,
                    "down" | "arrowdown" | "right" | "arrowright" => 1,
                    _ => 0,
                };
                if delta != 0 {
                    let t_now = motion_now(cx);
                    let next_idx = {
                        let mut st = key_state.borrow_mut();
                        let prev = st.index;
                        let next = announcement_wrap_index(prev, delta, total);
                        st.prev_index = Some(prev);
                        st.index = next;
                        st.direction = delta as i8;
                        st.progress = 0.0;
                        st.slide_started_at = t_now;
                        next
                    };
                    if let Some(ref cb) = on_idx_key {
                        cb(&next_idx, window, cx);
                    }
                    window.refresh();
                }
            })
            .child(bar_surface);

        if open_clamped < 0.995 {
            outer = outer.h(px((natural_bar_h * open_clamped).max(0.0)));
        }

        outer.into_any_element()
    }
}

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

    #[test]
    fn announcement_countdown_and_wrap_index_math() {
        let p = announcement_countdown_parts(2.0 * 86_400.0 + 3.0 * 3_600.0 + 9.0 * 60.0 + 5.0);
        assert_eq!(
            p,
            AnnouncementCountdownParts {
                days: 2,
                hours: 3,
                minutes: 9,
                seconds: 5,
            }
        );
        assert_eq!(format_announcement_countdown(p), "2d 03:09:05");

        let zero = announcement_countdown_parts(-10.0);
        assert_eq!(format_announcement_countdown(zero), "00:00:00");

        assert_eq!(announcement_wrap_index(0, -1, 3), 2);
        assert_eq!(announcement_wrap_index(2, 1, 3), 0);
        assert_eq!(announcement_wrap_index(1, 0, 3), 1);
    }

    #[test]
    fn announcement_dismissal_registry_remembers_and_clears() {
        let key = "test-campaign-2026";
        clear_announcement_dismissal(key);
        assert!(!is_announcement_dismissed(key));

        remember_announcement_dismissal(key);
        assert!(is_announcement_dismissed(key));

        clear_announcement_dismissal(key);
        assert!(!is_announcement_dismissed(key));
    }
}