1use std::{rc::Rc, time::Duration};
2
3use gpui::{
4 AnyElement, App, ElementId, Entity, EntityInputHandler, InteractiveElement, IntoElement,
5 ParentElement, Pixels, RenderOnce, SharedString, Styled, Window, div, prelude::FluentBuilder,
6 px,
7};
8use gpui_base::TestSupportExt;
9use gpui_material_components::{Icon, IconButton, IconName, ListItem, TextField, TextFieldState};
10use gpui_material_foundation::{Surface, current_material_theme};
11use gpui_material_theme::{ColorRole, CornerShape, Direction, Elevation};
12
13use super::{
14 SearchMotion, SearchPopupOptions, SearchStyle, SearchViewVariant, SearchWindowOptions, length,
15 valid_dimension,
16};
17use crate::search::{SearchResult, SearchState, SearchValue};
18
19mod results;
20
21use results::{ResultBuilder, RowBuilder};
22
23type InputBuilder = Box<dyn FnOnce(TextField) -> AnyElement>;
24
25#[derive(IntoElement)]
27pub struct SearchView {
28 id: ElementId,
29 pub(super) label: SharedString,
30 pub(super) state: Entity<SearchState>,
31 pub(super) variant: SearchViewVariant,
32 pub(super) close_label: SharedString,
33 loading_label: SharedString,
34 empty_label: SharedString,
35 prompt: SharedString,
36 input: Option<InputBuilder>,
37 filters: Option<AnyElement>,
38 row: Option<RowBuilder>,
39 result_content: Option<ResultBuilder>,
40 pub(super) focused_width: Option<Pixels>,
41 docked_dimensions: (Pixels, Pixels),
42 gap: Pixels,
43 pub(super) style: SearchStyle,
44 pub(super) motion: SearchMotion,
45 pub(super) popup: SearchPopupOptions,
46 pub(super) window: SearchWindowOptions,
47 pub(super) sampled_in_bar: bool,
48}
49
50impl SearchView {
51 pub fn new(
53 id: impl Into<ElementId>,
54 label: impl Into<SharedString>,
55 state: &Entity<SearchState>,
56 ) -> Self {
57 Self {
58 id: id.into(),
59 label: label.into(),
60 state: state.clone(),
61 variant: SearchViewVariant::default(),
62 close_label: "Close search".into(),
63 loading_label: "Searching".into(),
64 empty_label: "No results".into(),
65 prompt: "Enter a search term".into(),
66 input: None,
67 filters: None,
68 row: None,
69 result_content: None,
70 focused_width: None,
71 docked_dimensions: (px(440.), px(424.)),
72 gap: px(0.),
73 style: SearchStyle::default(),
74 motion: SearchMotion::default(),
75 popup: SearchPopupOptions::default(),
76 window: SearchWindowOptions::default(),
77 sampled_in_bar: false,
78 }
79 }
80
81 pub fn variant(mut self, variant: SearchViewVariant) -> Self {
83 self.variant = variant;
84 self
85 }
86
87 pub fn labels(
89 mut self,
90 close: SharedString,
91 loading: SharedString,
92 empty: SharedString,
93 prompt: SharedString,
94 ) -> Self {
95 self.close_label = close;
96 self.loading_label = loading;
97 self.empty_label = empty;
98 self.prompt = prompt;
99 self
100 }
101
102 pub fn input<E: IntoElement + 'static>(
104 mut self,
105 build: impl FnOnce(TextField) -> E + 'static,
106 ) -> Self {
107 self.input = Some(Box::new(move |field| build(field).into_any_element()));
108 self
109 }
110
111 pub fn filters(mut self, content: impl IntoElement) -> Self {
113 self.filters = Some(content.into_any_element());
114 self
115 }
116
117 pub fn result_row(
119 mut self,
120 build: impl Fn(ListItem, &SearchResult, &mut Window, &mut App) -> ListItem + 'static,
121 ) -> Self {
122 self.row = Some(Rc::new(build));
123 self
124 }
125
126 pub fn result_content<E: IntoElement + 'static>(
128 mut self,
129 build: impl FnOnce(&Entity<SearchState>, &mut Window, &mut App) -> E + 'static,
130 ) -> Self {
131 self.result_content = Some(Box::new(move |state, window, cx| {
132 build(state, window, cx).into_any_element()
133 }));
134 self
135 }
136
137 pub fn focused_width(mut self, width: Pixels) -> Self {
139 self.focused_width = valid_dimension(width);
140 self
141 }
142
143 pub fn docked_size(mut self, width: Pixels, height: Pixels) -> Self {
145 self.docked_dimensions = (
146 valid_dimension(width).unwrap_or(px(440.)),
147 valid_dimension(height).unwrap_or(px(424.)),
148 );
149 self
150 }
151
152 pub fn result_gap(mut self, gap: Pixels) -> Self {
154 self.gap = length(gap);
155 self
156 }
157
158 pub fn style(mut self, style: SearchStyle) -> Self {
160 self.style = style;
161 self
162 }
163
164 pub fn motion(mut self, motion: SearchMotion) -> Self {
166 self.motion = motion;
167 self
168 }
169
170 pub fn popup_options(mut self, options: SearchPopupOptions) -> Self {
172 self.popup = options;
173 self
174 }
175
176 pub fn window_options(mut self, options: SearchWindowOptions) -> Self {
178 self.window = options;
179 self
180 }
181
182 fn render_input_region(
183 &mut self,
184 editor: &Entity<TextFieldState>,
185 editor_width: Option<Pixels>,
186 direction: Direction,
187 duration: Duration,
188 ) -> impl IntoElement + use<> {
189 let close = self.state.clone();
190 let down_state = self.state.clone();
191 let down_editor = editor.clone();
192 let field = TextField::new((self.id.clone(), "editor"), self.label.clone(), editor)
193 .when_some(self.style.input_colors, TextField::colors);
194 let field = match self.input.take() {
195 Some(builder) => builder(field),
196 None => field.into_any_element(),
197 };
198 div()
199 .id((self.id.clone(), "input-region"))
200 .test_support()
201 .flex()
202 .flex_none()
203 .items_center()
204 .p_2()
205 .gap_2()
206 .when(direction == Direction::Rtl, Styled::flex_row_reverse)
207 .child(
208 IconButton::new(
209 (self.id.clone(), "close-search"),
210 self.close_label.clone(),
211 Icon::new(IconName::Close),
212 )
213 .on_activate(move |window, cx| {
214 dismiss_search(&close, duration, window, cx);
215 }),
216 )
217 .child(
218 div()
219 .flex_1()
220 .min_w_0()
221 .when_some(editor_width, |editor, width| editor.max_w(width))
222 .capture_key_down(move |event, window, cx| {
223 if event.keystroke.key != "down" || event.keystroke.modifiers.modified() {
224 return;
225 }
226 if down_editor.update(cx, |input, cx| {
227 input.marked_text_range(window, cx).is_some()
228 }) {
229 return;
230 }
231 let target = {
232 let model = down_state.read(cx);
233 model.rows().first().and_then(|row| {
234 model
235 .result_focus
236 .get(&row.id)
237 .cloned()
238 .map(|focus| (row.id.clone(), focus, model.scroll.clone()))
239 })
240 };
241 if let Some((first_id, focus, scroll)) = target {
242 if scroll.bounds_for_item(0).is_some() {
243 scroll.scroll_to_reveal_item(0);
244 } else {
245 scroll.scroll_to(gpui::ListOffset {
246 item_ix: 0,
247 offset_in_item: px(0.),
248 });
249 }
250 down_state.update(cx, |state, _| {
251 state.active_result = Some(first_id);
252 });
253 focus.focus(window, cx);
254 window.refresh();
255 cx.stop_propagation();
256 }
257 })
258 .child(field),
259 )
260 }
261}
262
263impl RenderOnce for SearchView {
264 fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
265 let theme = current_material_theme(window, cx);
266 let rem_size = window.rem_size();
267 let font_revision = gpui_material_foundation::font_cache_revision(cx);
268 let (needs_animation, needs_layout) = {
269 let state = self.state.read(cx);
270 let needs_layout = match &state.result_layout {
271 Some((typography, cached_rem, cached_rev)) => {
272 *cached_rem != rem_size
273 || *cached_rev != font_revision
274 || *typography != theme.typography
275 }
276 None => true,
277 };
278 (!self.sampled_in_bar && state.is_animating(), needs_layout)
279 };
280 let animate = if needs_animation || needs_layout {
281 let measurement =
282 needs_layout.then(|| (theme.typography.clone(), rem_size, font_revision));
283 self.state.update(cx, |state, cx| {
284 let animate = if needs_animation {
285 state.sample_animation(window, cx)
286 } else {
287 false
288 };
289 if let Some(measurement) = measurement {
290 state.result_layout = Some(measurement);
291 state.invalidate_result_measurements();
292 }
293 animate
294 })
295 } else {
296 false
297 };
298 if animate && window.is_visible() {
299 window.request_animation_frame();
300 }
301 let model = self.state.read(cx);
302 let progress = if model.presented() {
303 model.progress()
304 } else {
305 1.
306 };
307 let editor = model.input.clone();
308 let layout = theme.layout;
309 let direction = layout.direction;
310 let size = window.viewport_size();
311 let docked = self.variant == SearchViewVariant::Docked;
312 let contained = self.variant == SearchViewVariant::FullScreenContained;
313 let split = docked && (self.gap > px(0.) || self.style.results_shape.is_some());
314 let geometry = self.window.insets;
315 let (left, right) = layout.horizontal(length(geometry.left), length(geometry.right));
316 let width = if docked {
317 self.docked_dimensions
318 .0
319 .min((size.width - px(16.)).max(px(0.)))
320 } else {
321 (size.width - left - right).max(px(0.))
322 };
323 let height = if docked {
324 self.docked_dimensions.1.min(size.height * 0.65)
325 } else {
326 (size.height - length(geometry.top) - length(geometry.bottom)).max(px(0.))
327 };
328 let editor_limit = if contained {
329 (width - px(24.)).max(px(0.))
330 } else {
331 width
332 };
333 let editor_width = self
334 .focused_width
335 .or(contained.then_some(px(720.)))
336 .map(|width| width.min(editor_limit));
337 let dismiss = self.state.clone();
338 let duration = self.motion.collapse;
339 let close_on_escape = if docked {
340 self.popup.dismiss_on_escape
341 } else {
342 self.window.dismiss_on_escape
343 };
344
345 let input = self.render_input_region(&editor, editor_width, direction, duration);
346 let results = self.render_results_region(duration, window, cx);
347
348 let panel = panel_surface(self.style, docked, false).w(width).h(height);
349 let panel = if split {
350 div()
351 .flex()
352 .flex_col()
353 .w(width)
354 .h(height)
355 .child(panel_surface(self.style, true, false).child(input))
356 .child(div().flex_none().h(self.gap.min(height * 0.35)))
357 .child(
358 panel_surface(self.style, true, true)
359 .flex_1()
360 .min_h_0()
361 .child(results),
362 )
363 .into_any_element()
364 } else {
365 panel
366 .child(if contained {
367 div()
368 .flex()
369 .justify_center()
370 .p_3()
371 .child(
372 panel_surface(self.style, false, false)
373 .shape(self.style.shape.unwrap_or(CornerShape::Full))
374 .w(editor_width.unwrap_or(width))
375 .child(input),
376 )
377 .into_any_element()
378 } else {
379 input.into_any_element()
380 })
381 .child(results)
382 .into_any_element()
383 };
384 div()
385 .id(self.id)
386 .test_support()
387 .when(!docked, |view| {
388 view.pl(left)
389 .pr(right)
390 .pt(length(geometry.top))
391 .pb(length(geometry.bottom))
392 })
393 .opacity(progress)
394 .capture_key_down(move |event, window, cx| {
395 if event.keystroke.key == "escape"
396 && close_on_escape
397 && dismiss_search(&dismiss, duration, window, cx)
398 {
399 cx.stop_propagation();
400 }
401 })
402 .child(panel)
403 }
404}
405
406fn panel_surface(style: SearchStyle, docked: bool, results: bool) -> Surface {
407 Surface::new(ColorRole::SurfaceContainerHigh)
408 .flex()
409 .flex_col()
410 .when_some(style.container, Surface::container_color)
411 .when_some(style.content, Surface::content_color)
412 .when_some(
413 if results {
414 style.results_shape.or(style.shape)
415 } else {
416 style.shape
417 }
418 .or(docked.then_some(CornerShape::Radii([28.; 4]))),
419 Surface::shape,
420 )
421 .when_some(style.tonal_elevation, Surface::tonal_elevation)
422 .when_some(
423 style
424 .shadow_elevation
425 .or(docked.then_some(Elevation::Level3)),
426 Surface::shadow_elevation,
427 )
428}
429
430pub(super) fn dismiss_search(
431 state: &Entity<SearchState>,
432 duration: Duration,
433 window: &mut Window,
434 cx: &mut App,
435) -> bool {
436 state.update(cx, |state, cx| {
437 let composing = state.input.update(cx, |input, cx| {
438 input.marked_text_range(window, cx).is_some()
439 });
440 if !composing {
441 state.animate_to(SearchValue::Collapsed, duration, window, cx);
442 }
443 !composing
444 })
445}