use std::{cell::RefCell, rc::Rc, time::Duration};
use arc_motion::{BlurFallback, arc_transition, is_reduced_motion};
use arc_tokens::{ActiveArcTheme as _, Spacing, Typography};
use gpui_kit::{
AnyElement, App, ElementId, IntoElement, ParentElement, SharedString, Styled, Window, canvas,
div, prelude::*, px,
};
#[derive(Clone)]
struct FieldMessageState {
last_text: SharedString,
measured_height: Rc<RefCell<Option<f32>>>,
}
pub(crate) fn render_field_message(
id: ElementId,
text: Option<SharedString>,
is_error: bool,
window: &mut Window,
cx: &mut App,
) -> AnyElement {
let theme = cx.arc_theme().clone();
let colors = theme.colors;
let motion = theme.motion;
let reduced = is_reduced_motion(cx);
let state_id = ElementId::NamedChild(id.clone().into(), "__arc-field-msg".into());
let state = window.use_keyed_state(state_id, cx, |_, _| FieldMessageState {
last_text: text.clone().unwrap_or_default(),
measured_height: Rc::new(RefCell::new(None)),
});
if let Some(ref current) = text
&& state.read(cx).last_text != *current
{
state.update(cx, |s, _| s.last_text = current.clone());
}
let snap = state.read(cx).clone();
let visible = text.as_ref().is_some_and(|t| !t.is_empty());
let measured = snap.measured_height.borrow().map(|h| h.max(24.0));
let target_h = if visible { measured } else { Some(0.0) };
let anim_h = arc_motion::arc_measured_spring(
(id.clone(), "msg-h"),
target_h,
26.0,
motion.spring.smooth,
window,
cx,
);
let progress = arc_transition(
(id.clone(), "msg-p"),
if visible { 1.0 } else { 0.0 },
if reduced {
Duration::ZERO
} else if visible {
motion.duration.standard
} else {
motion.duration.instant
},
if visible {
motion.ease.enter
} else {
motion.ease.standard
},
window,
cx,
);
if !visible && anim_h <= 0.5 && progress <= 0.01 {
return div().id(id).h(px(0.0)).overflow_hidden().into_any_element();
}
let blur = BlurFallback::evaluate(motion.blur.soft * (1.0 - progress), reduced);
let y_offset = if reduced {
0.0
} else {
(1.0 - progress) * 4.5 + f32::from(blur.offset_y)
};
let text_color = if is_error {
colors.danger
} else {
colors.text_muted
};
let display = text.unwrap_or(snap.last_text);
let measure_ref = snap.measured_height.clone();
let probe = canvas(
move |rect, window, _| {
let h = f32::from(rect.size.height);
if h > 1.0 {
let prev = *measure_ref.borrow();
*measure_ref.borrow_mut() = Some(h);
if prev.is_none_or(|prev| (h - prev).abs() > 0.5) {
window.request_animation_frame();
}
}
},
|_, _, _, _| {},
)
.absolute()
.inset_0();
div()
.id(id)
.w_full()
.h(px(anim_h.max(0.0)))
.overflow_hidden()
.flex()
.flex_col()
.items_start()
.child(
div()
.relative()
.w_full()
.flex_none()
.pt(Spacing::S2)
.mt(px(y_offset))
.opacity((progress * blur.opacity_multiplier).clamp(0.0, 1.0))
.text_size(Typography::TEXT_XS)
.text_color(text_color)
.child(probe)
.child(display),
)
.into_any_element()
}