thread_context_picker.rs

  1use std::sync::Arc;
  2
  3use fuzzy::StringMatchCandidate;
  4use gpui::{AppContext, DismissEvent, FocusHandle, FocusableView, Task, View, WeakModel, WeakView};
  5use picker::{Picker, PickerDelegate};
  6use ui::{prelude::*, ListItem};
  7
  8use crate::context_picker::{ConfirmBehavior, ContextPicker};
  9use crate::context_store;
 10use crate::thread::ThreadId;
 11use crate::thread_store::ThreadStore;
 12
 13pub struct ThreadContextPicker {
 14    picker: View<Picker<ThreadContextPickerDelegate>>,
 15}
 16
 17impl ThreadContextPicker {
 18    pub fn new(
 19        thread_store: WeakModel<ThreadStore>,
 20        context_picker: WeakView<ContextPicker>,
 21        context_store: WeakModel<context_store::ContextStore>,
 22        confirm_behavior: ConfirmBehavior,
 23        cx: &mut ViewContext<Self>,
 24    ) -> Self {
 25        let delegate = ThreadContextPickerDelegate::new(
 26            thread_store,
 27            context_picker,
 28            context_store,
 29            confirm_behavior,
 30        );
 31        let picker = cx.new_view(|cx| Picker::uniform_list(delegate, cx));
 32
 33        ThreadContextPicker { picker }
 34    }
 35}
 36
 37impl FocusableView for ThreadContextPicker {
 38    fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
 39        self.picker.focus_handle(cx)
 40    }
 41}
 42
 43impl Render for ThreadContextPicker {
 44    fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
 45        self.picker.clone()
 46    }
 47}
 48
 49#[derive(Debug, Clone)]
 50struct ThreadContextEntry {
 51    id: ThreadId,
 52    summary: SharedString,
 53}
 54
 55pub struct ThreadContextPickerDelegate {
 56    thread_store: WeakModel<ThreadStore>,
 57    context_picker: WeakView<ContextPicker>,
 58    context_store: WeakModel<context_store::ContextStore>,
 59    confirm_behavior: ConfirmBehavior,
 60    matches: Vec<ThreadContextEntry>,
 61    selected_index: usize,
 62}
 63
 64impl ThreadContextPickerDelegate {
 65    pub fn new(
 66        thread_store: WeakModel<ThreadStore>,
 67        context_picker: WeakView<ContextPicker>,
 68        context_store: WeakModel<context_store::ContextStore>,
 69        confirm_behavior: ConfirmBehavior,
 70    ) -> Self {
 71        ThreadContextPickerDelegate {
 72            thread_store,
 73            context_picker,
 74            context_store,
 75            confirm_behavior,
 76            matches: Vec::new(),
 77            selected_index: 0,
 78        }
 79    }
 80}
 81
 82impl PickerDelegate for ThreadContextPickerDelegate {
 83    type ListItem = ListItem;
 84
 85    fn match_count(&self) -> usize {
 86        self.matches.len()
 87    }
 88
 89    fn selected_index(&self) -> usize {
 90        self.selected_index
 91    }
 92
 93    fn set_selected_index(&mut self, ix: usize, _cx: &mut ViewContext<Picker<Self>>) {
 94        self.selected_index = ix;
 95    }
 96
 97    fn placeholder_text(&self, _cx: &mut WindowContext) -> Arc<str> {
 98        "Search threads…".into()
 99    }
100
101    fn update_matches(&mut self, query: String, cx: &mut ViewContext<Picker<Self>>) -> Task<()> {
102        let Ok(threads) = self.thread_store.update(cx, |this, cx| {
103            this.threads(cx)
104                .into_iter()
105                .map(|thread| {
106                    const DEFAULT_SUMMARY: SharedString = SharedString::new_static("New Thread");
107
108                    let id = thread.read(cx).id().clone();
109                    let summary = thread.read(cx).summary().unwrap_or(DEFAULT_SUMMARY);
110                    ThreadContextEntry { id, summary }
111                })
112                .collect::<Vec<_>>()
113        }) else {
114            return Task::ready(());
115        };
116
117        let executor = cx.background_executor().clone();
118        let search_task = cx.background_executor().spawn(async move {
119            if query.is_empty() {
120                threads
121            } else {
122                let candidates = threads
123                    .iter()
124                    .enumerate()
125                    .map(|(id, thread)| StringMatchCandidate::new(id, &thread.summary))
126                    .collect::<Vec<_>>();
127                let matches = fuzzy::match_strings(
128                    &candidates,
129                    &query,
130                    false,
131                    100,
132                    &Default::default(),
133                    executor,
134                )
135                .await;
136
137                matches
138                    .into_iter()
139                    .map(|mat| threads[mat.candidate_id].clone())
140                    .collect()
141            }
142        });
143
144        cx.spawn(|this, mut cx| async move {
145            let matches = search_task.await;
146            this.update(&mut cx, |this, cx| {
147                this.delegate.matches = matches;
148                this.delegate.selected_index = 0;
149                cx.notify();
150            })
151            .ok();
152        })
153    }
154
155    fn confirm(&mut self, _secondary: bool, cx: &mut ViewContext<Picker<Self>>) {
156        let Some(entry) = self.matches.get(self.selected_index) else {
157            return;
158        };
159
160        let Some(thread_store) = self.thread_store.upgrade() else {
161            return;
162        };
163
164        let Some(thread) = thread_store.update(cx, |this, cx| this.open_thread(&entry.id, cx))
165        else {
166            return;
167        };
168
169        self.context_store
170            .update(cx, |context_store, cx| {
171                if let Some(context_id) = context_store.included_thread(&entry.id) {
172                    context_store.remove_context(&context_id);
173                } else {
174                    context_store.insert_thread(thread.read(cx));
175                }
176            })
177            .ok();
178
179        match self.confirm_behavior {
180            ConfirmBehavior::KeepOpen => {}
181            ConfirmBehavior::Close => self.dismissed(cx),
182        }
183    }
184
185    fn dismissed(&mut self, cx: &mut ViewContext<Picker<Self>>) {
186        self.context_picker
187            .update(cx, |this, cx| {
188                this.reset_mode();
189                cx.emit(DismissEvent);
190            })
191            .ok();
192    }
193
194    fn render_match(
195        &self,
196        ix: usize,
197        selected: bool,
198        cx: &mut ViewContext<Picker<Self>>,
199    ) -> Option<Self::ListItem> {
200        let thread = &self.matches[ix];
201
202        let added = self.context_store.upgrade().map_or(false, |ctx_store| {
203            ctx_store.read(cx).included_thread(&thread.id).is_some()
204        });
205
206        Some(
207            ListItem::new(ix)
208                .inset(true)
209                .toggle_state(selected)
210                .child(Label::new(thread.summary.clone()))
211                .when(added, |el| {
212                    el.end_slot(
213                        h_flex()
214                            .gap_1()
215                            .child(
216                                Icon::new(IconName::Check)
217                                    .size(IconSize::Small)
218                                    .color(Color::Success),
219                            )
220                            .child(Label::new("Added").size(LabelSize::Small)),
221                    )
222                }),
223        )
224    }
225}