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| context_store.add_thread(thread, cx))
171            .ok();
172
173        match self.confirm_behavior {
174            ConfirmBehavior::KeepOpen => {}
175            ConfirmBehavior::Close => self.dismissed(cx),
176        }
177    }
178
179    fn dismissed(&mut self, cx: &mut ViewContext<Picker<Self>>) {
180        self.context_picker
181            .update(cx, |this, cx| {
182                this.reset_mode();
183                cx.emit(DismissEvent);
184            })
185            .ok();
186    }
187
188    fn render_match(
189        &self,
190        ix: usize,
191        selected: bool,
192        cx: &mut ViewContext<Picker<Self>>,
193    ) -> Option<Self::ListItem> {
194        let thread = &self.matches[ix];
195
196        let added = self.context_store.upgrade().map_or(false, |context_store| {
197            context_store.read(cx).includes_thread(&thread.id).is_some()
198        });
199
200        Some(
201            ListItem::new(ix)
202                .inset(true)
203                .toggle_state(selected)
204                .child(Label::new(thread.summary.clone()))
205                .when(added, |el| {
206                    el.end_slot(
207                        h_flex()
208                            .gap_1()
209                            .child(
210                                Icon::new(IconName::Check)
211                                    .size(IconSize::Small)
212                                    .color(Color::Success),
213                            )
214                            .child(Label::new("Added").size(LabelSize::Small)),
215                    )
216                }),
217        )
218    }
219}