1use std::{collections::HashMap, time::Duration};
2
3use gpui::{
4 App, AppContext, Context, ElementId, Entity, EntityInputHandler, EventEmitter, FocusHandle,
5 Focusable, ListAlignment, ListState, SharedString, Subscription, Window, px,
6};
7use gpui_base::motion::Easing;
8use gpui_material_components::{IconName, TextFieldEvent, TextFieldState};
9use gpui_material_foundation::RetargetTransition;
10
11mod presentation;
12mod scroll;
13
14pub use presentation::{
15 SearchBar, SearchMotion, SearchPopupOptions, SearchScrim, SearchStyle, SearchView,
16 SearchViewVariant, SearchWindowOptions,
17};
18pub use scroll::SearchScrollState;
19
20#[derive(Clone, Debug, PartialEq, Eq)]
22pub struct SearchRequest {
23 revision: u64,
24 query: SharedString,
25}
26
27impl SearchRequest {
28 pub fn query(&self) -> &SharedString {
30 &self.query
31 }
32}
33
34#[derive(Clone, Debug, PartialEq, Eq)]
36pub struct SearchResult {
37 id: ElementId,
38 label: SharedString,
39 supporting: Option<SharedString>,
40 group: Option<SharedString>,
41 icon: Option<IconName>,
42}
43
44impl SearchResult {
45 pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
47 Self {
48 id: id.into(),
49 label: label.into(),
50 supporting: None,
51 group: None,
52 icon: None,
53 }
54 }
55
56 pub fn supporting(mut self, text: impl Into<SharedString>) -> Self {
58 self.supporting = Some(text.into());
59 self
60 }
61
62 pub fn group(mut self, heading: impl Into<SharedString>) -> Self {
64 self.group = Some(heading.into());
65 self
66 }
67
68 pub fn icon(mut self, icon: IconName) -> Self {
70 self.icon = Some(icon);
71 self
72 }
73
74 pub fn group_label(&self) -> Option<&SharedString> {
76 self.group.as_ref()
77 }
78
79 pub fn id(&self) -> &ElementId {
81 &self.id
82 }
83
84 pub fn label(&self) -> &SharedString {
86 &self.label
87 }
88}
89
90#[derive(Clone, Debug, PartialEq, Eq)]
92pub enum SearchOutcome {
93 Results(Vec<SearchResult>),
95 Error(SharedString),
97}
98
99#[derive(Clone, Debug)]
102pub enum SearchEvent {
103 Request(SearchRequest),
105 Submit(SharedString),
107 Select(SearchResult),
109}
110
111enum Results {
112 Idle,
113 Loading,
114 Ready(SearchOutcome),
115}
116
117struct SearchResponse {
118 revision: u64,
119 pending: Option<SearchRequest>,
120 results: Results,
121}
122
123impl Default for SearchResponse {
124 fn default() -> Self {
125 Self {
126 revision: 0,
127 pending: None,
128 results: Results::Idle,
129 }
130 }
131}
132
133impl SearchResponse {
134 fn begin(&mut self, query: SharedString) -> Option<SearchRequest> {
135 self.revision = self
136 .revision
137 .checked_add(1)
138 .expect("search revision exhausted");
139 self.pending = (!query.trim().is_empty()).then_some(SearchRequest {
140 revision: self.revision,
141 query,
142 });
143 self.results = if self.pending.is_some() {
144 Results::Loading
145 } else {
146 Results::Idle
147 };
148 self.pending.clone()
149 }
150
151 fn finish(&mut self, request: &SearchRequest, outcome: SearchOutcome) -> bool {
152 if self.pending.as_ref() != Some(request) {
153 return false;
154 }
155 self.pending = None;
156 self.results = Results::Ready(outcome);
157 true
158 }
159}
160
161#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
163pub enum SearchValue {
164 #[default]
166 Collapsed,
167 Expanded,
169}
170
171impl SearchValue {
172 fn progress(self) -> f32 {
173 match self {
174 Self::Collapsed => 0.,
175 Self::Expanded => 1.,
176 }
177 }
178}
179
180pub struct SearchState {
183 input: Entity<TextFieldState>,
184 trigger: FocusHandle,
185 scope: FocusHandle,
186 results_scope: FocusHandle,
187 restore: Option<FocusHandle>,
188 scroll: ListState,
189 result_focus: HashMap<ElementId, FocusHandle>,
190 active_result: Option<ElementId>,
191 result_layout: Option<(gpui_material_theme::Typography, gpui::Pixels, u64)>,
192 query: SharedString,
193 response: SearchResponse,
194 target: SearchValue,
195 progress: f32,
196 animation: RetargetTransition,
197 last_sampled: Option<gpui_material_foundation::Instant>,
198 _input: Subscription,
199}
200
201impl EventEmitter<SearchEvent> for SearchState {}
202
203impl SearchState {
204 pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
206 let input = cx.new(|cx| TextFieldState::new(window, cx));
207 Self::with_editor(&input, window, cx)
208 }
209
210 pub fn with_editor(
212 input: &Entity<TextFieldState>,
213 window: &mut Window,
214 cx: &mut Context<Self>,
215 ) -> Self {
216 let subscription = cx.subscribe_in(input, window, |state, input, event, window, cx| {
217 if !state.is_open()
218 || !matches!(
219 event,
220 TextFieldEvent::Change
221 | TextFieldEvent::PressEnter {
222 secondary: false,
223 shift: false
224 }
225 )
226 {
227 return;
228 }
229 if input.update(cx, |input, cx| {
230 input.marked_text_range(window, cx).is_some()
231 }) {
232 return;
233 }
234 let query = input.read(cx).value();
235 state.update_query(query.clone(), cx);
236 if matches!(event, TextFieldEvent::PressEnter { .. }) && !query.trim().is_empty() {
237 cx.emit(SearchEvent::Submit(query));
238 }
239 });
240 Self {
241 input: input.clone(),
242 trigger: cx.focus_handle(),
243 scope: cx.focus_handle(),
244 results_scope: cx.focus_handle().tab_stop(false),
245 restore: None,
246 scroll: ListState::new(0, ListAlignment::Top, px(100.)),
247 result_focus: HashMap::new(),
248 active_result: None,
249 result_layout: None,
250 query: "".into(),
251 response: SearchResponse::default(),
252 target: SearchValue::Collapsed,
253 progress: 0.,
254 animation: RetargetTransition::settled(0.),
255 last_sampled: None,
256 _input: subscription,
257 }
258 }
259
260 pub fn query(&self) -> &SharedString {
262 &self.query
263 }
264
265 pub fn is_open(&self) -> bool {
267 self.target == SearchValue::Expanded
268 }
269
270 pub fn current_value(&self) -> SearchValue {
272 if self.progress <= 0.02 {
273 SearchValue::Collapsed
274 } else {
275 SearchValue::Expanded
276 }
277 }
278
279 pub fn target_value(&self) -> SearchValue {
281 self.target
282 }
283
284 pub fn progress(&self) -> f32 {
286 self.progress
287 }
288
289 pub fn is_animating(&self) -> bool {
291 self.animation.is_animating()
292 }
293
294 pub fn editor(&self) -> &Entity<TextFieldState> {
296 &self.input
297 }
298
299 pub fn input_focus(&self, cx: &App) -> FocusHandle {
301 self.input.read(cx).focus_handle(cx)
302 }
303
304 pub fn trigger_focus(&self) -> &FocusHandle {
306 &self.trigger
307 }
308
309 pub fn open(&mut self, window: &mut Window, cx: &mut Context<Self>) {
311 self.snap_to(1., window, cx);
312 }
313
314 pub fn close(&mut self, window: &mut Window, cx: &mut Context<Self>) {
316 self.snap_to(0., window, cx);
317 }
318
319 pub fn snap_to(&mut self, fraction: f32, window: &mut Window, cx: &mut Context<Self>) {
321 if !fraction.is_finite() {
322 return;
323 }
324 let fraction = fraction.clamp(0., 1.);
325 if fraction == self.progress && !self.animation.is_animating() {
326 return;
327 }
328 if fraction > 0. {
329 self.prepare_open(window, cx);
330 } else {
331 self.target = SearchValue::Collapsed;
332 self.restore_focus(window, cx);
333 }
334 self.animation.snap_to(fraction);
335 self.progress = fraction;
336 self.last_sampled = None;
337 cx.notify();
338 }
339
340 pub fn animate_to(
342 &mut self,
343 target: SearchValue,
344 duration: Duration,
345 window: &mut Window,
346 cx: &mut Context<Self>,
347 ) {
348 if duration.is_zero() || cx.reduce_motion() {
349 self.snap_to(target.progress(), window, cx);
350 return;
351 }
352 self.sample_animation(window, cx);
353 if target == self.target
354 && (self.animation.is_animating() || self.progress == target.progress())
355 {
356 return;
357 }
358 if target == SearchValue::Expanded {
359 self.prepare_open(window, cx);
360 }
361 self.target = target;
362 let now = cx.background_executor().now();
363 self.animation
364 .animate_to(target.progress(), duration, Easing::EaseInOut, now, false);
365 self.progress = self.animation.value();
366 self.last_sampled = None;
367 if !self.animation.is_animating() && target == SearchValue::Collapsed {
368 self.restore_focus(window, cx);
369 }
370 cx.notify();
371 }
372
373 pub fn results(&self) -> Option<&SearchOutcome> {
375 match &self.response.results {
376 Results::Ready(outcome) => Some(outcome),
377 _ => None,
378 }
379 }
380
381 pub fn select_result(
383 &mut self,
384 result: SearchResult,
385 window: &mut Window,
386 cx: &mut Context<Self>,
387 ) {
388 self.select_with_motion(result, Duration::ZERO, window, cx);
389 }
390
391 fn select_with_motion(
392 &mut self,
393 result: SearchResult,
394 duration: Duration,
395 window: &mut Window,
396 cx: &mut Context<Self>,
397 ) {
398 self.animate_to(SearchValue::Collapsed, duration, window, cx);
399 cx.emit(SearchEvent::Select(result));
400 }
401
402 pub fn scroll_state(&self) -> &ListState {
404 &self.scroll
405 }
406
407 pub fn set_scroll_state(&mut self, scroll: &ListState, cx: &mut Context<Self>) {
409 self.scroll = scroll.clone();
410 self.invalidate_result_measurements();
411 cx.notify();
412 }
413
414 fn presented(&self) -> bool {
415 self.is_open() || self.animation.is_animating()
416 }
417
418 fn prepare_open(&mut self, window: &mut Window, cx: &mut Context<Self>) {
419 if self.is_open() {
420 return;
421 }
422 if self.restore.is_none() {
423 self.restore = window.focused(cx).or_else(|| Some(self.trigger.clone()));
424 }
425 self.target = SearchValue::Expanded;
426 self.input_focus(cx).focus(window, cx);
427 if self.input.update(cx, |input, cx| {
428 input.marked_text_range(window, cx).is_none()
429 }) {
430 let query = self.input.read(cx).value();
431 self.update_query(query, cx);
432 }
433 }
434
435 fn restore_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
436 if let Some(focus) = self.restore.take() {
437 focus.focus(window, cx);
438 }
439 }
440
441 fn sample_animation(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
442 if !self.animation.is_animating() {
443 return false;
444 }
445 let now = cx.background_executor().now();
446 if self.last_sampled == Some(now) {
447 return false;
448 }
449 self.last_sampled = Some(now);
450 let old = self.progress;
451 let (value, running) = self.animation.sample(now, cx.reduce_motion());
452 self.progress = value;
453 if !running {
454 if self.target == SearchValue::Collapsed {
455 self.restore_focus(window, cx);
456 }
457 cx.notify();
458 false
459 } else {
460 if old != self.progress {
461 cx.notify();
462 }
463 true
464 }
465 }
466
467 pub fn set_query(
470 &mut self,
471 query: impl Into<SharedString>,
472 window: &mut Window,
473 cx: &mut Context<Self>,
474 ) {
475 let query = query.into();
476 self.input.update(cx, |input, cx| {
477 if input.value() != query {
478 input.set_value(query.clone(), window, cx);
479 }
480 });
481 self.update_query(query, cx);
482 }
483
484 pub fn complete(
487 &mut self,
488 request: &SearchRequest,
489 outcome: SearchOutcome,
490 cx: &mut Context<Self>,
491 ) -> bool {
492 let accepted = self.response.finish(request, outcome);
493 if accepted {
494 self.sync_result_focus(cx);
495 cx.notify();
496 }
497 accepted
498 }
499
500 fn update_query(&mut self, query: SharedString, cx: &mut Context<Self>) {
501 if query == self.query {
502 return;
503 }
504 self.query = query.clone();
505 if let Some(request) = self.response.begin(query) {
506 cx.emit(SearchEvent::Request(request));
507 } else {
508 self.result_focus.clear();
509 self.active_result = None;
510 self.scroll
511 .splice_focusable(0..self.scroll.item_count(), std::iter::empty());
512 }
513 self.scroll.reset(0);
514 cx.notify();
515 }
516
517 fn rows(&self) -> &[SearchResult] {
518 match &self.response.results {
519 Results::Ready(SearchOutcome::Results(rows)) => rows,
520 _ => &[],
521 }
522 }
523
524 fn sync_result_focus(&mut self, cx: &App) {
525 let mut previous = std::mem::take(&mut self.result_focus);
526 self.result_focus = self
527 .rows()
528 .iter()
529 .map(|row| {
530 let focus = previous
531 .remove(&row.id)
532 .unwrap_or_else(|| cx.focus_handle());
533 (row.id.clone(), focus)
534 })
535 .collect();
536 if self
537 .active_result
538 .as_ref()
539 .is_some_and(|id| !self.result_focus.contains_key(id))
540 {
541 self.active_result = None;
542 }
543 self.invalidate_result_measurements();
544 }
545
546 fn invalidate_result_measurements(&self) {
547 let mut anchor = self.scroll.logical_scroll_top();
548 anchor.item_ix = anchor.item_ix.min(self.rows().len().saturating_sub(1));
549 self.scroll.splice_focusable(
552 0..self.scroll.item_count(),
553 self.rows()
554 .iter()
555 .map(|row| self.result_focus.get(&row.id).cloned()),
556 );
557 self.scroll.scroll_to(anchor);
558 }
559}
560
561#[cfg(test)]
562mod tests {
563 use super::*;
564
565 #[test]
566 fn query_revision_rejects_stale_duplicate_and_cleared_results() {
567 let mut state = SearchResponse::default();
568 let first = state.begin("alpha".into()).unwrap();
569 let second = state.begin("beta".into()).unwrap();
570 assert_eq!(second.query(), "beta");
571 assert!(!state.finish(&first, SearchOutcome::Error("stale".into())));
572 assert!(state.finish(&second, SearchOutcome::Results(vec![])));
573 assert!(!state.finish(&second, SearchOutcome::Error("duplicate".into())));
574 let third = state.begin("alpha".into()).unwrap();
575 assert!(state.begin(" ".into()).is_none());
576 assert!(!state.finish(&third, SearchOutcome::Error("cleared".into())));
577 assert!(matches!(state.results, Results::Idle));
578 }
579
580 #[cfg(feature = "test-support")]
581 #[gpui::test]
582 fn clearing_query_to_idle_releases_result_focus_handles(cx: &mut gpui::TestAppContext) {
583 use std::{cell::RefCell, rc::Rc};
584
585 use gpui::{IntoElement, Render, WindowOptions, div};
586 use gpui_material_foundation::MaterialRoot;
587 use gpui_material_theme::MaterialTheme;
588
589 struct Empty;
590 impl Render for Empty {
591 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
592 div()
593 }
594 }
595
596 let latest = Rc::new(RefCell::new(None::<SearchRequest>));
597 let mut search_state = None;
598 let window = cx
599 .update(|cx| {
600 MaterialRoot::init(MaterialTheme::default(), cx);
601 gpui_material_components::init_components(cx);
602 MaterialRoot::open_window(WindowOptions::default(), cx, |window, cx| {
603 let state = cx.new(|cx| SearchState::new(window, cx));
604 let capture = latest.clone();
605 cx.subscribe(&state, move |_, event, _| {
606 if let SearchEvent::Request(request) = event {
607 capture.replace(Some(request.clone()));
608 }
609 })
610 .detach();
611 search_state = Some(state);
612 cx.new(|_| Empty)
613 })
614 .unwrap()
615 })
616 .into();
617 let state = search_state.unwrap();
618 cx.update_window(window, |_, window, cx| {
619 state.update(cx, |state, cx| {
620 state.set_query("design", window, cx);
621 });
622 })
623 .unwrap();
624 let request = latest.borrow().clone().unwrap();
625 cx.update(|cx| {
626 state.update(cx, |state, cx| {
627 let rows = vec![
628 SearchResult::new("row-1", "Row 1"),
629 SearchResult::new("row-2", "Row 2"),
630 ];
631 assert!(state.complete(&request, SearchOutcome::Results(rows), cx));
632 assert_eq!(state.result_focus.len(), 2);
633 assert_eq!(state.scroll.item_count(), 2);
634 });
635 });
636 cx.update_window(window, |_, window, cx| {
637 state.update(cx, |state, cx| {
638 state.set_query("", window, cx);
639 assert!(matches!(state.response.results, Results::Idle));
640 assert!(state.result_focus.is_empty());
641 assert!(state.active_result.is_none());
642 assert_eq!(state.scroll.item_count(), 0);
643 });
644 })
645 .unwrap();
646 }
647}