Skip to main content

gpui_component/
marker.rs

1use gpui_base::LogicalStyledExt as _;
2
3use crate::{
4    ActiveTheme as _, RoleOverride, Sizable as _, StyledExt as _, h_flex,
5    shimmer::{ShimmerStyle, ShimmerText},
6    spinner::Spinner,
7};
8use gpui::{
9    AnimationExt as _, AnyElement, App, ElementId, InteractiveElement as _, IntoElement,
10    ParentElement, RenderOnce, SharedString, StatefulInteractiveElement as _, StyleRefinement,
11    Styled, StyledText, Window, div, prelude::FluentBuilder as _, px, relative, rems,
12};
13
14/// The visual treatment used by a [`Marker`].
15#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
16pub enum MarkerVariant {
17    /// An inline marker with no additional divider.
18    #[default]
19    Plain,
20    /// A centered marker with semantic divider lines on both sides.
21    Separator,
22    /// A marker with a semantic bottom border.
23    Border,
24}
25
26/// The visual treatment used while a [`Marker`] is loading.
27#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
28pub enum MarkerLoadingStyle {
29    /// Show a compact rotating spinner beside the marker content.
30    #[default]
31    Spinner,
32    /// Sweep a highlight across marker content without adding an icon.
33    Shimmer,
34}
35
36/// Horizontal placement of a [`Marker`]'s children inside its full-width row.
37#[derive(Clone, Copy, Debug, PartialEq, Eq)]
38pub enum MarkerAlignment {
39    /// Keep the children at the leading edge.
40    Start,
41    /// Center the children, like a system notice in a transcript.
42    Center,
43    /// Keep the children at the trailing edge.
44    End,
45}
46
47enum MarkerChild {
48    Icon(MarkerIcon),
49    Content(MarkerContent),
50    Element(AnyElement),
51}
52
53/// A compact, composable row for conversation status and system markers.
54///
55/// `Marker` intentionally accepts arbitrary children. An icon, text, spinner,
56/// or action can be composed directly without introducing fixed icon and
57/// content slots. Use [`Styled`] methods on the marker to refine its layout or
58/// typography for an application-specific use. Loading effects only affect
59/// configured content slots, so icons and separators retain their appearance.
60#[derive(IntoElement)]
61pub struct Marker {
62    id: Option<ElementId>,
63    style: StyleRefinement,
64    separator_style: StyleRefinement,
65    variant: MarkerVariant,
66    alignment: Option<MarkerAlignment>,
67    loading: bool,
68    loading_style: MarkerLoadingStyle,
69    shimmer_style: ShimmerStyle,
70    role: RoleOverride,
71    children: Vec<MarkerChild>,
72}
73
74impl Marker {
75    /// Create a plain marker.
76    pub fn new() -> Self {
77        Self {
78            id: None,
79            style: StyleRefinement::default(),
80            separator_style: StyleRefinement::default(),
81            variant: MarkerVariant::default(),
82            alignment: None,
83            loading: false,
84            loading_style: MarkerLoadingStyle::default(),
85            shimmer_style: ShimmerStyle::default(),
86            role: RoleOverride::default(),
87            children: Vec::new(),
88        }
89    }
90
91    /// Set a stable identity so the marker can appear in the accessibility tree.
92    pub fn id(mut self, id: impl Into<ElementId>) -> Self {
93        self.id = Some(id.into());
94        self
95    }
96
97    /// Set the accessibility role announced for this marker.
98    ///
99    /// A marker is presentational by default. Set [`gpui::Role::Status`] on a
100    /// row that reports streaming or loading progress so assistive technology
101    /// announces its updates. Accessibility nodes need a stable identity, so
102    /// the role takes effect only together with [`Self::id`].
103    pub fn role(mut self, role: impl Into<RoleOverride>) -> Self {
104        self.role = role.into();
105        self
106    }
107
108    /// Set the visual treatment of the marker.
109    pub fn with_variant(mut self, variant: MarkerVariant) -> Self {
110        self.variant = variant;
111        self
112    }
113
114    /// Set where the row places its children.
115    ///
116    /// Unset, a [`MarkerVariant::Separator`] centers its label between the two
117    /// lines and every other variant starts at the leading edge. An explicit
118    /// alignment applies to any variant and also aligns wrapped text lines. A
119    /// separator keeps only the line on the far side of its label, so `Start`
120    /// draws the trailing line and `End` the leading one.
121    pub fn alignment(mut self, alignment: MarkerAlignment) -> Self {
122        self.alignment = Some(alignment);
123        self
124    }
125
126    fn resolved_alignment(&self) -> MarkerAlignment {
127        self.alignment.unwrap_or(match self.variant {
128            MarkerVariant::Separator => MarkerAlignment::Center,
129            MarkerVariant::Plain | MarkerVariant::Border => MarkerAlignment::Start,
130        })
131    }
132
133    /// Set whether the marker should display its configured loading effect.
134    pub fn loading(mut self, loading: bool) -> Self {
135        self.loading = loading;
136        self
137    }
138
139    /// Set the visual treatment used when [`Self::loading`] is enabled.
140    pub fn with_loading_style(mut self, loading_style: MarkerLoadingStyle) -> Self {
141        self.loading_style = loading_style;
142        self
143    }
144
145    /// Configure the text highlight used by [`MarkerLoadingStyle::Shimmer`].
146    pub fn with_shimmer_style(mut self, shimmer_style: ShimmerStyle) -> Self {
147        self.shimmer_style = shimmer_style;
148        self
149    }
150
151    /// Refine the decorative lines used by [`MarkerVariant::Separator`].
152    pub fn separator_style(mut self, style: StyleRefinement) -> Self {
153        self.separator_style = style;
154        self
155    }
156
157    /// Add a configured icon slot.
158    pub fn icon(mut self, icon: MarkerIcon) -> Self {
159        self.children.push(MarkerChild::Icon(icon));
160        self
161    }
162
163    /// Add a configured content slot.
164    pub fn content(mut self, content: MarkerContent) -> Self {
165        self.children.push(MarkerChild::Content(content));
166        self
167    }
168}
169
170impl Default for Marker {
171    fn default() -> Self {
172        Self::new()
173    }
174}
175
176impl ParentElement for Marker {
177    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
178        self.children
179            .extend(elements.into_iter().map(MarkerChild::Element));
180    }
181}
182
183impl Styled for Marker {
184    fn style(&mut self) -> &mut StyleRefinement {
185        &mut self.style
186    }
187}
188
189impl RenderOnce for Marker {
190    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
191        let tokens = cx.theme().semantic_tokens();
192        let variant = self.variant;
193        let alignment = self.resolved_alignment();
194        let loading = self.loading;
195        let loading_style = self.loading_style;
196        let shimmer_style = self.shimmer_style;
197        let has_icon = self
198            .children
199            .iter()
200            .any(|child| matches!(child, MarkerChild::Icon(_)));
201        let role = self.role;
202        let separator_style = self.separator_style;
203        let children = self.children.into_iter().map(move |child| match child {
204            MarkerChild::Icon(icon) => icon.into_any_element(),
205            MarkerChild::Content(mut content) => {
206                content.shimmer = loading && loading_style == MarkerLoadingStyle::Shimmer;
207                content.shimmer_style = shimmer_style;
208                content.separator = variant == MarkerVariant::Separator;
209                content.alignment = alignment;
210                content.into_any_element()
211            }
212            MarkerChild::Element(element) => element,
213        });
214
215        let row = h_flex()
216            .flex_row_dir(cx)
217            .w_full()
218            .min_h(rems(1.))
219            .gap_2()
220            .text_sm()
221            .line_height(relative(1.5))
222            .text_color(tokens.colors.muted_foreground)
223            .map(|this| match alignment {
224                MarkerAlignment::Start => this.justify_flex_start().text_start(cx),
225                MarkerAlignment::Center => this.justify_center().text_center(),
226                MarkerAlignment::End => this.justify_flex_end().text_end(cx),
227            })
228            .when(variant == MarkerVariant::Border, |this| {
229                this.border_b_1().border_color(tokens.colors.border).pb_2()
230            })
231            .when(
232                variant == MarkerVariant::Separator && alignment != MarkerAlignment::Start,
233                |this| {
234                    this.child(
235                        div()
236                            .flex_1()
237                            .min_w_0()
238                            .h(px(1.))
239                            .me(rems(0.25), cx)
240                            .bg(tokens.colors.border)
241                            .refine_style(&separator_style),
242                    )
243                },
244            )
245            .when(
246                loading && loading_style == MarkerLoadingStyle::Spinner && !has_icon,
247                |this| this.child(MarkerIcon::new().child(Spinner::new().xsmall())),
248            )
249            .children(children)
250            .when(
251                variant == MarkerVariant::Separator && alignment != MarkerAlignment::End,
252                |this| {
253                    this.child(
254                        div()
255                            .flex_1()
256                            .min_w_0()
257                            .h(px(1.))
258                            .ms(rems(0.25), cx)
259                            .bg(tokens.colors.border)
260                            .refine_style(&separator_style),
261                    )
262                },
263            )
264            .refine_style(&self.style);
265
266        // `role` lives on the stateful element: accessibility nodes need the
267        // stable identity that only an element id provides.
268        match (self.id, role) {
269            (Some(id), RoleOverride::Role(role)) => row.id(id).role(role).into_any_element(),
270            (Some(id), _) => row.id(id).into_any_element(),
271            (None, _) => row.into_any_element(),
272        }
273    }
274}
275
276/// A compact decorative icon slot inside a [`Marker`].
277#[derive(IntoElement)]
278pub struct MarkerIcon {
279    style: StyleRefinement,
280    children: Vec<AnyElement>,
281}
282
283impl MarkerIcon {
284    /// Create an empty marker icon slot.
285    pub fn new() -> Self {
286        Self {
287            style: StyleRefinement::default(),
288            children: Vec::new(),
289        }
290    }
291}
292
293impl Default for MarkerIcon {
294    fn default() -> Self {
295        Self::new()
296    }
297}
298
299impl ParentElement for MarkerIcon {
300    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
301        self.children.extend(elements);
302    }
303}
304
305impl Styled for MarkerIcon {
306    fn style(&mut self) -> &mut StyleRefinement {
307        &mut self.style
308    }
309}
310
311impl RenderOnce for MarkerIcon {
312    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
313        h_flex()
314            .size_4()
315            .flex_none()
316            .items_center()
317            .justify_center()
318            .refine_style(&self.style)
319            .children(self.children)
320    }
321}
322
323/// The independently styleable text or rich-content slot in a [`Marker`].
324#[derive(IntoElement)]
325pub struct MarkerContent {
326    style: StyleRefinement,
327    shimmer: bool,
328    shimmer_style: ShimmerStyle,
329    separator: bool,
330    alignment: MarkerAlignment,
331    children: Vec<MarkerContentChild>,
332}
333
334enum MarkerContentChild {
335    Text(SharedString),
336    Element(AnyElement),
337}
338
339impl MarkerContent {
340    /// Create an empty marker content slot.
341    pub fn new() -> Self {
342        Self {
343            style: StyleRefinement::default(),
344            shimmer: false,
345            shimmer_style: ShimmerStyle::default(),
346            separator: false,
347            alignment: MarkerAlignment::Start,
348            children: Vec::new(),
349        }
350    }
351
352    /// Add text that can receive a continuous loading shimmer.
353    ///
354    /// Arbitrary children remain supported through [`ParentElement`].
355    pub fn text(mut self, text: impl Into<SharedString>) -> Self {
356        self.children.push(MarkerContentChild::Text(text.into()));
357        self
358    }
359}
360
361impl Default for MarkerContent {
362    fn default() -> Self {
363        Self::new()
364    }
365}
366
367impl ParentElement for MarkerContent {
368    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
369        self.children
370            .extend(elements.into_iter().map(MarkerContentChild::Element));
371    }
372}
373
374impl Styled for MarkerContent {
375    fn style(&mut self) -> &mut StyleRefinement {
376        &mut self.style
377    }
378}
379
380impl RenderOnce for MarkerContent {
381    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
382        let animate = self.shimmer && !cx.reduce_motion();
383        let has_text = self
384            .children
385            .iter()
386            .any(|child| matches!(child, MarkerContentChild::Text(_)));
387        let base_opacity = self.style.opacity.unwrap_or(1.);
388        let shimmer_style = self.shimmer_style;
389        let children =
390            self.children
391                .into_iter()
392                .enumerate()
393                .map(move |(index, child)| match child {
394                    MarkerContentChild::Text(text) if animate => ShimmerText::new(text)
395                        .id(("marker-loading-text", index))
396                        .with_shimmer_style(shimmer_style)
397                        .into_any_element(),
398                    MarkerContentChild::Text(text) => StyledText::new(text).into_any_element(),
399                    MarkerContentChild::Element(element) => element,
400                });
401
402        let content = div()
403            .min_w_0()
404            // Between separator lines the label keeps its own width so the
405            // lines take the rest; elsewhere it may shrink and wrap.
406            .when(self.separator, |this| this.flex_none())
407            .map(|this| match self.alignment {
408                MarkerAlignment::Start => this.text_start(cx),
409                MarkerAlignment::Center => this.text_center(),
410                MarkerAlignment::End => this.text_end(cx),
411            })
412            .refine_style(&self.style)
413            .children(children);
414
415        if animate && !has_text {
416            content
417                .with_animation(
418                    "marker-loading-content",
419                    shimmer_style.animation(),
420                    move |this, phase| {
421                        let highlight = (phase * std::f32::consts::TAU).cos().mul_add(0.5, 0.5);
422                        this.opacity(base_opacity * highlight.mul_add(0.4, 0.6))
423                    },
424                )
425                .into_any_element()
426        } else {
427            content.into_any_element()
428        }
429    }
430}
431
432#[cfg(test)]
433mod tests {
434    use super::*;
435
436    #[test]
437    fn test_marker_builder() {
438        let marker = Marker::new()
439            .with_variant(MarkerVariant::Separator)
440            .loading(true)
441            .with_loading_style(MarkerLoadingStyle::Shimmer)
442            .with_shimmer_style(ShimmerStyle::new().reverse(true))
443            .separator_style(StyleRefinement::default())
444            .content(MarkerContent::new().child("Today"));
445
446        assert_eq!(marker.variant, MarkerVariant::Separator);
447        assert!(marker.loading);
448        assert_eq!(marker.loading_style, MarkerLoadingStyle::Shimmer);
449        assert_eq!(marker.children.len(), 1);
450        assert_eq!(Marker::default().variant, MarkerVariant::Plain);
451        assert!(Marker::default().alignment.is_none());
452        assert!(!Marker::default().loading);
453        assert_eq!(Marker::default().loading_style, MarkerLoadingStyle::Spinner);
454
455        let centered = Marker::new().alignment(MarkerAlignment::Center);
456        assert_eq!(centered.alignment, Some(MarkerAlignment::Center));
457
458        let content_first = Marker::new()
459            .content(MarkerContent::new().text("Thinking"))
460            .with_loading_style(MarkerLoadingStyle::Shimmer)
461            .loading(true);
462        assert!(content_first.loading);
463        assert_eq!(content_first.loading_style, MarkerLoadingStyle::Shimmer);
464        assert!(matches!(
465            &content_first.children[0],
466            MarkerChild::Content(_)
467        ));
468
469        let custom_icon = Marker::new()
470            .loading(true)
471            .icon(MarkerIcon::new().child("custom"))
472            .content(MarkerContent::new().text("Loading"));
473        assert_eq!(custom_icon.children.len(), 2);
474        assert!(matches!(&custom_icon.children[0], MarkerChild::Icon(_)));
475
476        assert_eq!(Marker::default().role, RoleOverride::default());
477        assert!(Marker::default().id.is_none());
478        let status = Marker::new().id("sync-status").role(gpui::Role::Status);
479        assert_eq!(status.id, Some("sync-status".into()));
480        assert_eq!(status.role, RoleOverride::Role(gpui::Role::Status));
481
482        let styled = Marker::new().opacity(0.37).child("Status").child("Details");
483
484        assert_eq!(styled.style.opacity, Some(0.37));
485        assert_eq!(styled.children.len(), 2);
486
487        let icon = MarkerIcon::new().child("icon");
488        assert_eq!(icon.children.len(), 1);
489
490        let content = MarkerContent::new()
491            .text("Thinking")
492            .child("…")
493            .text("正在思考");
494        assert_eq!(content.children.len(), 3);
495        assert!(matches!(&content.children[0], MarkerContentChild::Text(_)));
496        assert!(matches!(
497            &content.children[1],
498            MarkerContentChild::Element(_)
499        ));
500        assert!(matches!(&content.children[2], MarkerContentChild::Text(_)));
501    }
502
503    #[test]
504    fn test_marker_resolved_alignment() {
505        // Unset: only the separator centers its label.
506        assert_eq!(Marker::new().resolved_alignment(), MarkerAlignment::Start);
507        assert_eq!(
508            Marker::new()
509                .with_variant(MarkerVariant::Border)
510                .resolved_alignment(),
511            MarkerAlignment::Start
512        );
513        assert_eq!(
514            Marker::new()
515                .with_variant(MarkerVariant::Separator)
516                .resolved_alignment(),
517            MarkerAlignment::Center
518        );
519
520        // Explicit alignment wins over the variant default, in either order.
521        assert_eq!(
522            Marker::new()
523                .alignment(MarkerAlignment::End)
524                .with_variant(MarkerVariant::Separator)
525                .resolved_alignment(),
526            MarkerAlignment::End
527        );
528        assert_eq!(
529            Marker::new()
530                .with_variant(MarkerVariant::Plain)
531                .alignment(MarkerAlignment::Center)
532                .resolved_alignment(),
533            MarkerAlignment::Center
534        );
535    }
536}