use super::parts::{self, rem};
use crate::{
density,
icons::{CarbonIcon, Icon},
motion,
t3::base::{endless_phase, fmt_elapsed_opt, reduced_pulse_opacity},
theme::color,
tokens::ColorRole,
};
use gpui_kit::{
Animation, AnimationExt as _, AnyElement, App, ElementId, HighlightStyle, Hsla,
InteractiveElement as _, IntoElement, ParentElement, RenderOnce, SharedString,
StatefulInteractiveElement as _, Styled, StyledText, Window, div, prelude::FluentBuilder as _,
px, relative,
};
use std::time::Duration;
pub const SHIMMER_PERIOD: Duration = Duration::from_millis(2400);
pub const PULSE_PERIOD: Duration = Duration::from_millis(1400);
pub fn shimmer_mix(u: f32, t: f32) -> f32 {
let p = 1. - 1.5 * t.rem_euclid(1.);
let peak = 1.5 - 2. * p;
(1. - (u - peak).abs() / 0.3).clamp(0., 1.)
}
fn mix(a: Hsla, b: Hsla, f: f32) -> Hsla {
let a = a.to_rgb();
let b = b.to_rgb();
gpui_kit::Rgba {
r: a.r + (b.r - a.r) * f,
g: a.g + (b.g - a.g) * f,
b: a.b + (b.b - a.b) * f,
a: a.a + (b.a - a.a) * f,
}
.into()
}
fn shimmer(id: ElementId, text: SharedString, window: &mut Window, cx: &App) -> AnyElement {
let secondary = color(ColorRole::TextSecondary);
if motion::reduced_motion(cx) {
let opacity = reduced_pulse_opacity(endless_phase(PULSE_PERIOD, window));
return div()
.text_color(secondary)
.child(text)
.opacity(opacity)
.into_any_element();
}
let primary = color(ColorRole::TextPrimary);
let spans: Vec<(usize, usize)> = text
.char_indices()
.map(|(i, c)| (i, i + c.len_utf8()))
.collect();
let n = spans.len().max(1) as f32;
div()
.text_color(secondary)
.child(StyledText::new(text.clone()).with_animation(
id,
Animation::new(SHIMMER_PERIOD).repeat(),
move |styled, t| {
styled.with_highlights(spans.iter().enumerate().map(|(k, &(a, b))| {
let f = shimmer_mix((k as f32 + 0.5) / n, t);
(
a..b,
HighlightStyle {
color: Some(mix(secondary, primary, f)),
..Default::default()
},
)
}))
},
))
.into_any_element()
}
#[derive(Clone, Debug)]
pub struct ThinkingBlockTexts {
pub thinking: SharedString,
pub thought_for: SharedString,
}
impl Default for ThinkingBlockTexts {
fn default() -> Self {
Self {
thinking: "Thinking".into(),
thought_for: "Thought for".into(),
}
}
}
impl ThinkingBlockTexts {
pub fn thought(&self, seconds: Option<u64>) -> String {
format!("{} {}", self.thought_for, fmt_elapsed_opt(seconds))
}
}
pub mod geometry {
pub const INDENT: f32 = 8.;
pub const HEAD_GAP: f32 = 8.;
pub const FONT: f32 = 13.;
pub const BODY_PADDING: (f32, f32, f32) = (16., 8., 32.);
pub const BODY_LINE: f32 = 1.5;
}
#[derive(IntoElement)]
pub struct ThinkingBlock {
id: ElementId,
seconds: Option<u64>,
live: bool,
default_open: bool,
interactive: bool,
children: Vec<AnyElement>,
texts: ThinkingBlockTexts,
}
impl ThinkingBlock {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
seconds: None,
live: false,
default_open: false,
interactive: true,
children: Vec::new(),
texts: ThinkingBlockTexts::default(),
}
}
pub fn interactive(mut self, interactive: bool) -> Self {
self.interactive = interactive;
self
}
pub fn seconds(mut self, seconds: u64) -> Self {
self.seconds = Some(seconds);
self
}
pub fn live(mut self, live: bool) -> Self {
self.live = live;
self
}
pub fn default_open(mut self, open: bool) -> Self {
self.default_open = open;
self
}
pub fn texts(mut self, texts: ThinkingBlockTexts) -> Self {
self.texts = texts;
self
}
}
impl ParentElement for ThinkingBlock {
fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
self.children.extend(elements);
}
}
impl RenderOnce for ThinkingBlock {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let id = self.id;
let interactive = self.interactive;
let open_state = parts::open_state((id.clone(), "open"), self.default_open, window, cx);
let open = *open_state.read(cx);
let (focus, ring) = parts::focus((id.clone(), "focus"), window, cx);
let (raw_hovered, hover) = parts::hover((id.clone(), "hover"), window, cx);
let hovered = interactive && raw_hovered;
let ink = parts::head_ink(hovered);
let label = if self.live {
shimmer(
(id.clone(), "shimmer").into(),
self.texts.thinking,
window,
cx,
)
} else {
div()
.child(self.texts.thought(self.seconds))
.into_any_element()
};
let head = gpui_kit::base::Button::new((id.clone(), "head"))
.when(interactive, |b| b.track_focus(&focus))
.relative()
.flex()
.flex_row()
.flex_none()
.items_center()
.justify_start()
.h(density::current().row_sm())
.px(rem(geometry::HEAD_GAP))
.gap(rem(geometry::HEAD_GAP))
.text_color(ink)
.text_size(rem(geometry::FONT))
.line_height(relative(crate::t3::craft::BODY_LINE))
.whitespace_nowrap()
.when(interactive, |b| {
let open_state = open_state.clone();
b.cursor_pointer()
.on_hover(parts::track_hover(hover))
.on_click(move |_, _, cx| parts::toggle(&open_state, cx))
})
.child(
Icon::carbon(CarbonIcon::Idea)
.size_length(rem(16.))
.color(ink),
)
.child(label)
.when(interactive, |b| {
b.child(parts::chevron_down(open, 14., ink))
.when(ring, |b| b.child(parts::ring()))
});
let (pr, pb, pl) = geometry::BODY_PADDING;
let body = open.then(|| {
div()
.pr(rem(pr))
.pb(rem(pb))
.pl(rem(pl))
.text_size(rem(geometry::FONT))
.line_height(relative(geometry::BODY_LINE))
.text_color(color(ColorRole::TextSecondary))
.italic()
.children(self.children)
});
div()
.id(id)
.flex()
.flex_col()
.items_start()
.ml(rem(geometry::INDENT))
.border_l(px(1.))
.border_color(color(ColorRole::BorderSubtle01))
.child(head)
.children(body)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_sweep_crosses_from_left_to_right() {
assert_eq!(shimmer_mix(0., 0.), 0.);
assert!((shimmer_mix(0., 1. / 6.) - 1.).abs() < 1e-5);
assert!((shimmer_mix(1., 0.5) - 1.).abs() < 1e-5);
assert_eq!(shimmer_mix(0.2, 0.5), 0.);
assert!((shimmer_mix(0.85, 0.5) - 0.5).abs() < 1e-5);
}
#[test]
fn labels_follow_the_reference() {
let t = ThinkingBlockTexts::default();
assert_eq!(t.thinking, "Thinking");
assert_eq!(t.thought(Some(23)), "Thought for 23s");
assert_eq!(t.thought(Some(74)), "Thought for 1m 14s");
assert_eq!(geometry::BODY_PADDING.2, 32.);
}
}