arc-ui 0.4.0

Physics-first native Rust desktop UI component library & charts for GPUI (120+ interactive components ported from Arc).
Documentation
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: `Arc源码/arc-library/registry/components/search-field/search-field.tsx` & `.module.css`
//!
//! P2 Component #18: `search-field`
//!
//! - Leading `IconName::Search` wakes from `text_muted` to `foreground` when focused or filled.
//! - Trailing reserved `24×24px` clear slot prevents horizontal shift; clear button enters/exits
//!   with `scale 0.8 -> 1.0` (`snappy`) + `BlurFallback::subtle`, and returns focus on clear.

use std::{rc::Rc, time::Duration};

use arc_motion::{BlurFallback, arc_spring, arc_transition, is_reduced_motion};
use arc_tokens::{ActiveArcTheme as _, ControlHeights, Radii, Spacing, Typography};
use gpui_kit::{
    App, ElementId, Entity, Focusable as _, IntoElement, ParentElement, RenderOnce, SharedString,
    Styled, Window,
    assets::IconName,
    base::{Button as BaseButton, StyledExt as _},
    component::{
        Icon,
        input::{Input as KitInput, InputState},
    },
    div,
    prelude::*,
    px,
};

type ClearHandler = Rc<dyn Fn(&(), &mut Window, &mut App)>;

/// Arc `SearchField` — search input with adaptive magnifier contrast and animated clear slot.
#[derive(IntoElement)]
pub struct SearchField {
    id: ElementId,
    label: SharedString,
    state: Entity<InputState>,
    clear_label: SharedString,
    disabled: bool,
    on_clear: Option<ClearHandler>,
}

impl SearchField {
    pub fn new(
        id: impl Into<ElementId>,
        label: impl Into<SharedString>,
        state: &Entity<InputState>,
    ) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            state: state.clone(),
            clear_label: "Clear search".into(),
            disabled: false,
            on_clear: None,
        }
    }

    pub fn clear_label(mut self, label: impl Into<SharedString>) -> Self {
        self.clear_label = label.into();
        self
    }

    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    pub fn on_clear(mut self, handler: impl Fn(&(), &mut Window, &mut App) + 'static) -> Self {
        self.on_clear = Some(Rc::new(handler));
        self
    }
}

impl RenderOnce for SearchField {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let theme = cx.arc_theme().clone();
        let colors = theme.colors;
        let motion = theme.motion;
        let reduced = is_reduced_motion(cx);

        let filled = !self.state.read(cx).value().is_empty();
        let is_focused = self.state.read(cx).focus_handle(cx).is_focused(window);
        let active_glass = filled || is_focused;

        let clear_scale = if reduced {
            if filled { 1.0 } else { 0.8 }
        } else {
            arc_spring(
                (self.id.clone(), "clear-scale"),
                if filled { 1.0 } else { 0.8 },
                motion.spring.snappy,
                window,
                cx,
            )
        };
        let clear_op = arc_transition(
            (self.id.clone(), "clear-op"),
            if filled { 1.0 } else { 0.0 },
            if reduced {
                motion.duration.instant
            } else if filled {
                motion.duration.fast
            } else {
                motion.duration.instant
            },
            motion.ease.standard,
            window,
            cx,
        );
        let blur = BlurFallback::evaluate(motion.blur.subtle * (1.0 - clear_op), reduced);
        let show_clear = filled || clear_op > 0.02;

        let border_color = if is_focused {
            colors.foreground
        } else {
            colors.border_strong
        };
        let hover_border = colors.foreground;
        let hover_bg = colors.surface_muted;
        let hover_fg = colors.foreground;

        let clear_state = self.state.clone();
        let on_clear = self.on_clear.clone();
        let disabled = self.disabled;

