Skip to main content

gpui_component/input/
group.rs

1//! A shared frame around one text control and its addons.
2//!
3//! The parts follow shadcn's input group: [`InputGroup`] is the frame,
4//! [`InputGroupInput`] and [`InputGroupTextarea`] are the ordinary [`Input`]
5//! and [`Textarea`] placed in it, [`InputGroupAddon`] holds text, icons and
6//! buttons on one of its four sides, [`InputGroupButton`] is a [`Button`] with
7//! compact input-group presentation and [`InputGroupText`] is muted text. The
8//! caller keeps the `InputState` or `TextareaState`; the group owns only
9//! composition and the frame.
10
11use std::time::Duration;
12
13use gpui_base::LogicalStyledExt as _;
14use gpui_base::TestSupportExt as _;
15
16use gpui::{
17    AnyElement, App, ElementId, InteractiveElement, Interactivity, IntoElement, MouseButton,
18    ParentElement, RenderOnce, Role, SharedString, StatefulInteractiveElement as _,
19    StyleRefinement, Styled, ViewElement, Window, div, prelude::FluentBuilder as _, px, rems,
20};
21
22use crate::{
23    ActiveTheme as _, Disableable, FocusableExt as _, Icon, Selectable, Sizable, Size,
24    StyleSized as _, StyledExt as _,
25    button::{Button, ButtonCustomVariant, ButtonVariant, ButtonVariants},
26    h_flex,
27    input::{Input, Textarea},
28    v_flex,
29};
30
31/// A shared frame around one text control and any number of explicitly aligned addons.
32///
33/// The caller retains the `InputState` or `TextareaState`. The group owns only
34/// composition and presentation; the control keeps every `Input` capability
35/// and renders without its own frame. `input` replaces the slot.
36#[derive(IntoElement)]
37pub struct InputGroup {
38    id: ElementId,
39    style: StyleRefinement,
40    control: Option<Input>,
41    addons: Vec<InputGroupAddon>,
42    size: Size,
43    disabled: bool,
44    readonly: bool,
45    invalid: bool,
46    focus_ring: bool,
47    aria_label: Option<SharedString>,
48}
49
50impl InputGroup {
51    pub fn new(id: impl Into<ElementId>) -> Self {
52        Self {
53            id: id.into(),
54            style: StyleRefinement::default(),
55            control: None,
56            addons: Vec::new(),
57            size: Size::default(),
58            disabled: false,
59            readonly: false,
60            invalid: false,
61            focus_ring: true,
62            aria_label: None,
63        }
64    }
65
66    /// Set the single-line input or textarea, replacing the previous control.
67    pub fn input(mut self, input: impl Into<InputGroupControl>) -> Self {
68        self.control = Some(input.into().0);
69        self
70    }
71
72    /// Append an addon. Addons on the same side retain their insertion order.
73    pub fn addon(mut self, addon: InputGroupAddon) -> Self {
74        self.addons.push(addon);
75        self
76    }
77
78    /// Prevent editing and interaction throughout this group.
79    pub fn disabled(mut self, disabled: bool) -> Self {
80        self.disabled = disabled;
81        self
82    }
83
84    /// Prevent editing while preserving selection, copying, and addon actions.
85    pub fn readonly(mut self, readonly: bool) -> Self {
86        self.readonly = readonly;
87        self
88    }
89
90    /// Display the caller's validation result. This does not reject text edits.
91    pub fn invalid(mut self, invalid: bool) -> Self {
92        self.invalid = invalid;
93        self
94    }
95
96    /// Set a name for the group. Name its text control separately with `aria_label`.
97    pub fn aria_label(mut self, label: impl Into<SharedString>) -> Self {
98        self.aria_label = Some(label.into());
99        self
100    }
101}
102
103impl Sizable for InputGroup {
104    fn with_size(mut self, size: impl Into<Size>) -> Self {
105        self.size = size.into();
106        self
107    }
108}
109
110impl crate::FocusableExt for InputGroup {
111    fn focus_ring(mut self, enabled: bool) -> Self {
112        self.focus_ring = enabled;
113        self
114    }
115
116    fn is_focus_ring_enabled(&self) -> bool {
117        self.focus_ring
118    }
119}
120
121impl Styled for InputGroup {
122    fn style(&mut self) -> &mut StyleRefinement {
123        &mut self.style
124    }
125}
126
127/// What the addons and the control need to know about the group they sit in.
128#[derive(Clone, Copy, Default)]
129struct GroupPresentation {
130    size: Size,
131    disabled: bool,
132    readonly: bool,
133    inline_start: bool,
134    inline_end: bool,
135    block_start: bool,
136    block_end: bool,
137}
138
139impl RenderOnce for InputGroup {
140    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
141        let state = self.control.as_ref().map(|input| input.state().clone());
142        let disabled = self.disabled
143            || self
144                .control
145                .as_ref()
146                .is_some_and(|input| input.is_disabled());
147        let focused = !disabled
148            && state
149                .as_ref()
150                .is_some_and(|state| state.has_selection_focus(window, cx));
151        let multiline = state
152            .as_ref()
153            .is_some_and(|state| state.presentation(cx).is_multi_line());
154        let has = |alignment| self.addons.iter().any(|addon| addon.alignment == alignment);
155        let presentation = GroupPresentation {
156            size: self.size,
157            disabled,
158            readonly: self.readonly,
159            inline_start: has(InputGroupAddonAlignment::InlineStart),
160            inline_end: has(InputGroupAddonAlignment::InlineEnd),
161            block_start: has(InputGroupAddonAlignment::BlockStart),
162            block_end: has(InputGroupAddonAlignment::BlockEnd),
163        };
164        let mut inline_start = Vec::new();
165        let mut inline_end = Vec::new();
166        let mut block_start = Vec::new();
167        let mut block_end = Vec::new();
168        for addon in self.addons {
169            let target = match addon.alignment {
170                InputGroupAddonAlignment::InlineStart => &mut inline_start,
171                InputGroupAddonAlignment::InlineEnd => &mut inline_end,
172                InputGroupAddonAlignment::BlockStart => &mut block_start,
173                InputGroupAddonAlignment::BlockEnd => &mut block_end,
174            };
175            target.push(addon.render_in_group(presentation, window, cx));
176        }
177        let control = self
178            .control
179            .map(|input| render_control(input, presentation, multiline, cx));
180        let theme = cx.theme();
181        let appearance = GroupAppearance::new(theme, focused, disabled, self.invalid);
182        let radius = theme.radius;
183        let foreground = theme.foreground;
184        let show_ring = theme.focus_ring && self.focus_ring;
185        let motion = theme.motion_tokens();
186        let duration = motion.duration_fast;
187        let easing = motion.easing_move.clone();
188        // The border and background colors transition; the ring outside them
189        // changes immediately, like the standalone input's. A color cannot
190        // overshoot its target, so the theme curve is clamped.
191        let (border, background) = window.with_id(self.id.clone(), |window| {
192            let transition = || {
193                let easing = easing.clone();
194                gpui_base::Transition::new(duration)
195                    .ease(move |progress| easing.sample(progress).clamp(0., 1.))
196            };
197            (
198                gpui_base::transition("border-color", appearance.border, transition(), window, cx),
199                gpui_base::transition(
200                    "background-color",
201                    appearance.background,
202                    transition(),
203                    window,
204                    cx,
205                ),
206            )
207        });
208        v_flex()
209            .id(self.id)
210            .test_support()
211            .role(Role::Group)
212            .when_some(self.aria_label, |this, label| this.aria_label(label))
213            .relative()
214            .w_full()
215            .min_w_0()
216            .when(
217                !multiline && !presentation.block_start && !presentation.block_end,
218                |this| this.input_h(self.size),
219            )
220            .rounded(radius)
221            .border_1()
222            .border_color(border)
223            .bg(background)
224            .text_color(foreground)
225            .input_text_size(self.size)
226            .shadow_none()
227            .when(disabled, |this| {
228                // Custom addon content must not bypass the group's disabled policy.
229                this.capture_any_mouse_down(|_, _, cx| cx.stop_propagation())
230                    .capture_key_down(|event, _, cx| {
231                        if event.keystroke.key != "tab" {
232                            cx.stop_propagation();
233                        }
234                    })
235            })
236            .refine_style(&self.style)
237            .when(disabled, |this| this.bg(background).opacity(0.5))
238            .when(appearance.ring.is_some(), |this| this.border_color(border))
239            .when_some(appearance.ring.filter(|_| show_ring), |this, ring| {
240                crate::styled::focus_ring(this, window, ring)
241            })
242            .when_some(state.filter(|_| !disabled), |this, state| {
243                this.on_mouse_down(MouseButton::Left, move |_, window, cx| {
244                    // Native buttons prevent the default mouse-down focus action.
245                    // Respect that before focusing the editor from an addon or inset.
246                    if !window.default_prevented() {
247                        state.focus(window, cx);
248                        window.prevent_default();
249                    }
250                })
251            })
252            .children(block_start)
253            .child(
254                h_flex()
255                    // Inline addons sit on the logical sides of the control.
256                    .flex_row_dir(cx)
257                    .w_full()
258                    .min_w_0()
259                    .items_center()
260                    .when(
261                        !multiline && !presentation.block_start && !presentation.block_end,
262                        |this| this.h_full(),
263                    )
264                    .children(inline_start)
265                    .children(control)
266                    .children(inline_end),
267            )
268            .children(block_end)
269    }
270}
271
272/// The control rendered without its own frame: the group draws the border,
273/// background and ring. An inline addon takes over part of the control's
274/// horizontal inset, as in shadcn; the caller's own style still wins.
275fn render_control(
276    mut input: Input,
277    presentation: GroupPresentation,
278    multiline: bool,
279    cx: &App,
280) -> AnyElement {
281    let style = std::mem::take(input.style());
282    input
283        .with_size(presentation.size)
284        .appearance(false)
285        .focus_bordered(false)
286        .disabled(presentation.disabled)
287        .readonly(presentation.readonly)
288        .flex_1()
289        .min_w_0()
290        .when(multiline, |this| this.min_h_16())
291        .when(!multiline, |this| {
292            this.when(presentation.inline_start, |this| this.ps(rems(0.5), cx))
293                .when(presentation.inline_end, |this| this.pe(rems(0.5), cx))
294        })
295        .refine_style(&style)
296        .into_any_element()
297}
298
299struct GroupAppearance {
300    background: gpui::Hsla,
301    border: gpui::Hsla,
302    ring: Option<gpui::Hsla>,
303}
304
305impl GroupAppearance {
306    fn new(theme: &crate::Theme, focused: bool, disabled: bool, invalid: bool) -> Self {
307        let background = if disabled {
308            theme.input.opacity(if theme.is_dark() { 0.8 } else { 0.5 })
309        } else if theme.is_dark() {
310            theme.input.opacity(0.3)
311        } else {
312            theme.transparent
313        };
314        // Validation remains visible when editing is disabled. Focus alone never
315        // reactivates a disabled control, and never replaces its validation color.
316        let (border, ring) = if invalid {
317            (
318                theme.danger,
319                Some(
320                    theme
321                        .danger
322                        .opacity(if theme.is_dark() { 0.4 } else { 0.2 }),
323                ),
324            )
325        } else if focused && !disabled {
326            (theme.ring, Some(theme.ring.opacity(0.5)))
327        } else {
328            (theme.input, None)
329        };
330        Self {
331            background,
332            border,
333            ring,
334        }
335    }
336}
337
338/// The logical side of an addon relative to the text control.
339#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
340pub enum InputGroupAddonAlignment {
341    #[default]
342    InlineStart,
343    InlineEnd,
344    BlockStart,
345    BlockEnd,
346}
347
348/// Text, icons, buttons, or custom content on one side of an input group.
349///
350/// Children retain their insertion order. Direct `InputGroupButton` children
351/// inherit the group's disabled state. Custom children retain their own semantics.
352#[derive(IntoElement)]
353pub struct InputGroupAddon {
354    id: ElementId,
355    alignment: InputGroupAddonAlignment,
356    style: StyleRefinement,
357    children: Vec<AnyElement>,
358}
359
360impl InputGroupAddon {
361    pub fn new(id: impl Into<ElementId>) -> Self {
362        Self {
363            id: id.into(),
364            alignment: InputGroupAddonAlignment::default(),
365            style: StyleRefinement::default(),
366            children: Vec::new(),
367        }
368    }
369
370    pub fn align(mut self, alignment: InputGroupAddonAlignment) -> Self {
371        self.alignment = alignment;
372        self
373    }
374
375    fn render_in_group(
376        mut self,
377        presentation: GroupPresentation,
378        window: &mut Window,
379        cx: &mut App,
380    ) -> AnyElement {
381        for child in &mut self.children {
382            if let Some(button) = button_element::InputGroupButtonElement::from_element(child) {
383                button.disable(presentation.disabled);
384            }
385        }
386        let border_top = self
387            .style
388            .border_widths
389            .top
390            .is_some_and(|width| width.to_pixels(window.rem_size()) > px(0.));
391        let border_bottom = self
392            .style
393            .border_widths
394            .bottom
395            .is_some_and(|width| width.to_pixels(window.rem_size()) > px(0.));
396        // An inline addon keeps the same clearance from the frame's edge that
397        // a compact button has from its top and bottom; block addons share the
398        // control's horizontal inset so a leading icon or a trailing button
399        // lines up with the text.
400        let block_px = presentation.size.input_px();
401        h_flex()
402            .flex_row_dir(cx)
403            .id(self.id)
404            .test_support()
405            .flex_none()
406            .gap_2()
407            .py_1p5()
408            .when(
409                matches!(presentation.size, Size::XSmall | Size::Small),
410                |this| this.py_0(),
411            )
412            .justify_center()
413            .font_medium()
414            .input_text_size(presentation.size)
415            .text_color(cx.theme().muted_foreground)
416            .cursor_text()
417            .map(|this| match self.alignment {
418                InputGroupAddonAlignment::InlineStart => this.ps(rems(0.375), cx),
419                InputGroupAddonAlignment::InlineEnd => this.pe(rems(0.375), cx),
420                InputGroupAddonAlignment::BlockStart => this
421                    .w_full()
422                    .justify_flex_start()
423                    .px(block_px)
424                    .pt_2()
425                    .when(border_bottom, |this| this.pb_2()),
426                InputGroupAddonAlignment::BlockEnd => this
427                    .w_full()
428                    .justify_flex_start()
429                    .px(block_px)
430                    .pb_2()
431                    .when(border_top, |this| this.pt_2()),
432            })
433            .refine_style(&self.style)
434            .children(self.children.into_iter().map(addon_child))
435            .into_any_element()
436    }
437}
438
439impl ParentElement for InputGroupAddon {
440    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
441        self.children.extend(elements);
442    }
443}
444
445impl Styled for InputGroupAddon {
446    fn style(&mut self) -> &mut StyleRefinement {
447        &mut self.style
448    }
449}
450
451impl RenderOnce for InputGroupAddon {
452    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
453        self.render_in_group(GroupPresentation::default(), window, cx)
454    }
455}
456
457/// The single-line control of a group: an [`Input`] placed in the frame, with
458/// every `Input` capability.
459pub type InputGroupInput = Input;
460
461/// The multi-line control of a group: a [`Textarea`] placed in the frame,
462/// with every `Textarea` capability.
463pub type InputGroupTextarea = Textarea;
464
465/// A single-line input or textarea accepted by [`InputGroup::input`].
466pub struct InputGroupControl(Input);
467
468impl From<Input> for InputGroupControl {
469    fn from(input: Input) -> Self {
470        Self(input)
471    }
472}
473
474impl From<Textarea> for InputGroupControl {
475    fn from(textarea: Textarea) -> Self {
476        Self(textarea.into_input())
477    }
478}
479
480/// A [`Button`] with compact input-group presentation and disabled inheritance.
481///
482/// Ghost and extra-small by default, as in shadcn; `xsmall` and `small` are
483/// the two compact sizes, and a button with only an icon is square at either.
484pub struct InputGroupButton {
485    button: Button,
486    size: Size,
487    style: StyleRefinement,
488}
489
490impl InputGroupButton {
491    pub fn new(id: impl Into<ElementId>) -> Self {
492        Self {
493            button: Button::new(id).ghost(),
494            size: Size::XSmall,
495            style: StyleRefinement::default(),
496        }
497    }
498
499    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
500        self.button = self.button.label(label);
501        self
502    }
503
504    pub fn icon(mut self, icon: impl Into<Icon>) -> Self {
505        self.button = self.button.icon(icon.into());
506        self
507    }
508
509    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
510        self.button = self.button.accessibility_label(label);
511        self
512    }
513
514    pub fn tooltip(mut self, tooltip: impl Into<SharedString>) -> Self {
515        self.button = self.button.tooltip(tooltip);
516        self
517    }
518
519    pub fn tooltip_show_delay(mut self, delay: Duration) -> Self {
520        self.button = self.button.tooltip_show_delay(delay);
521        self
522    }
523
524    pub fn loading(mut self, loading: bool) -> Self {
525        self.button = self.button.loading(loading);
526        self
527    }
528
529    pub fn loading_icon(mut self, icon: impl Into<Icon>) -> Self {
530        self.button = self.button.loading_icon(icon);
531        self
532    }
533
534    pub fn outline(mut self) -> Self {
535        self.button = self.button.outline();
536        self
537    }
538
539    pub fn tab_index(mut self, tab_index: isize) -> Self {
540        self.button = self.button.tab_index(tab_index);
541        self
542    }
543
544    pub fn dropdown_caret(mut self, dropdown_caret: bool) -> Self {
545        self.button = self.button.dropdown_caret(dropdown_caret);
546        self
547    }
548
549    pub fn on_click(
550        mut self,
551        handler: impl Fn(&gpui::ClickEvent, &mut Window, &mut App) + 'static,
552    ) -> Self {
553        self.button = self.button.on_click(handler);
554        self
555    }
556
557    fn render_in_group(self, disabled: bool, window: &mut Window, cx: &mut App) -> AnyElement {
558        let disabled = disabled || self.button.is_disabled();
559        let selected = self.button.is_selected();
560        let icon_only = self.button.is_icon_only();
561        let ghost =
562            matches!(self.button.variant(), ButtonVariant::Ghost) && !self.button.is_outline();
563        let muted = cx.theme().muted;
564        let hover = muted.opacity(if cx.theme().is_dark() { 0.5 } else { 1. });
565        let compact = matches!(self.size, Size::XSmall | Size::Small);
566        let icon_size = match self.size {
567            Size::XSmall => Size::Small,
568            Size::Small => Size::Medium,
569            size => size,
570        };
571        let content_style = div()
572            .text_sm()
573            .line_height(rems(1.25))
574            .map(|this| match self.size {
575                Size::XSmall => this.gap_1(),
576                _ => this.gap_1p5(),
577            })
578            .style()
579            .clone();
580        self.button
581            .when(disabled, |this| this.disabled(true))
582            .map(|this| {
583                if compact {
584                    this.with_size(Size::Medium)
585                        .content_style(content_style, icon_size)
586                } else {
587                    this.with_size(self.size)
588                }
589            })
590            .when(ghost, |this| {
591                this.custom(
592                    ButtonCustomVariant::new(cx)
593                        .color(cx.theme().transparent)
594                        .foreground(cx.theme().foreground)
595                        .hover(hover)
596                        .active(if selected { muted } else { hover }),
597                )
598                .text_color(cx.theme().foreground)
599                .when(disabled, |this| this.opacity(0.5))
600            })
601            .when(disabled, |this| this.focus_ring(false))
602            .text_sm()
603            .font_medium()
604            .border_1()
605            .shadow_none()
606            .map(|this| match (self.size, icon_only) {
607                (Size::XSmall, false) => this.h_6().px_2().rounded(cx.theme().radius_tokens().sm),
608                (Size::XSmall, true) => this.size_6().p_0().rounded(cx.theme().radius_tokens().sm),
609                (Size::Small, false) => this.h_8().px_2p5().rounded(cx.theme().radius),
610                (Size::Small, true) => this.size_8().p_0().rounded(cx.theme().radius),
611                _ => this,
612            })
613            .refine_style(&self.style)
614            .render(window, cx)
615            .into_any_element()
616    }
617}
618
619impl Sizable for InputGroupButton {
620    fn with_size(mut self, size: impl Into<Size>) -> Self {
621        self.size = size.into();
622        self
623    }
624}
625
626impl ButtonVariants for InputGroupButton {
627    fn with_variant(mut self, variant: ButtonVariant) -> Self {
628        self.button = self.button.with_variant(variant);
629        self
630    }
631}
632
633impl Disableable for InputGroupButton {
634    fn disabled(mut self, disabled: bool) -> Self {
635        self.button = self.button.disabled(disabled);
636        self
637    }
638}
639
640impl Selectable for InputGroupButton {
641    fn selected(mut self, selected: bool) -> Self {
642        self.button = self.button.selected(selected);
643        self
644    }
645
646    fn is_selected(&self) -> bool {
647        self.button.is_selected()
648    }
649}
650
651impl InteractiveElement for InputGroupButton {
652    fn interactivity(&mut self) -> &mut Interactivity {
653        self.button.interactivity()
654    }
655}
656
657impl crate::menu::DropdownMenu for InputGroupButton {}
658
659impl IntoElement for InputGroupButton {
660    type Element = AnyElement;
661
662    fn into_element(self) -> Self::Element {
663        button_element::InputGroupButtonElement::new(self).into_any_element()
664    }
665
666    fn into_any_element(self) -> AnyElement {
667        self.into_element()
668    }
669}
670
671impl Styled for InputGroupButton {
672    fn style(&mut self) -> &mut StyleRefinement {
673        &mut self.style
674    }
675}
676
677impl ParentElement for InputGroupButton {
678    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
679        self.button.extend(elements);
680    }
681}
682
683impl RenderOnce for InputGroupButton {
684    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
685        self.render_in_group(false, window, cx)
686    }
687}
688
689/// Muted helper text, optionally combined with icons, inside an input group.
690#[derive(IntoElement, Default)]
691pub struct InputGroupText {
692    style: StyleRefinement,
693    children: Vec<AnyElement>,
694}
695
696impl InputGroupText {
697    pub fn new() -> Self {
698        Self::default()
699    }
700}
701
702impl ParentElement for InputGroupText {
703    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
704        self.children.extend(elements);
705    }
706}
707
708impl Styled for InputGroupText {
709    fn style(&mut self) -> &mut StyleRefinement {
710        &mut self.style
711    }
712}
713
714impl RenderOnce for InputGroupText {
715    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
716        h_flex()
717            .flex_row_dir(cx)
718            .gap_2()
719            .text_sm()
720            .text_color(cx.theme().muted_foreground)
721            .refine_style(&self.style)
722            .children(self.children.into_iter().map(addon_child))
723    }
724}
725
726fn addon_child(mut child: AnyElement) -> AnyElement {
727    if button_element::unwrapped_element(&mut child)
728        .downcast_mut::<ViewElement<Icon>>()
729        .is_some()
730    {
731        // An icon without an explicit size follows the addon's one-rem
732        // default; an explicit size stays with the icon.
733        div()
734            .flex_none()
735            .text_base()
736            .child(child)
737            .into_any_element()
738    } else {
739        child
740    }
741}
742
743#[cfg(test)]
744mod tests;
745
746mod button_element;