1use std::{cell::RefCell, rc::Rc};
12
13use arc_motion::{ArcPresence, ArcPresenceConfig, CubicBezier, is_reduced_motion, motion_now};
14use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, Spacing, Typography, oklab_mix};
15use gpui_kit::{
16 AnyElement, App, Bounds, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
17 ParentElement, PathBuilder, Pixels, RenderOnce, Role, SharedString, Styled,
18 TestSupportExt as _, Window, base::StyledExt as _, canvas, deferred, div, point, prelude::*,
19 px,
20};
21use std::time::Duration;
22
23#[derive(Clone, Debug, Eq, PartialEq)]
25pub struct FilterChip {
26 pub id: SharedString,
27 pub label: SharedString,
28 pub value: Option<SharedString>,
29}
30
31impl FilterChip {
32 pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
33 Self {
34 id: id.into(),
35 label: label.into(),
36 value: None,
37 }
38 }
39
40 pub fn value(mut self, value: impl Into<SharedString>) -> Self {
41 self.value = Some(value.into());
42 self
43 }
44}
45
46#[derive(Clone, Debug, Eq, PartialEq)]
48pub struct FilterOption {
49 pub value: SharedString,
50 pub label: Option<SharedString>,
51 pub hint: Option<SharedString>,
52}
53
54impl FilterOption {
55 pub fn new(value: impl Into<SharedString>) -> Self {
56 Self {
57 value: value.into(),
58 label: None,
59 hint: None,
60 }
61 }
62
63 pub fn label(mut self, label: impl Into<SharedString>) -> Self {
64 self.label = Some(label.into());
65 self
66 }
67
68 pub fn hint(mut self, hint: impl Into<SharedString>) -> Self {
69 self.hint = Some(hint.into());
70 self
71 }
72
73 pub fn display_label(&self) -> SharedString {
74 self.label.clone().unwrap_or_else(|| self.value.clone())
75 }
76}
77
78impl From<&str> for FilterOption {
79 fn from(s: &str) -> Self {
80 Self::new(s.to_string())
81 }
82}
83
84#[derive(Clone, Debug, Eq, PartialEq)]
86pub struct FilterField {
87 pub id: SharedString,
88 pub label: SharedString,
89 pub options: Vec<FilterOption>,
90}
91
92impl FilterField {
93 pub fn new(
94 id: impl Into<SharedString>,
95 label: impl Into<SharedString>,
96 options: impl IntoIterator<Item = impl Into<FilterOption>>,
97 ) -> Self {
98 Self {
99 id: id.into(),
100 label: label.into(),
101 options: options.into_iter().map(Into::into).collect(),
102 }
103 }
104}
105
106pub fn upsert_filter_chip(filters: &[FilterChip], chip: FilterChip) -> Vec<FilterChip> {
108 let mut next = filters.to_vec();
109 if let Some(existing) = next.iter_mut().find(|c| c.id == chip.id) {
110 *existing = chip;
111 } else {
112 next.push(chip);
113 }
114 next
115}
116
117fn paint_plus(cx: f32, cy: f32, color: Hsla, window: &mut Window) {
118 let r = 4.2;
119 for (x1, y1, x2, y2) in [(cx - r, cy, cx + r, cy), (cx, cy - r, cx, cy + r)] {
120 let mut pb = PathBuilder::stroke(px(1.6));
121 pb.move_to(point(px(x1), px(y1)));
122 pb.line_to(point(px(x2), px(y2)));
123 if let Ok(p) = pb.build() {
124 window.paint_path(p, color);
125 }
126 }
127}
128
129fn paint_close_x(cx: f32, cy: f32, color: Hsla, window: &mut Window) {
130 let r = 3.2;
131 for (x1, y1, x2, y2) in [
132 (cx - r, cy - r, cx + r, cy + r),
133 (cx + r, cy - r, cx - r, cy + r),
134 ] {
135 let mut pb = PathBuilder::stroke(px(1.5));
136 pb.move_to(point(px(x1), px(y1)));
137 pb.line_to(point(px(x2), px(y2)));
138 if let Ok(p) = pb.build() {
139 window.paint_path(p, color);
140 }
141 }
142}
143
144fn paint_chevron_right(cx: f32, cy: f32, color: Hsla, window: &mut Window) {
145 let mut pb = PathBuilder::stroke(px(1.5));
146 pb.move_to(point(px(cx - 2.0), px(cy - 3.5)));
147 pb.line_to(point(px(cx + 2.0), px(cy)));
148 pb.line_to(point(px(cx - 2.0), px(cy + 3.5)));
149 if let Ok(p) = pb.build() {
150 window.paint_path(p, color);
151 }
152}
153
154fn paint_chevron_left(cx: f32, cy: f32, color: Hsla, window: &mut Window) {
155 let mut pb = PathBuilder::stroke(px(1.5));
156 pb.move_to(point(px(cx + 2.0), px(cy - 3.5)));
157 pb.line_to(point(px(cx - 2.0), px(cy)));
158 pb.line_to(point(px(cx + 2.0), px(cy + 3.5)));
159 if let Ok(p) = pb.build() {
160 window.paint_path(p, color);
161 }
162}
163
164fn paint_check(cx: f32, cy: f32, color: Hsla, window: &mut Window) {
165 let mut pb = PathBuilder::stroke(px(1.7));
166 pb.move_to(point(px(cx - 4.0), px(cy + 0.4)));
167 pb.line_to(point(px(cx - 1.2), px(cy + 3.2)));
168 pb.line_to(point(px(cx + 4.4), px(cy - 3.0)));
169 if let Ok(p) = pb.build() {
170 window.paint_path(p, color);
171 }
172}
173
174type RemoveCallback = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
175type ClearAllCallback = Rc<dyn Fn(&mut Window, &mut App)>;
176type AddFilterCallback = Rc<dyn Fn(&FilterChip, &FilterField, &mut Window, &mut App)>;
177type TrailingSlot = Rc<dyn Fn(&mut Window, &mut App) -> AnyElement>;
178
179#[derive(Clone)]
180struct FilterToolbarInternal {
181 menu_open: bool,
182 active_field_id: Option<SharedString>,
183 highlighted_idx: usize,
184 step_changed_at: f64,
185 focus_handle: FocusHandle,
186 trigger_bounds: Rc<RefCell<Option<Bounds<Pixels>>>>,
187}
188
189#[cfg(test)]
190type FilterToolbarProbe = Rc<RefCell<Option<Rc<RefCell<FilterToolbarInternal>>>>>;
191
192#[derive(IntoElement)]
194pub struct FilterToolbar {
195 id: ElementId,
196 label: SharedString,
197 filters: Vec<FilterChip>,
198 fields: Vec<FilterField>,
199 add_label: SharedString,
200 clear_label: SharedString,
201 trailing: Option<TrailingSlot>,
202 on_remove: Option<RemoveCallback>,
203 on_clear_all: Option<ClearAllCallback>,
204 on_add: Option<AddFilterCallback>,
205 #[cfg(test)]
206 probe: Option<FilterToolbarProbe>,
207}
208
209impl FilterToolbar {
210 pub fn new(id: impl Into<ElementId>, filters: impl IntoIterator<Item = FilterChip>) -> Self {
211 Self {
212 id: id.into(),
213 label: SharedString::from("Active filters"),
214 filters: filters.into_iter().collect(),
215 fields: Vec::new(),
216 add_label: SharedString::from("Add filter"),
217 clear_label: SharedString::from("Clear all"),
218 trailing: None,
219 on_remove: None,
220 on_clear_all: None,
221 on_add: None,
222 #[cfg(test)]
223 probe: None,
224 }
225 }
226
227 pub fn label(mut self, label: impl Into<SharedString>) -> Self {
228 self.label = label.into();
229 self
230 }
231
232 pub fn fields(mut self, fields: impl IntoIterator<Item = FilterField>) -> Self {
233 self.fields = fields.into_iter().collect();
234 self
235 }
236
237 pub fn add_label(mut self, label: impl Into<SharedString>) -> Self {
238 self.add_label = label.into();
239 self
240 }
241
242 pub fn clear_label(mut self, label: impl Into<SharedString>) -> Self {
243 self.clear_label = label.into();
244 self
245 }
246
247 pub fn trailing(
248 mut self,
249 builder: impl Fn(&mut Window, &mut App) -> AnyElement + 'static,
250 ) -> Self {
251 self.trailing = Some(Rc::new(builder));
252 self
253 }
254
255 pub fn on_remove(
256 mut self,
257 cb: impl Fn(&SharedString, &mut Window, &mut App) + 'static,
258 ) -> Self {
259 self.on_remove = Some(Rc::new(cb));
260 self
261 }
262
263 pub fn on_clear_all(mut self, cb: impl Fn(&mut Window, &mut App) + 'static) -> Self {
264 self.on_clear_all = Some(Rc::new(cb));
265 self
266 }
267
268 pub fn on_add(
269 mut self,
270 cb: impl Fn(&FilterChip, &FilterField, &mut Window, &mut App) + 'static,
271 ) -> Self {
272 self.on_add = Some(Rc::new(cb));
273 self
274 }
275}
276
277impl RenderOnce for FilterToolbar {
278 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
279 let theme = cx.arc_theme().clone();
280 let colors = theme.colors;
281 let reduced = is_reduced_motion(cx);
282 let now = motion_now(cx);
283
284 let state_cell = window
285 .use_keyed_state(
286 ElementId::NamedChild(self.id.clone().into(), SharedString::from("ft-state")),
287 cx,
288 |_, cx| {
289 Rc::new(RefCell::new(FilterToolbarInternal {
290 menu_open: false,
291 active_field_id: None,
292 highlighted_idx: 0,
293 step_changed_at: now - 1.0,
294 focus_handle: cx.focus_handle(),
295 trigger_bounds: Rc::new(RefCell::new(None)),
296 }))
297 },
298 )
299 .read(cx)
300 .clone();
301
302 #[cfg(test)]
303 if let Some(probe) = self.probe.as_ref() {
304 *probe.borrow_mut() = Some(state_cell.clone());
305 }
306
307 let (menu_open, active_field_id, highlighted_idx, step_elapsed, focus_handle) = {
308 let st = state_cell.borrow();
309 let dt = (now - st.step_changed_at).max(0.0);
310 if !reduced && st.menu_open && dt < 0.24 {
311 window.request_animation_frame();
312 }
313 (
314 st.menu_open,
315 st.active_field_id.clone(),
316 st.highlighted_idx,
317 dt,
318 st.focus_handle.clone(),
319 )
320 };
321
322 let presence = ArcPresence::new((self.id.clone(), "ft-menu-presence"), menu_open)
323 .config(ArcPresenceConfig {
324 enter_duration: Duration::from_millis(180),
325 exit_duration: Duration::from_millis(140),
326 ..ArcPresenceConfig::default()
327 })
328 .animate_initial(false)
329 .sample(window, cx);
330
331 let chip_bg = colors.surface_muted;
332 let chip_hover_bg = oklab_mix(colors.foreground, colors.surface_muted, 0.06);
333 let row_hi_bg = oklab_mix(colors.foreground, colors.surface_raised, 0.06);
334
335 let mut chips_row = div()
336 .flex_1()
337 .min_w(px(0.0))
338 .flex()
339 .flex_row()
340 .flex_wrap()
341 .items_center()
342 .gap(Spacing::S2);
343
344 for chip in &self.filters {
345 let chip_id = chip.id.clone();
346 let cb_rm = self.on_remove.clone();
347 let close_col = colors.text_muted;
348 chips_row = chips_row.child(
349 div()
350 .h(px(30.0))
351 .pl(Spacing::S3)
352 .pr(Spacing::S2)
353 .rounded(Radii::PILL)
354 .border_1()
355 .border_color(colors.border)
356 .bg(chip_bg)
357 .flex()
358 .flex_row()
359 .items_center()
360 .gap(px(5.0))
361 .text_size(Typography::TEXT_XS)
362 .child(
363 div()
364 .text_color(colors.text_muted)
365 .child(chip.label.clone()),
366 )
367 .when_some(chip.value.clone(), |el, val| {
368 el.child(div().font_medium().text_color(colors.foreground).child(val))
369 })
370 .child(
371 div()
372 .id(ElementId::NamedChild(
373 self.id.clone().into(),
374 SharedString::from(format!("ft-rm-{chip_id}")),
375 ))
376 .w(px(18.0))
377 .h(px(18.0))
378 .rounded(Radii::PILL)
379 .hover(move |s| s.bg(chip_hover_bg))
380 .cursor_pointer()
381 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
382 if let Some(ref cb) = cb_rm {
383 cb(&chip_id, window, cx);
384 }
385 window.refresh();
386 })
387 .child(
388 canvas(
389 |_, _, _| {},
390 move |bounds, _, window, _| {
391 let cx_p = f32::from(bounds.origin.x)
392 + f32::from(bounds.size.width) * 0.5;
393 let cy_p = f32::from(bounds.origin.y)
394 + f32::from(bounds.size.height) * 0.5;
395 paint_close_x(cx_p, cy_p, close_col, window);
396 },
397 )
398 .size_full(),
399 ),
400 ),
401 );
402 }
403
404 if !self.fields.is_empty() {
406 let st_trig = state_cell.clone();
407 let fh_trig = focus_handle.clone();
408 let plus_col = colors.text_secondary;
409 let trig_hover_bg = oklab_mix(colors.foreground, colors.surface, 0.05);
410
411 let active_field = active_field_id
412 .as_ref()
413 .and_then(|fid| self.fields.iter().find(|f| &f.id == fid));
414
415 let step_t = if reduced {
416 1.0
417 } else {
418 CubicBezier::new(0.16, 1.0, 0.3, 1.0)
419 .sample((step_elapsed / 0.20).clamp(0.0, 1.0) as f32)
420 };
421
422 let menu_panel: Option<AnyElement> = if presence.should_render() {
423 let p = presence.progress.clamp(0.0, 1.0);
424 let panel_y = if reduced { 0.0 } else { (1.0 - p) * -6.0 };
425
426 let outside_state = state_cell.clone();
427 let mut panel = div()
428 .id(ElementId::NamedChild(
429 self.id.clone().into(),
430 SharedString::from("ft-menu-panel"),
431 ))
432 .test_support()
433 .role(Role::Menu)
434 .on_mouse_down_out(move |event, window, _| {
435 let mut st = outside_state.borrow_mut();
436 if st
438 .trigger_bounds
439 .borrow()
440 .is_some_and(|b| b.contains(&event.position))
441 {
442 return;
443 }
444 if st.menu_open {
445 st.menu_open = false;
446 st.active_field_id = None;
447 st.highlighted_idx = 0;
448 window.refresh();
449 }
450 })
451 .track_focus(&focus_handle)
452 .absolute()
453 .left_0()
454 .top(px(36.0 + panel_y))
455 .w(px(236.0))
456 .p(Spacing::S1)
457 .rounded(Radii::PANEL)
458 .border_1()
459 .border_color(colors.border)
460 .bg(colors.surface_raised)
461 .shadow(Shadows::floating(theme.mode))
462 .opacity(p)
463 .flex()
464 .flex_col()
465 .gap(px(2.0));
466
467 if let Some(field) = active_field {
468 let st_back = state_cell.clone();
470 let back_col = colors.text_muted;
471 panel = panel.child(
472 div()
473 .id(ElementId::NamedChild(
474 self.id.clone().into(),
475 SharedString::from("ft-back"),
476 ))
477 .h(px(30.0))
478 .px(Spacing::S2)
479 .rounded(Radii::CONTROL)
480 .border_b_1()
481 .border_color(colors.border_subtle)
482 .flex()
483 .flex_row()
484 .items_center()
485 .gap(Spacing::S2)
486 .text_size(Typography::TEXT_XS)
487 .font_medium()
488 .text_color(colors.text_secondary)
489 .cursor_pointer()
490 .hover(move |s| s.bg(row_hi_bg))
491 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
492 let mut st = st_back.borrow_mut();
493 st.active_field_id = None;
494 st.highlighted_idx = 0;
495 st.step_changed_at = motion_now(cx);
496 window.refresh();
497 })
498 .child(
499 div().w(px(14.0)).h(px(14.0)).child(
500 canvas(
501 |_, _, _| {},
502 move |bounds, _, window, _| {
503 let cx_p = f32::from(bounds.origin.x)
504 + f32::from(bounds.size.width) * 0.5;
505 let cy_p = f32::from(bounds.origin.y)
506 + f32::from(bounds.size.height) * 0.5;
507 paint_chevron_left(cx_p, cy_p, back_col, window);
508 },
509 )
510 .size_full(),
511 ),
512 )
513 .child(field.label.clone()),
514 );
515
516 let current_val = self
517 .filters
518 .iter()
519 .find(|c| c.id == field.id)
520 .and_then(|c| c.value.clone());
521
522 let mut list_box = div().opacity(step_t).flex().flex_col().gap(px(2.0));
523
524 for (idx, opt) in field.options.iter().enumerate() {
525 let is_checked = current_val.as_ref() == Some(&opt.value);
526 let is_hi = idx == highlighted_idx;
527 let st_pick = state_cell.clone();
528 let cb_add = self.on_add.clone();
529 let field_cloned = field.clone();
530 let opt_cloned = opt.clone();
531 let chk_col = colors.accent;
532 list_box = list_box.child(
533 div()
534 .id(ElementId::NamedChild(
535 self.id.clone().into(),
536 SharedString::from(format!("ft-opt-{}-{idx}", field.id)),
537 ))
538 .test_support()
539 .h(px(32.0))
540 .px(Spacing::S2)
541 .rounded(Radii::CONTROL)
542 .when(is_hi, |el| el.bg(row_hi_bg))
543 .hover(move |s| s.bg(row_hi_bg))
544 .cursor_pointer()
545 .flex()
546 .flex_row()
547 .items_center()
548 .justify_between()
549 .gap(Spacing::S2)
550 .text_size(Typography::TEXT_SM)
551 .text_color(colors.foreground)
552 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
553 let chip = FilterChip::new(
554 field_cloned.id.clone(),
555 field_cloned.label.clone(),
556 )
557 .value(opt_cloned.display_label());
558 {
559 let mut st = st_pick.borrow_mut();
560 st.menu_open = false;
561 st.active_field_id = None;
562 }
563 if let Some(ref cb) = cb_add {
564 cb(&chip, &field_cloned, window, cx);
565 }
566 window.refresh();
567 })
568 .child(
569 div()
570 .flex()
571 .flex_row()
572 .items_center()
573 .gap(Spacing::S2)
574 .child(opt.display_label()),
575 )
576 .child(
577 div()
578 .flex()
579 .flex_row()
580 .items_center()
581 .gap(Spacing::S2)
582 .when_some(opt.hint.clone(), |el, hint| {
583 el.child(
584 div()
585 .text_size(Typography::TEXT_XS)
586 .text_color(colors.text_muted)
587 .child(hint),
588 )
589 })
590 .when(is_checked, |el| {
591 el.child(
592 div().w(px(14.0)).h(px(14.0)).child(
593 canvas(
594 |_, _, _| {},
595 move |bounds, _, window, _| {
596 let cx_p = f32::from(bounds.origin.x)
597 + f32::from(bounds.size.width)
598 * 0.5;
599 let cy_p = f32::from(bounds.origin.y)
600 + f32::from(bounds.size.height)
601 * 0.5;
602 paint_check(
603 cx_p, cy_p, chk_col, window,
604 );
605 },
606 )
607 .size_full(),
608 ),
609 )
610 }),
611 ),
612 );
613 }
614 panel = panel.child(list_box);
615 } else {
616 let mut list_box = div().opacity(step_t).flex().flex_col().gap(px(2.0));
618 for (idx, field) in self.fields.iter().enumerate() {
619 let is_hi = idx == highlighted_idx;
620 let active_val = self
621 .filters
622 .iter()
623 .find(|c| c.id == field.id)
624 .and_then(|c| c.value.clone());
625 let st_field = state_cell.clone();
626 let fid = field.id.clone();
627 let chev_col = colors.text_muted;
628 list_box = list_box.child(
629 div()
630 .id(ElementId::NamedChild(
631 self.id.clone().into(),
632 SharedString::from(format!("ft-field-{fid}")),
633 ))
634 .test_support()
635 .h(px(32.0))
636 .px(Spacing::S2)
637 .rounded(Radii::CONTROL)
638 .when(is_hi, |el| el.bg(row_hi_bg))
639 .hover(move |s| s.bg(row_hi_bg))
640 .cursor_pointer()
641 .flex()
642 .flex_row()
643 .items_center()
644 .justify_between()
645 .gap(Spacing::S2)
646 .text_size(Typography::TEXT_SM)
647 .text_color(colors.foreground)
648 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
649 let mut st = st_field.borrow_mut();
650 st.active_field_id = Some(fid.clone());
651 st.highlighted_idx = 0;
652 st.step_changed_at = motion_now(cx);
653 window.refresh();
654 })
655 .child(field.label.clone())
656 .child(
657 div()
658 .flex()
659 .flex_row()
660 .items_center()
661 .gap(Spacing::S1)
662 .when_some(active_val, |el, val| {
663 el.child(
664 div()
665 .text_size(Typography::TEXT_XS)
666 .text_color(colors.text_muted)
667 .child(val),
668 )
669 })
670 .child(
671 div().w(px(14.0)).h(px(14.0)).child(
672 canvas(
673 |_, _, _| {},
674 move |bounds, _, window, _| {
675 let cx_p = f32::from(bounds.origin.x)
676 + f32::from(bounds.size.width) * 0.5;
677 let cy_p = f32::from(bounds.origin.y)
678 + f32::from(bounds.size.height) * 0.5;
679 paint_chevron_right(
680 cx_p, cy_p, chev_col, window,
681 );
682 },
683 )
684 .size_full(),
685 ),
686 ),
687 ),
688 );
689 }
690 panel = panel.child(list_box);
691 }
692
693 let st_k = state_cell.clone();
695 let fields_k = self.fields.clone();
696 let cb_add_k = self.on_add.clone();
697 panel = panel.on_key_down(move |ev: &KeyDownEvent, window, cx| {
698 let key = ev.keystroke.key.as_str();
699 let cur_fid = st_k.borrow().active_field_id.clone();
700 let cur_field = cur_fid
701 .as_ref()
702 .and_then(|id| fields_k.iter().find(|f| &f.id == id));
703 let len = cur_field.map(|f| f.options.len()).unwrap_or(fields_k.len());
704 if len == 0 {
705 return;
706 }
707 match key {
708 "escape" => {
709 let mut st = st_k.borrow_mut();
710 st.menu_open = false;
711 st.active_field_id = None;
712 window.refresh();
713 }
714 "down" => {
715 let mut st = st_k.borrow_mut();
716 st.highlighted_idx = (st.highlighted_idx + 1) % len;
717 window.refresh();
718 }
719 "up" => {
720 let mut st = st_k.borrow_mut();
721 st.highlighted_idx = (st.highlighted_idx + len - 1) % len;
722 window.refresh();
723 }
724 "left" if cur_field.is_some() => {
725 let mut st = st_k.borrow_mut();
726 st.active_field_id = None;
727 st.highlighted_idx = 0;
728 st.step_changed_at = motion_now(cx);
729 window.refresh();
730 }
731 "right" | "enter" => {
732 let idx = st_k.borrow().highlighted_idx.min(len - 1);
733 if let Some(field) = cur_field {
734 if key == "enter" {
735 let opt = &field.options[idx];
736 let chip =
737 FilterChip::new(field.id.clone(), field.label.clone())
738 .value(opt.display_label());
739 {
740 let mut st = st_k.borrow_mut();
741 st.menu_open = false;
742 st.active_field_id = None;
743 }
744 if let Some(ref cb) = cb_add_k {
745 cb(&chip, field, window, cx);
746 }
747 window.refresh();
748 }
749 } else {
750 let mut st = st_k.borrow_mut();
751 st.active_field_id = Some(fields_k[idx].id.clone());
752 st.highlighted_idx = 0;
753 st.step_changed_at = motion_now(cx);
754 window.refresh();
755 }
756 }
757 _ => {}
758 }
759 });
760
761 Some(deferred(panel).with_priority(20).into_any_element())
762 } else {
763 None
764 };
765
766 let trigger_bounds = state_cell.borrow().trigger_bounds.clone();
767 chips_row = chips_row.child(
768 div()
769 .relative()
770 .child(
771 div()
772 .id(ElementId::NamedChild(
773 self.id.clone().into(),
774 SharedString::from("ft-add-btn"),
775 ))
776 .test_support()
777 .h(px(30.0))
778 .px(Spacing::S3)
779 .rounded(Radii::PILL)
780 .border_1()
781 .border_color(if menu_open {
782 colors.border_strong
783 } else {
784 colors.border
785 })
786 .bg(colors.surface)
787 .hover(move |s| s.bg(trig_hover_bg))
788 .cursor_pointer()
789 .flex()
790 .flex_row()
791 .items_center()
792 .gap(px(5.0))
793 .text_size(Typography::TEXT_XS)
794 .font_medium()
795 .text_color(colors.foreground)
796 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
797 let mut st = st_trig.borrow_mut();
798 st.menu_open = !st.menu_open;
799 st.active_field_id = None;
800 st.highlighted_idx = 0;
801 st.step_changed_at = motion_now(cx);
802 if st.menu_open {
803 fh_trig.focus(window, cx);
804 }
805 window.refresh();
806 })
807 .child(
808 div().w(px(12.0)).h(px(12.0)).child(
809 canvas(
810 |_, _, _| {},
811 move |bounds, _, window, _| {
812 let cx_p = f32::from(bounds.origin.x)
813 + f32::from(bounds.size.width) * 0.5;
814 let cy_p = f32::from(bounds.origin.y)
815 + f32::from(bounds.size.height) * 0.5;
816 paint_plus(cx_p, cy_p, plus_col, window);
817 },
818 )
819 .size_full(),
820 ),
821 )
822 .child(self.add_label.clone())
823 .child(
824 canvas(
825 move |bounds, _, _| *trigger_bounds.borrow_mut() = Some(bounds),
826 |_, _, _, _| {},
827 )
828 .absolute()
829 .inset_0(),
830 ),
831 )
832 .when_some(menu_panel, |el, m| el.child(m)),
833 );
834 }
835
836 if self.filters.len() >= 2
837 && let Some(cb_clear) = self.on_clear_all
838 {
839 let clear_hover = oklab_mix(colors.foreground, colors.surface, 0.05);
840 chips_row = chips_row.child(
841 div()
842 .id(ElementId::NamedChild(
843 self.id.clone().into(),
844 SharedString::from("ft-clear-all"),
845 ))
846 .h(px(30.0))
847 .px(Spacing::S2)
848 .rounded(Radii::CONTROL)
849 .hover(move |s| s.bg(clear_hover))
850 .cursor_pointer()
851 .flex()
852 .items_center()
853 .text_size(Typography::TEXT_XS)
854 .text_color(colors.text_muted)
855 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
856 cb_clear(window, cx);
857 window.refresh();
858 })
859 .child(self.clear_label),
860 );
861 }
862
863 let trailing_el = self.trailing.as_ref().map(|t| t(window, cx));
864
865 div()
866 .id(self.id)
867 .role(Role::Toolbar)
868 .aria_label(self.label)
869 .w_full()
870 .flex()
871 .flex_row()
872 .flex_wrap()
873 .items_center()
874 .justify_between()
875 .gap(Spacing::S3)
876 .child(chips_row)
877 .when_some(trailing_el, |el, t| el.child(t))
878 .into_any_element()
879 }
880}
881
882#[cfg(test)]
883mod tests {
884 use super::*;
885
886 struct MenuHost {
887 probe: Rc<RefCell<Option<Rc<RefCell<FilterToolbarInternal>>>>>,
888 }
889
890 impl gpui_kit::Render for MenuHost {
891 fn render(&mut self, _: &mut Window, _: &mut gpui_kit::Context<Self>) -> impl IntoElement {
892 let mut toolbar = FilterToolbar::new("ft-test", []).fields([FilterField::new(
893 "status",
894 "Status",
895 ["Active", "Paused"],
896 )]);
897 toolbar.probe = Some(self.probe.clone());
898 div().size(px(600.0)).p(px(20.0)).child(toolbar)
899 }
900 }
901
902 fn menu_id(name: &str) -> ElementId {
903 ElementId::NamedChild(ElementId::from("ft-test").into(), name.to_string().into())
904 }
905
906 #[gpui_kit::test]
907 fn filter_toolbar_outside_click_trigger_and_two_step_selection(
908 cx: &mut gpui_kit::TestAppContext,
909 ) {
910 use gpui_kit::test::{TestEventExt as _, TestWindowExt as _};
911 cx.update(|cx| {
912 gpui_kit::init(cx);
913 arc_tokens::install_arc_theme(
914 arc_tokens::ThemeMode::Light,
915 arc_tokens::Accent::Neutral,
916 cx,
917 );
918 arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx);
919 });
920 let probe = Rc::new(RefCell::new(None));
921 let (_, cx) = cx.add_window_view(|_, _| MenuHost {
922 probe: probe.clone(),
923 });
924 cx.update(|w, cx| {
925 w.render_frame(cx);
926 w.click(menu_id("ft-add-btn"), cx);
927 w.render_frame(cx);
928 assert!(w.try_find(menu_id("ft-menu-panel")).is_some());
929 w.click(menu_id("ft-field-status"), cx);
930 w.render_frame(cx);
931 assert!(
932 w.try_find(menu_id("ft-opt-status-0")).is_some(),
933 "内部点击不得被外部关闭误伤"
934 );
935 w.pointer_down(point(px(580.0), px(580.0)), MouseButton::Left, cx);
936 w.pointer_up(point(px(580.0), px(580.0)), MouseButton::Left, cx);
937 w.render_frame(cx);
938 let state = probe.borrow().as_ref().unwrap().clone();
939 assert!(!state.borrow().menu_open);
940 w.click(menu_id("ft-add-btn"), cx);
941 w.render_frame(cx);
942 assert!(
943 w.try_find(menu_id("ft-field-status")).is_some(),
944 "重开从字段步骤开始"
945 );
946 w.click(menu_id("ft-add-btn"), cx);
947 w.render_frame(cx);
948 assert!(!state.borrow().menu_open, "触发按钮不得关闭后再次打开");
949 w.click(menu_id("ft-add-btn"), cx);
950 w.render_frame(cx);
951 w.click(menu_id("ft-field-status"), cx);
952 w.render_frame(cx);
953 w.click(menu_id("ft-opt-status-0"), cx);
954 w.render_frame(cx);
955 let state = probe.borrow().as_ref().unwrap().clone();
956 assert!(!state.borrow().menu_open);
957 });
958 }
959
960 #[test]
961 fn upsert_filter_chip_replaces_existing_field_in_place() {
962 let initial = vec![
963 FilterChip::new("status", "Status").value("Active"),
964 FilterChip::new("owner", "Owner").value("Elia"),
965 ];
966 let updated = upsert_filter_chip(
967 &initial,
968 FilterChip::new("status", "Status").value("Paused"),
969 );
970 assert_eq!(updated.len(), 2);
971 assert_eq!(updated[0].value.as_deref(), Some("Paused"));
972 assert_eq!(updated[1].id.as_ref(), "owner");
973
974 let appended = upsert_filter_chip(
975 &updated,
976 FilterChip::new("tier", "Tier").value("Enterprise"),
977 );
978 assert_eq!(appended.len(), 3);
979 assert_eq!(appended[2].id.as_ref(), "tier");
980 }
981}