Skip to main content

arc_ui/inputs/
search_field.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/search-field/search-field.tsx` & `.module.css`
3//!
4//! P2 Component #18: `search-field`
5//!
6//! - Leading `IconName::Search` wakes from `text_muted` to `foreground` when focused or filled.
7//! - Trailing reserved `24×24px` clear slot prevents horizontal shift; clear button enters/exits
8//!   with `scale 0.8 -> 1.0` (`snappy`) + `BlurFallback::subtle`, and returns focus on clear.
9
10use std::{rc::Rc, time::Duration};
11
12use arc_motion::{BlurFallback, arc_spring, arc_transition, is_reduced_motion};
13use arc_tokens::{ActiveArcTheme as _, ControlHeights, Radii, Spacing, Typography};
14use gpui_kit::{
15    App, ElementId, Entity, Focusable as _, IntoElement, ParentElement, RenderOnce, SharedString,
16    Styled, Window,
17    assets::IconName,
18    base::{Button as BaseButton, StyledExt as _},
19    component::{
20        Icon,
21        input::{Input as KitInput, InputState},
22    },
23    div,
24    prelude::*,
25    px,
26};
27
28type ClearHandler = Rc<dyn Fn(&(), &mut Window, &mut App)>;
29
30/// Arc `SearchField` — search input with adaptive magnifier contrast and animated clear slot.
31#[derive(IntoElement)]
32pub struct SearchField {
33    id: ElementId,
34    label: SharedString,
35    state: Entity<InputState>,
36    clear_label: SharedString,
37    disabled: bool,
38    on_clear: Option<ClearHandler>,
39}
40
41impl SearchField {
42    pub fn new(
43        id: impl Into<ElementId>,
44        label: impl Into<SharedString>,
45        state: &Entity<InputState>,
46    ) -> Self {
47        Self {
48            id: id.into(),
49            label: label.into(),
50            state: state.clone(),
51            clear_label: "Clear search".into(),
52            disabled: false,
53            on_clear: None,
54        }
55    }
56
57    pub fn clear_label(mut self, label: impl Into<SharedString>) -> Self {
58        self.clear_label = label.into();
59        self
60    }
61
62    pub fn disabled(mut self, disabled: bool) -> Self {
63        self.disabled = disabled;
64        self
65    }
66
67    pub fn on_clear(mut self, handler: impl Fn(&(), &mut Window, &mut App) + 'static) -> Self {
68        self.on_clear = Some(Rc::new(handler));
69        self
70    }
71}
72
73impl RenderOnce for SearchField {
74    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
75        let theme = cx.arc_theme().clone();
76        let colors = theme.colors;
77        let motion = theme.motion;
78        let reduced = is_reduced_motion(cx);
79
80        let filled = !self.state.read(cx).value().is_empty();
81        let is_focused = self.state.read(cx).focus_handle(cx).is_focused(window);
82        let active_glass = filled || is_focused;
83
84        let clear_scale = if reduced {
85            if filled { 1.0 } else { 0.8 }
86        } else {
87            arc_spring(
88                (self.id.clone(), "clear-scale"),
89                if filled { 1.0 } else { 0.8 },
90                motion.spring.snappy,
91                window,
92                cx,
93            )
94        };
95        let clear_op = arc_transition(
96            (self.id.clone(), "clear-op"),
97            if filled { 1.0 } else { 0.0 },
98            if reduced {
99                motion.duration.instant
100            } else if filled {
101                motion.duration.fast
102            } else {
103                motion.duration.instant
104            },
105            motion.ease.standard,
106            window,
107            cx,
108        );
109        let blur = BlurFallback::evaluate(motion.blur.subtle * (1.0 - clear_op), reduced);
110        let show_clear = filled || clear_op > 0.02;
111
112        let border_color = if is_focused {
113            colors.foreground
114        } else {
115            colors.border_strong
116        };
117        let hover_border = colors.foreground;
118        let hover_bg = colors.surface_muted;
119        let hover_fg = colors.foreground;
120
121        let clear_state = self.state.clone();
122        let on_clear = self.on_clear.clone();
123        let disabled = self.disabled;
124
125        let clear_slot = div()
126            .w(px(24.0))
127            .h(px(24.0))
128            .flex_none()
129            .flex()
130            .items_center()
131            .justify_center()
132            .when(show_clear && !disabled, |this| {
133                let sz = (24.0 * clear_scale).clamp(16.0, 26.0);
134                let icon_sz = (15.0 * clear_scale).clamp(11.0, 17.0);
135                this.child(
136                    BaseButton::new(ElementId::NamedChild(
137                        self.id.clone().into(),
138                        "clear-btn".into(),
139                    ))
140                    .accessibility_label(self.clear_label)
141                    .on_click(move |_, window, cx| {
142                        clear_state.update(cx, |s, cx| {
143                            s.clean(window, cx);
144                            s.focus(window, cx);
145                        });
146                        if let Some(cb) = &on_clear {
147                            cb(&(), window, cx);
148                        }
149                        window.refresh();
150                    })
151                    .w(px(sz))
152                    .h(px(sz))
153                    .flex()
154                    .items_center()
155                    .justify_center()
156                    .rounded(Radii::CONTROL)
157                    .opacity((clear_op * blur.opacity_multiplier).clamp(0.0, 1.0))
158                    .text_color(colors.text_muted)
159                    .cursor_pointer()
160                    .hover(move |s| s.bg(hover_bg).text_color(hover_fg))
161                    .child(Icon::new(IconName::X).text_size(px(icon_sz))),
162                )
163            });
164
165        let _ = Duration::ZERO;
166        let shell =
167            div()
168                .w_full()
169                .min_h(ControlHeights::MD)
170                .px(Spacing::S3)
171                .flex()
172                .flex_row()
173                .items_center()
174                .gap(Spacing::S2)
175                .rounded(Radii::CONTROL)
176                .border_1()
177                .border_color(border_color)
178                .bg(if self.disabled {
179                    colors.surface_muted
180                } else {
181                    colors.surface
182                })
183                .when(self.disabled, |this| this.opacity(0.5))
184                .when(!self.disabled && !is_focused, |this| {
185                    this.hover(move |s| s.border_color(hover_border))
186                })
187                .child(Icon::new(IconName::Search).text_size(px(17.0)).text_color(
188                    if active_glass {
189                        colors.foreground
190                    } else {
191                        colors.text_muted
192                    },
193                ))
194                .child(
195                    div()
196                        .flex_1()
197                        .min_w_0()
198                        .text_size(Typography::TEXT_SM)
199                        .text_color(colors.foreground)
200                        .child(
201                            KitInput::new(&self.state)
202                                .appearance(false)
203                                .disabled(self.disabled)
204                                .w_full(),
205                        ),
206                )
207                .child(clear_slot);
208
209        div()
210            .id(self.id)
211            .w_full()
212            .flex()
213            .flex_col()
214            .gap(Spacing::S2)
215            .child(
216                div()
217                    .text_size(Typography::TEXT_SM)
218                    .font_medium()
219                    .text_color(colors.foreground)
220                    .child(self.label),
221            )
222            .child(shell)
223    }
224}
225
226#[cfg(test)]
227mod tests {
228    use std::{cell::Cell, rc::Rc};
229
230    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
231    use gpui_kit::{
232        Context, MouseButton, Render, Role, TestAppContext, div,
233        test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
234    };
235
236    use super::*;
237
238    struct SearchHost {
239        state: Entity<InputState>,
240        cleared: Rc<Cell<usize>>,
241    }
242
243    impl Render for SearchHost {
244        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
245            let cleared = self.cleared.clone();
246            div().w(px(360.0)).p(Spacing::S4).child(
247                SearchField::new("search", "Search docs", &self.state).on_clear(move |_, _, _| {
248                    cleared.set(cleared.get() + 1);
249                }),
250            )
251        }
252    }
253
254    #[gpui_kit::test]
255    fn search_field_clears_text_and_invokes_callback(cx: &mut TestAppContext) {
256        cx.update(|cx| {
257            gpui_kit::init(cx);
258            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
259        });
260        let cleared = Rc::new(Cell::new(0));
261        let (view, cx) = cx.add_window_view(|window, cx| {
262            let state = cx.new(|cx| {
263                InputState::new(window, cx)
264                    .placeholder("Filter components...")
265                    .default_value("elastic")
266            });
267            SearchHost {
268                state,
269                cleared: cleared.clone(),
270            }
271        });
272
273        cx.update(|window, cx| {
274            window.render_frame(cx);
275            let clear = window.find_by_label("Clear search");
276            assert_eq!(clear.role(), Some(Role::Button));
277            let pos = clear.bounds().center();
278            window.pointer_down(pos, MouseButton::Left, cx);
279            window.pointer_up(pos, MouseButton::Left, cx);
280            window.render_frame(cx);
281
282            let state = view.read(cx).state.clone();
283            assert_eq!(state.read(cx).value(), "");
284        });
285
286        assert_eq!(cleared.get(), 1);
287    }
288}