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::{self, ContextStore};
 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)]
 50pub struct ThreadContextEntry {
 51    pub id: ThreadId,
 52    pub 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                    let id = thread.read(cx).id().clone();
107                    let summary = thread.read(cx).summary_or_default();
108                    ThreadContextEntry { id, summary }
109                })
110                .collect::<Vec<_>>()
111        }) else {
112            return Task::ready(());
113        };
114
115        let executor = cx.background_executor().clone();
116        let search_task = cx.background_executor().spawn(async move {
117            if query.is_empty() {
118                threads
119            } else {
120                let candidates = threads
121                    .iter()
122                    .enumerate()
123                    .map(|(id, thread)| StringMatchCandidate::new(id, &thread.summary))
124                    .collect::<Vec<_>>();
125                let matches = fuzzy::match_strings(
126                    &candidates,
127                    &query,
128                    false,
129                    100,
130                    &Default::default(),
131                    executor,
132                )
133                .await;
134
135                matches
136                    .into_iter()
137                    .map(|mat| threads[mat.candidate_id].clone())
138                    .collect()
139            }
140        });
141
142        cx.spawn(|this, mut cx| async move {
143            let matches = search_task.await;
144            this.update(&mut cx, |this, cx| {
145                this.delegate.matches = matches;
146                this.delegate.selected_index = 0;
147                cx.notify();
148            })
149            .ok();
150        })
151    }
152
153    fn confirm(&mut self, _secondary: bool, cx: &mut ViewContext<Picker<Self>>) {
154        let Some(entry) = self.matches.get(self.selected_index) else {
155            return;
156        };
157
158        let Some(thread_store) = self.thread_store.upgrade() else {
159            return;
160        };
161
162        let Some(thread) = thread_store.update(cx, |this, cx| this.open_thread(&entry.id, cx))
163        else {
164            return;
165        };
166
167        self.context_store
168            .update(cx, |context_store, cx| context_store.add_thread(thread, cx))
169            .ok();
170
171        match self.confirm_behavior {
172            ConfirmBehavior::KeepOpen => {}
173            ConfirmBehavior::Close => self.dismissed(cx),
174        }
175    }
176
177    fn dismissed(&mut self, cx: &mut ViewContext<Picker<Self>>) {
178        self.context_picker
179            .update(cx, |this, cx| {
180                this.reset_mode(cx);
181                cx.emit(DismissEvent);
182            })
183            .ok();
184    }
185
186    fn render_match(
187        &self,
188        ix: usize,
189        selected: bool,
190        cx: &mut ViewContext<Picker<Self>>,
191    ) -> Option<Self::ListItem> {
192        let thread = &self.matches[ix];
193
194        Some(ListItem::new(ix).inset(true).toggle_state(selected).child(
195            render_thread_context_entry(thread, self.context_store.clone(), cx),
196        ))
197    }
198}
199
200pub fn render_thread_context_entry(
201    thread: &ThreadContextEntry,
202    context_store: WeakModel<ContextStore>,
203    cx: &mut WindowContext,
204) -> Div {
205    let added = context_store.upgrade().map_or(false, |ctx_store| {
206        ctx_store.read(cx).includes_thread(&thread.id).is_some()
207    });
208
209    h_flex()
210        .gap_1()
211        .w_full()
212        .child(Icon::new(IconName::MessageCircle).size(IconSize::Small))
213        .child(Label::new(thread.summary.clone()))
214        .child(div().w_full())
215        .when(added, |el| {
216            el.child(
217                h_flex()
218                    .gap_1()
219                    .child(
220                        Icon::new(IconName::Check)
221                            .size(IconSize::Small)
222                            .color(Color::Success),
223                    )
224                    .child(Label::new("Added").size(LabelSize::Small)),
225            )
226        })
227}