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)>;
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()))
}
pub fn remember_announcement_dismissal(id: &str) {
if let Ok(mut set) = dismissed_registry().lock() {
set.insert(id.to_string());
}
}
pub fn is_announcement_dismissed(id: &str) -> bool {
dismissed_registry()
.lock()
.map(|set| set.contains(id))
.unwrap_or(false)
}
pub fn clear_announcement_dismissal(id: &str) {
if let Ok(mut set) = dismissed_registry().lock() {
set.remove(id);
}
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
pub enum AnnouncementBarTone {
#[default]
Neutral,
Inverted,
}
#[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
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct AnnouncementCountdown {
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,
}
}
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
}
}
#[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
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct AnnouncementCountdownParts {
pub days: u64,
pub hours: u64,
pub minutes: u64,
pub seconds: u64,
}
#[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,
}
}
#[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
}
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,
}
#[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,
}
}
pub fn rounded_top(mut self, radius: impl Into<Pixels>) -> Self {
self.top_radius = Some(radius.into());
self
}
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);
}
}
if is_paused {
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 {
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;
}
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(¤t_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),
),
};
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
};
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));
}
}