1use std::rc::Rc;
8
9use gpui_kit::assets::IconName;
10use gpui_kit::component::input::{Input, InputEvent, InputState};
11use gpui_kit::component::{Icon, h_flex, v_flex};
12use gpui_kit::prelude::FluentBuilder as _;
13use gpui_kit::{
14 App, AppContext as _, Context, Entity, EventEmitter, FontWeight, InteractiveElement as _, IntoElement,
15 KeyDownEvent, ParentElement as _, Render, SharedString, StatefulInteractiveElement as _, Styled as _, Subscription,
16 Window, div, px,
17};
18use kitchen_ui::theme::{self, color};
19
20use crate::command::{CommandSpec, Registry};
21
22#[derive(Clone, Debug, PartialEq, Eq)]
24pub enum SearchEvent {
25 Close,
27 Run(SharedString),
30}
31
32pub type Filter = Rc<dyn Fn(&CommandSpec) -> bool>;
34
35#[derive(Clone)]
37pub struct Row {
38 pub command: CommandSpec,
40 pub disabled: Option<String>,
42}
43
44pub struct Search {
46 registry: Registry,
47 filter: Option<Filter>,
48 input: Entity<InputState>,
49 title: SharedString,
50 cursor: usize,
52 _subs: Vec<Subscription>,
53}
54
55impl EventEmitter<SearchEvent> for Search {}
56
57const SHOWN: usize = 50;
59const ROW_H: f32 = 48.;
61
62impl Search {
63 pub fn new(registry: Registry, window: &mut Window, cx: &mut Context<Self>) -> Self {
65 let input = cx.new(|cx| InputState::new(window, cx).placeholder("Search commands…"));
66 let subs = vec![cx.subscribe_in(&input, window, |this, _, e: &InputEvent, _, cx| match e {
67 InputEvent::PressEnter { .. } => this.run_cursor(cx),
68 InputEvent::Change => {
69 this.cursor = this.first_enabled(cx);
70 cx.notify()
71 }
72 _ => {}
73 })];
74 let focus = gpui_kit::Focusable::focus_handle(input.read(cx), cx);
75 window.focus(&focus, cx);
76 let mut s = Self { registry, filter: None, input, title: "Search".into(), cursor: 0, _subs: subs };
77 s.cursor = s.first_enabled(cx);
78 s
79 }
80
81 pub fn filter(mut self, filter: impl Fn(&CommandSpec) -> bool + 'static) -> Self {
83 self.filter = Some(Rc::new(filter));
84 self
85 }
86
87 pub fn title(mut self, title: impl Into<SharedString>) -> Self {
89 self.title = title.into();
90 self
91 }
92
93 pub fn placeholder(self, text: impl Into<SharedString>, window: &mut Window, cx: &mut Context<Self>) -> Self {
95 let text: SharedString = text.into();
96 self.input.update(cx, |i, cx| i.set_placeholder(text, window, cx));
97 self
98 }
99
100 pub fn set_query(&mut self, query: &str, window: &mut Window, cx: &mut Context<Self>) {
102 let q = query.to_string();
103 self.input.update(cx, |i, cx| i.set_value(q, window, cx));
104 self.cursor = self.first_enabled(cx);
105 cx.notify();
106 }
107
108 pub fn rows(&self, cx: &App) -> Vec<Row> {
110 let q = self.input.read(cx).value().to_lowercase();
111 let words: Vec<&str> = q.split_whitespace().collect();
112 let mut rows: Vec<Row> = self
113 .registry
114 .all()
115 .into_iter()
116 .filter(|c| self.filter.as_ref().is_none_or(|f| f(c)))
117 .filter(|c| {
118 let hay =
119 format!("{} {} {} {}", c.group, c.title, c.hint, c.key_label().unwrap_or_default()).to_lowercase();
120 words.iter().all(|w| hay.contains(w))
121 })
122 .map(|c| Row { disabled: (c.enabled)(cx).err(), command: c })
123 .collect();
124 let order: Vec<SharedString> = rows.iter().map(|r| r.command.group.clone()).fold(Vec::new(), |mut v, g| {
126 if !v.contains(&g) {
127 v.push(g);
128 }
129 v
130 });
131 rows.sort_by_key(|r| order.iter().position(|g| *g == r.command.group));
132 rows.truncate(SHOWN);
133 rows
134 }
135
136 pub fn cursor(&self) -> usize {
138 self.cursor
139 }
140
141 fn first_enabled(&self, cx: &App) -> usize {
142 self.rows(cx).iter().position(|r| r.disabled.is_none()).unwrap_or(0)
143 }
144
145 fn run_cursor(&mut self, cx: &mut Context<Self>) {
146 if let Some(r) = self.rows(cx).into_iter().nth(self.cursor).filter(|r| r.disabled.is_none()) {
147 cx.emit(SearchEvent::Run(r.command.id));
148 }
149 }
150
151 fn on_key(&mut self, e: &KeyDownEvent, _: &mut Window, cx: &mut Context<Self>) {
152 let rows = self.rows(cx);
153 let enabled: Vec<usize> =
154 rows.iter().enumerate().filter(|(_, r)| r.disabled.is_none()).map(|(i, _)| i).collect();
155 let at = enabled.iter().position(|&i| i == self.cursor);
156 match e.keystroke.key.as_str() {
157 "down" if !enabled.is_empty() => self.cursor = enabled[at.map_or(0, |i| (i + 1).min(enabled.len() - 1))],
158 "up" if !enabled.is_empty() => self.cursor = enabled[at.map_or(0, |i| i.saturating_sub(1))],
159 "escape" => cx.emit(SearchEvent::Close),
160 "enter" => {
161 self.run_cursor(cx);
162 cx.stop_propagation();
163 return;
164 }
165 _ => return,
166 }
167 cx.stop_propagation();
168 cx.notify();
169 }
170}
171
172impl Render for Search {
173 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
174 let rows = self.rows(cx);
175 let cursor = self.cursor;
176 let mut list = v_flex().id("search-rows").flex_1().min_h_0().overflow_y_scroll();
177 let mut last_group = SharedString::default();
178 if rows.is_empty() {
179 list = list
180 .child(div().p(px(theme::MD)).text_sm().text_color(color::text_muted()).child("No command matches."));
181 }
182 for (i, r) in rows.into_iter().enumerate() {
183 let c = r.command;
184 if c.group != last_group {
185 last_group = c.group.clone();
186 list = list.child(
187 div()
188 .px(px(theme::SM))
189 .pt(px(if i == 0 { theme::XS } else { theme::MD }))
190 .pb(px(theme::XS))
191 .text_xs()
192 .font_weight(FontWeight::SEMIBOLD)
193 .text_color(color::text_muted())
194 .child(c.group.clone()),
195 );
196 }
197 let enabled = r.disabled.is_none();
198 let line: SharedString = r.disabled.map(SharedString::from).unwrap_or(c.hint.clone());
199 let me = cx.entity().downgrade();
200 let id = c.id.clone();
201 list = list.child(
202 h_flex()
203 .id(SharedString::from(format!("search-row-{}", c.id)))
204 .min_h(px(ROW_H))
205 .px(px(theme::SM))
206 .gap(px(theme::MD))
207 .rounded(px(theme::RADIUS))
208 .when(enabled && i == cursor, |d| d.bg(color::control()))
209 .when(enabled, |d| {
210 d.cursor_pointer().hover(|d| d.bg(color::control())).on_click(move |_, _, cx| {
211 let id = id.clone();
212 let _ = me.update(cx, |_, cx| cx.emit(SearchEvent::Run(id)));
213 })
214 })
215 .child(
216 div()
217 .flex_none()
218 .size(px(32.))
219 .rounded(px(theme::RADIUS))
220 .border_1()
221 .border_color(color::hover())
222 .flex()
223 .items_center()
224 .justify_center()
225 .child(Icon::new(c.icon).text_color(if enabled {
226 color::text()
227 } else {
228 color::text_disabled()
229 })),
230 )
231 .child(
232 v_flex()
233 .flex_1()
234 .min_w_0()
235 .child(
236 div()
237 .text_sm()
238 .font_weight(FontWeight::SEMIBOLD)
239 .truncate()
240 .text_color(if enabled { color::text() } else { color::text_disabled() })
241 .child(c.title.clone()),
242 )
243 .child(div().text_xs().text_color(color::text_muted()).truncate().child(line)),
244 )
245 .children(c.key_label().map(|k| {
246 div().flex_none().text_xs().font_family("monospace").text_color(color::text_muted()).child(k)
247 })),
248 );
249 }
250 let (back, close) = (cx.entity().downgrade(), cx.entity().downgrade());
251 div()
252 .id("search-backdrop")
253 .absolute()
254 .top_0()
255 .left_0()
256 .size_full()
257 .flex()
258 .items_start()
259 .justify_center()
260 .pt(px(72.))
261 .px(px(theme::LG))
262 .bg(gpui_kit::black().opacity(0.35))
263 .on_click(move |_, _, cx| {
264 let _ = back.update(cx, |_, cx| cx.emit(SearchEvent::Close));
265 })
266 .child(
267 v_flex()
268 .id("search")
269 .occlude()
270 .w_full()
272 .max_w(px(560.))
273 .max_h(gpui_kit::relative(0.8))
274 .p(px(theme::SM))
275 .gap(px(theme::XS))
276 .rounded(px(theme::RADIUS_LG))
277 .border_1()
278 .border_color(color::border())
279 .bg(color::raised())
280 .text_color(color::text())
281 .shadow_lg()
282 .capture_key_down(cx.listener(Self::on_key))
283 .on_click(|_, _, cx| cx.stop_propagation())
284 .child(
285 h_flex()
286 .px(px(theme::SM))
287 .py(px(theme::XS))
288 .gap(px(theme::SM))
289 .items_center()
290 .child(div().text_sm().font_weight(FontWeight::SEMIBOLD).child(self.title.clone()))
291 .child(div().text_xs().text_color(color::text_muted()).child("↑ ↓ Enter · Esc"))
292 .child(div().flex_1())
293 .child(
294 kitchen_ui::widgets::icon_button("search-close", IconName::Close, "Close (Esc)")
295 .on_click(move |_, _, cx| {
296 let _ = close.update(cx, |_, cx| cx.emit(SearchEvent::Close));
297 }),
298 ),
299 )
300 .child(Input::new(&self.input))
301 .child(list),
302 )
303 }
304}