use std::{cell::RefCell, rc::Rc};
use arc_motion::{arc_spring_with_options, is_reduced_motion, spring::SpringOptions};
use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, Spacing, SpringSpec, Typography, oklab_mix};
use gpui_kit::{
AnyElement, App, Bounds, ElementId, Entity, FocusHandle, Hsla, IntoElement, KeyDownEvent,
MouseDownEvent, ParentElement, Pixels, RenderOnce, Role, SharedString, Styled,
TestSupportExt as _, Window,
assets::IconName,
base::StyledExt as _,
canvas,
component::{
Icon,
input::{Input as KitInput, InputState},
},
deferred, div,
prelude::*,
px,
};
use super::field_message::render_field_message;
pub const EXPANDING_SEARCH_COLLAPSED_PX: f32 = 36.0;
pub const EXPANDING_SEARCH_EXPANDED_PX: f32 = 320.0;
pub const EXPANDING_SEARCH_MAX_RESULTS: usize = 6;
pub const fn expanding_search_morph_spring() -> SpringSpec {
SpringSpec::visual(0.42, 0.0)
}
#[derive(Clone, Debug, PartialEq)]
pub struct ExpandingSearchItem {
pub id: SharedString,
pub title: SharedString,
pub meta: Option<SharedString>,
pub group: Option<SharedString>,
pub keywords: Vec<SharedString>,
}
impl ExpandingSearchItem {
pub fn new(id: impl Into<SharedString>, title: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
title: title.into(),
meta: None,
group: None,
keywords: Vec::new(),
}
}
pub fn meta(mut self, meta: impl Into<SharedString>) -> Self {
self.meta = Some(meta.into());
self
}
pub fn group(mut self, group: impl Into<SharedString>) -> Self {
self.group = Some(group.into());
self
}
pub fn keywords<I, S>(mut self, keywords: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<SharedString>,
{
self.keywords = keywords.into_iter().map(Into::into).collect();
self
}
}
pub fn expanding_search_rank(
items: &[ExpandingSearchItem],
query: &str,
limit: usize,
) -> Vec<ExpandingSearchItem> {
let q = query.to_lowercase();
let mut scored: Vec<(usize, usize, &ExpandingSearchItem)> = Vec::new();
for (order, item) in items.iter().enumerate() {
let title = item.title.to_lowercase();
let at = title.find(&q);
let extra = item
.meta
.as_ref()
.map(|m| m.to_lowercase().contains(&q))
.unwrap_or(false)
|| item
.keywords
.iter()
.any(|word| word.to_lowercase().contains(&q));
let score = match at {
Some(0) => 0,
Some(at) if at > 0 => {
let prev = title[..at].chars().last().unwrap_or(' ');
if prev == ' ' || prev == '-' || prev == '/' {
1
} else {
2
}
}
_ if extra => 3,
_ => continue,
};
scored.push((score, order, item));
}
scored.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));
scored
.into_iter()
.take(limit)
.map(|(_, _, item)| item.clone())
.collect()
}
pub fn expanding_search_group_by(
list: &[ExpandingSearchItem],
source: &[ExpandingSearchItem],
) -> Vec<(Option<SharedString>, Vec<ExpandingSearchItem>)> {
let mut order: Vec<Option<SharedString>> = Vec::new();
for item in source {
let name = item.group.clone();
if !order.contains(&name) {
order.push(name);
}
}
let mut groups: Vec<(Option<SharedString>, Vec<ExpandingSearchItem>)> = Vec::new();
for item in list {
let name = item.group.clone();
match groups.iter_mut().find(|(g, _)| *g == name) {
Some((_, items)) => items.push(item.clone()),
None => groups.push((name, vec![item.clone()])),
}
}
groups.sort_by_key(|(name, _)| order.iter().position(|n| n == name).unwrap_or(usize::MAX));
groups
}
type SearchSelectHandler = Rc<dyn Fn(&ExpandingSearchItem, &mut Window, &mut App)>;
type SearchExpandHandler = Rc<dyn Fn(&bool, &mut Window, &mut App)>;
#[derive(Clone)]
struct ExpandingSearchInternal {
expanded: bool,
last_query: SharedString,
active_index: i64,
keyboard_moved: bool,
query_input: Entity<InputState>,
focus_handle: FocusHandle,
shell_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
panel_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
}
impl ExpandingSearchInternal {
fn new(window: &mut Window, cx: &mut App) -> Self {
let query_input = cx.new(|cx| InputState::new(window, cx).placeholder("Search"));
Self {
expanded: false,
last_query: "".into(),
active_index: -1,
keyboard_moved: false,
query_input,
focus_handle: cx.focus_handle(),
shell_bounds: Rc::new(RefCell::new(None)),
panel_bounds: Rc::new(RefCell::new(None)),
}
}
}
#[derive(IntoElement)]
pub struct ExpandingSearch {
id: ElementId,
label: SharedString,
items: Vec<ExpandingSearchItem>,
suggestions: Vec<ExpandingSearchItem>,
suggestions_label: SharedString,
placeholder: Option<SharedString>,
expanded_width: Pixels,
max_results: usize,
disabled: bool,
width: Option<Pixels>,
on_select: Option<SearchSelectHandler>,
on_expanded_change: Option<SearchExpandHandler>,
}
impl ExpandingSearch {
pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
label: label.into(),
items: Vec::new(),
suggestions: Vec::new(),
suggestions_label: "Recent".into(),
placeholder: None,
expanded_width: px(EXPANDING_SEARCH_EXPANDED_PX),
max_results: EXPANDING_SEARCH_MAX_RESULTS,
disabled: false,
width: None,
on_select: None,
on_expanded_change: None,
}
}
pub fn items<I>(mut self, items: I) -> Self
where
I: IntoIterator<Item = ExpandingSearchItem>,
{
self.items = items.into_iter().collect();
self
}
pub fn suggestions<I>(mut self, suggestions: I) -> Self
where
I: IntoIterator<Item = ExpandingSearchItem>,
{
self.suggestions = suggestions.into_iter().collect();
self
}
pub fn suggestions_label(mut self, label: impl Into<SharedString>) -> Self {
self.suggestions_label = label.into();
self
}
pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
self.placeholder = Some(placeholder.into());
self
}
pub fn expanded_width(mut self, width: impl Into<Pixels>) -> Self {
self.expanded_width = width.into();
self
}
pub fn max_results(mut self, max: usize) -> Self {
self.max_results = max.max(1);
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn width(mut self, width: impl Into<Pixels>) -> Self {
self.width = Some(width.into());
self
}
pub fn on_select(
mut self,
handler: impl Fn(&ExpandingSearchItem, &mut Window, &mut App) + 'static,
) -> Self {
self.on_select = Some(Rc::new(handler));
self
}
pub fn on_expanded_change(
mut self,
handler: impl Fn(&bool, &mut Window, &mut App) + 'static,
) -> Self {
self.on_expanded_change = Some(Rc::new(handler));
self
}
}
impl RenderOnce for ExpandingSearch {
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 state_id =
ElementId::NamedChild(self.id.clone().into(), "__arc-expanding-state".into());
let internal = window.use_keyed_state(state_id, cx, |window, cx| {
ExpandingSearchInternal::new(window, cx)
});
let expanded = internal.read(cx).expanded && !self.disabled;
let query_raw = internal
.read(cx)
.query_input
.read(cx)
.value()
.trim()
.to_string();
let query = query_raw.clone();
let results = if query.is_empty() {
Vec::new()
} else {
expanding_search_rank(&self.items, &query, self.max_results)
};
let mode: Option<&str> = if query.is_empty() {
if self.suggestions.is_empty() {
None
} else {
Some("suggestions")
}
} else if results.is_empty() {
Some("empty")
} else {
Some("results")
};
let groups = if mode == Some("suggestions") {
vec![(
Some(self.suggestions_label.clone()),
self.suggestions.clone(),
)]
} else if mode == Some("results") {
expanding_search_group_by(&results, &self.items)
} else {
Vec::new()
};
let flat: Vec<ExpandingSearchItem> = groups
.iter()
.flat_map(|(_, items)| items.iter().cloned())
.collect();
let snap_state = internal.read(cx).clone();
let active_index = if snap_state.active_index < 0 {
-1_i64
} else {
(snap_state.active_index as usize).min(flat.len().saturating_sub(1)) as i64
};
let panel_open = expanded && mode.is_some();
let last_query = snap_state.last_query.clone();
if query != last_query {
internal.update(cx, |s, _| {
s.last_query = SharedString::from(query.clone());
s.active_index = if query.is_empty() { -1 } else { 0 };
});
}
let _choose_st = internal.clone();
let choose_ch = self.on_select.clone();
let choose_fn = move |item: ExpandingSearchItem,
st: &gpui_kit::Entity<ExpandingSearchInternal>,
window: &mut Window,
cx: &mut App| {
let q_in = st.read(cx).query_input.clone();
q_in.update(cx, |s, cx| s.set_value("", window, cx));
st.update(cx, |s, _| {
s.expanded = false;
s.last_query = "".into();
s.active_index = -1;
});
if let Some(handler) = &choose_ch {
handler(&item, window, cx);
}
window.refresh();
};
let choose = Rc::new(choose_fn);
let collapsed = EXPANDING_SEARCH_COLLAPSED_PX;
let expanded_w = f32::from(self.expanded_width).max(collapsed);
let goal = if expanded { expanded_w } else { collapsed };
let morph_spec = expanding_search_morph_spring();
let shell_w = if reduced {
goal
} else {
arc_spring_with_options(
(self.id.clone(), "shell-w"),
goal,
SpringOptions::new(morph_spec).with_initial_value(goal),
window,
cx,
)
.value
};
let open_frac = ((shell_w - collapsed) / (expanded_w - collapsed).max(1.0)).clamp(0.0, 1.0);
let radius_px = collapsed / 2.0 + (12.0 - collapsed / 2.0).max(0.0) * open_frac;
let icon_color = colors.text_muted;
let st_click = internal.clone();
let ch_expand = self.on_expanded_change.clone();
let disabled_click = self.disabled;
let focus_click = snap_state.focus_handle.clone();
let query_input_el = KitInput::new(&snap_state.query_input)
.appearance(false)
.w_full()
.text_size(Typography::TEXT_SM);
let _st_key = internal.clone();
let key_flat = flat.clone();
let key_ch = self.on_select.clone();
let key_disabled = self.disabled;
let key_expand = self.on_expanded_change.clone();
let shell_bounds_ref = snap_state.shell_bounds.clone();
let shell_bounds_outside = snap_state.shell_bounds.clone();
let panel_bounds_outside = snap_state.panel_bounds.clone();
let st_outside = internal.clone();
let ch_expand_outside = self.on_expanded_change.clone();
let shell_probe = canvas(
move |rect, _, _| {
*shell_bounds_ref.borrow_mut() = Some(rect);
},
move |_, _, window, _| {
if expanded {
let s_ref = shell_bounds_outside.clone();
let p_ref = panel_bounds_outside.clone();
let st = st_outside.clone();
let ch = ch_expand_outside.clone();
window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
if !phase.bubble() || !st.read(cx).expanded {
return;
}
let in_shell = s_ref.borrow().is_some_and(|b| b.contains(&event.position));
let in_panel = p_ref.borrow().is_some_and(|b| b.contains(&event.position));
if !in_shell && !in_panel {
let q_in = st.read(cx).query_input.clone();
q_in.update(cx, |s, cx| s.set_value("", window, cx));
st.update(cx, |s, _| {
s.expanded = false;
s.last_query = "".into();
s.active_index = -1;
});
if let Some(handler) = &ch {
handler(&false, window, cx);
}
window.refresh();
}
});
}
},
)
.absolute()
.inset_0();
let shell = div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"shell".into(),
))
.test_support()
.role(Role::Search)
.aria_label(self.label.clone())
.track_focus(&snap_state.focus_handle.clone())
.relative()
.w(px(shell_w))
.h(px(collapsed))
.rounded(px(radius_px))
.border_1()
.border_color(if expanded {
colors.control_fill
} else {
colors.border_strong
})
.bg(colors.surface)
.overflow_hidden()
.flex()
.flex_row()
.items_center()
.when(!expanded, |this| this.justify_center())
.when(expanded, |this| this.px(px(12.0)).gap(px(8.0)))
.when(!self.disabled, |this| {
this.cursor_pointer()
.hover(move |s| s.bg(colors.surface_muted))
})
.on_click(move |_, window, cx| {
if disabled_click {
return;
}
let was_open = st_click.read(cx).expanded;
let q_in = st_click.read(cx).query_input.clone();
window.focus(&focus_click.clone(), cx);
q_in.update(cx, |s, cx| s.focus(window, cx));
if !was_open {
st_click.update(cx, |s, _| {
s.expanded = true;
s.active_index = -1;
});
if let Some(handler) = &ch_expand {
handler(&true, window, cx);
}
}
window.refresh();
})
.on_key_down({
let st_open = internal.clone();
move |event: &KeyDownEvent, window, cx| {
if key_disabled {
return;
}
let key = event.keystroke.key.as_str();
let is_open = st_open.read(cx).expanded;
match key {
"escape" if is_open => {
let q_in = st_open.read(cx).query_input.clone();
q_in.update(cx, |s, cx| s.set_value("", window, cx));
st_open.update(cx, |s, _| {
s.expanded = false;
s.last_query = "".into();
s.active_index = -1;
});
if let Some(handler) = &key_expand {
handler(&false, window, cx);
}
window.refresh();
}
"down" | "arrowdown" | "up" | "arrowup"
if is_open && !key_flat.is_empty() =>
{
let len = key_flat.len() as i64;
let cur = st_open.read(cx).active_index;
let step = if key.starts_with("down") { 1 } else { -1 };
let next = if cur < 0 {
if step > 0 { 0 } else { len - 1 }
} else {
(cur + step).rem_euclid(len)
};
st_open.update(cx, |s, _| {
s.active_index = next;
s.keyboard_moved = true;
});
window.refresh();
}
"enter" if is_open && !key_flat.is_empty() => {
let idx = st_open.read(cx).active_index;
if idx >= 0
&& let Some(item) = key_flat.get(idx as usize)
{
let item = item.clone();
let ch = key_ch.clone();
let q_in = st_open.read(cx).query_input.clone();
q_in.update(cx, |s, cx| s.set_value("", window, cx));
st_open.update(cx, |s, _| {
s.expanded = false;
s.last_query = "".into();
s.active_index = -1;
});
if let Some(handler) = &ch {
handler(&item, window, cx);
}
window.refresh();
}
}
_ => {}
}
}
})
.child(shell_probe)
.child(
div()
.w(px(18.0))
.h(px(18.0))
.flex_none()
.flex()
.items_center()
.justify_center()
.child(
Icon::new(IconName::Search)
.text_size(px(16.0))
.text_color(icon_color),
),
)
.when(expanded, |this| {
this.child(
div()
.flex_1()
.min_w_0()
.text_color(colors.foreground)
.child(query_input_el),
)
});
let panel_el = if panel_open {
let st_hover = internal.clone();
let choose_panel = (internal.clone(), choose.clone());
let mut section_els: Vec<AnyElement> = Vec::new();
if mode == Some("empty") {
section_els.push(
div()
.px(px(10.0))
.py(px(12.0))
.flex()
.flex_col()
.gap(px(2.0))
.child(
div()
.text_size(Typography::TEXT_SM)
.text_color(colors.foreground)
.child(SharedString::from(format!(
"No results for \u{201c}{query}\u{201d}"
))),
)
.child(
div()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.child(SharedString::from(
"Try a shorter word or check the spelling.",
)),
)
.into_any_element(),
);
} else {
for (group_name, items) in &groups {
if let Some(name) = group_name {
section_els.push(
div()
.px(px(10.0))
.pt(px(8.0))
.pb(px(2.0))
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.child(name.clone())
.into_any_element(),
);
}
for item in items {
let position = flat.iter().position(|f| f.id == item.id).unwrap_or(0);
let is_active = position as i64 == active_index;
let row_fg = if is_active {
colors.foreground
} else {
colors.text_secondary
};
let item_click = item.clone();
let hover_st = st_hover.clone();
let st_row = choose_panel.0.clone();
let choose_row = choose_panel.1.clone();
section_els.push(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("option-{}", item.id)),
))
.test_support()
.role(Role::ListBoxOption)
.aria_selected(is_active)
.aria_label(item.title.clone())
.w_full()
.min_h(px(36.0))
.px(px(10.0))
.flex()
.flex_row()
.items_center()
.gap(px(8.0))
.rounded(px(10.0))
.text_size(Typography::TEXT_SM)
.text_color(row_fg)
.bg(if is_active {
oklab_mix(colors.foreground, colors.surface_raised, 0.065)
} else {
Hsla::transparent_black()
})
.cursor_pointer()
.on_hover(move |hovered, window, cx| {
if *hovered {
hover_st.update(cx, |s, _| {
s.active_index = position as i64;
s.keyboard_moved = false;
});
window.refresh();
}
})
.on_click(move |_, window, cx| {
choose_row(item_click.clone(), &st_row, window, cx);
})
.child(
div()
.flex()
.flex_col()
.gap(px(1.0))
.min_w_0()
.child(
div()
.font_medium()
.truncate()
.child(item.title.clone()),
)
.when_some(item.meta.clone(), |this, meta| {
this.child(
div()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.truncate()
.child(meta),
)
}),
)
.into_any_element(),
);
}
}
}
let panel_bounds_ref = snap_state.panel_bounds.clone();
let panel_probe = canvas(
move |rect, _, _| {
*panel_bounds_ref.borrow_mut() = Some(rect);
},
|_, _, _, _| {},
)
.absolute()
.inset_0();
Some(
deferred(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"panel".into(),
))
.test_support()
.role(Role::ListBox)
.aria_label(SharedString::from(if mode == Some("suggestions") {
self.suggestions_label.to_string()
} else {
format!("Results for {query}")
}))
.absolute()
.top_full()
.mt(px(6.0))
.left_0()
.w(px(shell_w.max(280.0)))
.p(px(6.0))
.rounded(Radii::CONTROL)
.border_1()
.border_color(colors.border)
.bg(colors.surface_raised)
.shadow(Shadows::floating(theme.mode))
.overflow_hidden()
.child(panel_probe)
.children(section_els),
)
.with_priority(25),
)
} else {
None
};
let msg_id = ElementId::NamedChild(self.id.clone().into(), "message".into());
div()
.id(self.id)
.test_support()
.when_some(self.width, |this, w| this.w(w))
.when(self.width.is_none(), |this| this.w(px(360.0)))
.flex()
.flex_col()
.gap(Spacing::S1)
.child(
div()
.relative()
.w(px(shell_w.max(collapsed)))
.child(shell)
.when_some(panel_el, |this, el| this.child(el)),
)
.child(render_field_message(msg_id, None, false, window, cx))
}
}
#[cfg(test)]
mod tests {
use std::cell::RefCell;
use arc_tokens::{Accent, ThemeMode, install_arc_theme};
use gpui_kit::{Context, Render, TestAppContext, test::TestWindowExt as _};
use super::*;
fn sample_items() -> Vec<ExpandingSearchItem> {
vec![
ExpandingSearchItem::new("proj", "Projects")
.meta("Workspace")
.group("Workspace"),
ExpandingSearchItem::new("docs", "Documentation")
.meta("Wiki")
.group("Workspace"),
ExpandingSearchItem::new("set", "Settings")
.meta("App")
.group("App"),
]
}
#[test]
fn expanding_search_ranks_prefix_then_word_then_substring() {
let items = vec![
ExpandingSearchItem::new("a", "Documents"),
ExpandingSearchItem::new("b", "My Documents"),
ExpandingSearchItem::new("c", "Documenting"),
];
let ranked = expanding_search_rank(&items, "doc", 6);
assert_eq!(ranked[0].id.as_ref(), "a");
assert_eq!(ranked[1].id.as_ref(), "c");
assert_eq!(ranked[2].id.as_ref(), "b");
let items = vec![
ExpandingSearchItem::new("a", "Totally unrelated").keywords(["doc"]),
ExpandingSearchItem::new("b", "Documentation"),
];
let ranked = expanding_search_rank(&items, "doc", 6);
assert_eq!(ranked[0].id.as_ref(), "b");
}
#[test]
fn expanding_search_groups_keep_first_appearance_order() {
let source = vec![
ExpandingSearchItem::new("a", "A").group("Workspace"),
ExpandingSearchItem::new("b", "B").group("App"),
ExpandingSearchItem::new("c", "C").group("Workspace"),
];
let list = vec![
ExpandingSearchItem::new("b", "B").group("App"),
ExpandingSearchItem::new("a", "A").group("Workspace"),
ExpandingSearchItem::new("c", "C").group("Workspace"),
];
let groups = expanding_search_group_by(&list, &source);
assert_eq!(groups[0].0.as_ref().map(|s| s.as_ref()), Some("Workspace"));
assert_eq!(groups[1].0.as_ref().map(|s| s.as_ref()), Some("App"));
}
struct SearchHost {
events: Rc<RefCell<Vec<String>>>,
disabled: bool,
}
impl Render for SearchHost {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let events = self.events.clone();
div().w(px(480.0)).p(px(16.0)).child(
ExpandingSearch::new("search-test", "Search projects and docs")
.items(sample_items())
.suggestions([ExpandingSearchItem::new(
"recent",
"Recent: Deploy pipeline",
)])
.disabled(self.disabled)
.on_select(cx.listener({
let events = events.clone();
move |this, item: &ExpandingSearchItem, _, cx| {
events.borrow_mut().push(item.id.to_string());
let _ = this;
cx.notify();
}
})),
)
}
}
fn search_element(name: &str) -> ElementId {
ElementId::NamedChild(ElementId::Name("search-test".into()).into(), name.into())
}
#[gpui_kit::test]
fn search_expands_filters_selects_and_collapses(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
});
let host = SearchHost {
events: Rc::new(RefCell::new(Vec::new())),
disabled: false,
};
let events = host.events.clone();
let (view, cx) = cx.add_window_view(|_, _| host);
cx.update(|window, cx| {
window.render_frame(cx);
let shell = window.find(search_element("shell"));
assert_eq!(shell.role(), Some(Role::Search));
window.click(search_element("shell"), cx);
window.render_frame(cx);
let panel = window.find(search_element("panel"));
assert_eq!(panel.role(), Some(Role::ListBox));
});
cx.update(|window, cx| {
window.click(search_element("shell"), cx);
});
assert_eq!(events.borrow().as_slice(), Vec::<String>::new().as_slice());
view.update(cx, |host, cx| {
host.disabled = true;
cx.notify();
});
cx.update(|window, cx| {
window.render_frame(cx);
window.click(search_element("shell"), cx);
window.render_frame(cx);
assert!(window.try_find(search_element("panel")).is_none());
});
}
}