        let clear_slot = div()
            .w(px(24.0))
            .h(px(24.0))
            .flex_none()
            .flex()
            .items_center()
            .justify_center()
            .when(show_clear && !disabled, |this| {
                let sz = (24.0 * clear_scale).clamp(16.0, 26.0);
                let icon_sz = (15.0 * clear_scale).clamp(11.0, 17.0);
                this.child(
                    BaseButton::new(ElementId::NamedChild(
                        self.id.clone().into(),
                        "clear-btn".into(),
                    ))
                    .accessibility_label(self.clear_label)
                    .on_click(move |_, window, cx| {
                        clear_state.update(cx, |s, cx| {
                            s.clean(window, cx);
                            s.focus(window, cx);
                        });
                        if let Some(cb) = &on_clear {
                            cb(&(), window, cx);
                        }
                        window.refresh();
                    })
                    .w(px(sz))
                    .h(px(sz))
                    .flex()
                    .items_center()
                    .justify_center()
                    .rounded(Radii::CONTROL)
                    .opacity((clear_op * blur.opacity_multiplier).clamp(0.0, 1.0))
                    .text_color(colors.text_muted)
                    .cursor_pointer()
                    .hover(move |s| s.bg(hover_bg).text_color(hover_fg))
                    .child(Icon::new(IconName::X).text_size(px(icon_sz))),
                )
            });

        let _ = Duration::ZERO;
        let shell =
            div()
                .w_full()
                .min_h(ControlHeights::MD)
                .px(Spacing::S3)
                .flex()
                .flex_row()
                .items_center()
                .gap(Spacing::S2)
                .rounded(Radii::CONTROL)
                .border_1()
                .border_color(border_color)
                .bg(if self.disabled {
                    colors.surface_muted
                } else {
                    colors.surface
                })
                .when(self.disabled, |this| this.opacity(0.5))
                .when(!self.disabled && !is_focused, |this| {
                    this.hover(move |s| s.border_color(hover_border))
                })
                .child(Icon::new(IconName::Search).text_size(px(17.0)).text_color(
                    if active_glass {
                        colors.foreground
                    } else {
                        colors.text_muted
                    },
                ))
                .child(
                    div()
                        .flex_1()
                        .min_w_0()
                        .text_size(Typography::TEXT_SM)
                        .text_color(colors.foreground)
                        .child(
                            KitInput::new(&self.state)
                                .appearance(false)
                                .disabled(self.disabled)
                                .w_full(),
                        ),
                )
                .child(clear_slot);

        div()
            .id(self.id)
            .w_full()
            .flex()
            .flex_col()
            .gap(Spacing::S2)
            .child(
                div()
                    .text_size(Typography::TEXT_SM)
                    .font_medium()
                    .text_color(colors.foreground)
                    .child(self.label),
            )
            .child(shell)
    }
}

#[cfg(test)]
mod tests {
    use std::{cell::Cell, rc::Rc};

    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
    use gpui_kit::{
        Context, MouseButton, Render, Role, TestAppContext, div,
        test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
    };

    use super::*;

    struct SearchHost {
        state: Entity<InputState>,
        cleared: Rc<Cell<usize>>,
    }

    impl Render for SearchHost {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            let cleared = self.cleared.clone();
            div().w(px(360.0)).p(Spacing::S4).child(
                SearchField::new("search", "Search docs", &self.state).on_clear(move |_, _, _| {
                    cleared.set(cleared.get() + 1);
                }),
            )
        }
    }

    #[gpui_kit::test]
    fn search_field_clears_text_and_invokes_callback(cx: &mut TestAppContext) {
        cx.update(|cx| {
            gpui_kit::init(cx);
            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
        });
        let cleared = Rc::new(Cell::new(0));
        let (view, cx) = cx.add_window_view(|window, cx| {
            let state = cx.new(|cx| {
                InputState::new(window, cx)
                    .placeholder("Filter components...")
                    .default_value("elastic")
            });
            SearchHost {
                state,
                cleared: cleared.clone(),
            }
        });

        cx.update(|window, cx| {
            window.render_frame(cx);
            let clear = window.find_by_label("Clear search");
            assert_eq!(clear.role(), Some(Role::Button));
            let pos = clear.bounds().center();
            window.pointer_down(pos, MouseButton::Left, cx);
            window.pointer_up(pos, MouseButton::Left, cx);
            window.render_frame(cx);

            let state = view.read(cx).state.clone();
            assert_eq!(state.read(cx).value(), "");
        });

        assert_eq!(cleared.get(), 1);
    }
}