BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / views / conversation / feed.rs

feed.rs

feed.rs 15.0 KiB Download Raw
1use std::cell::RefCell;
2use std::rc::Rc;
3
4use gpui_kit::assets::IconName;
5use gpui_kit::component::{
6 button::{Button, ButtonVariants as _},
7 h_flex,
8 input::{Input, InputEvent, InputState},
9 message_scroller::MessageScrollerState,
10 v_flex,
11};
12use gpui_kit::*;
13
14use super::{ConversationView, ViewMode};
15use crate::notice::short_error;
16use crate::rows::Row;
17use crate::runtime;
18use crate::theme;
19use crate::views::channel_tabs::ChannelPane;
20use crate::views::composer::{Composer, ComposerEvent, ReplyPreview};
21use crate::views::post_card::{PostAction, post_in_channel_card};
22use crate::views::widgets::icon;
23
24const REPLY_PLACEHOLDER: &str = "Reply in thread";
25const SUBJECT_PLACEHOLDER: &str = "Add a subject";
26
27pub(super) struct FeedStash {
28 scroller: Entity<MessageScrollerState>,
29 rows: Rc<RefCell<Vec<Row>>>,
30 near_top: bool,
31}
32
33pub(super) fn subject_input(
34 window: &mut Window,
35 cx: &mut Context<ConversationView>,
36) -> Entity<InputState> {
37 cx.new(|cx| InputState::new(window, cx).placeholder(SUBJECT_PLACEHOLDER))
38}
39
40impl ConversationView {
41 pub(super) fn in_feed(&self) -> bool {
42 !self.draft_active
43 && self
44 .current
45 .as_ref()
46 .is_some_and(|current| current.mode == ViewMode::ThreadList)
47 }
48
49 pub(super) fn open_new_post(&mut self, window: &mut Window, cx: &mut Context<Self>) {
50 self.new_post_open = true;
51 self.composer
52 .update(cx, |composer, cx| composer.focus(window, cx));
53 cx.notify();
54 }
55
56 pub(super) fn close_new_post(&mut self, cx: &mut Context<Self>) {
57 if self.new_post_open {
58 self.new_post_open = false;
59 cx.notify();
60 }
61 }
62
63 pub(super) fn take_subject(
64 &mut self,
65 window: &mut Window,
66 cx: &mut Context<Self>,
67 ) -> Option<String> {
68 let subject = self.subject.read(cx).value().trim().to_owned();
69 self.subject
70 .update(cx, |input, cx| input.set_value("", window, cx));
71 (!subject.is_empty()).then_some(subject)
72 }
73
74 pub(super) fn restore_subject(
75 &mut self,
76 subject: Option<&str>,
77 window: &mut Window,
78 cx: &mut Context<Self>,
79 ) {
80 let subject = subject.unwrap_or_default().to_owned();
81 self.subject
82 .update(cx, |input, cx| input.set_value(subject, window, cx));
83 }
84
85 pub(super) fn has_subject(&self, cx: &App) -> bool {
86 !self.subject.read(cx).value().trim().is_empty()
87 }
88
89 pub(super) fn on_subject_event(
90 &mut self,
91 _: &Entity<InputState>,
92 event: &InputEvent,
93 window: &mut Window,
94 cx: &mut Context<Self>,
95 ) {
96 if matches!(event, InputEvent::PressEnter { .. }) {
97 self.composer
98 .update(cx, |composer, cx| composer.focus(window, cx));
99 }
100 }
101
102 fn reply_composer(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Composer> {
103 if let Some(composer) = &self.reply_composer {
104 return composer.clone();
105 }
106 let composer = cx.new(|cx| Composer::new(self.app.clone(), window, cx).inline());
107 let subscription = cx.subscribe_in(&composer, window, Self::on_reply_event);
108 self._subscriptions.push(subscription);
109 self.reply_composer = Some(composer.clone());
110 self.sync_reply_composer(window, cx);
111 composer
112 }
113
114 fn keep_reply_editor_in_view(&mut self, window: &mut Window, cx: &mut Context<Self>) {
115 let Some(root_id) = self.reply_root.clone() else {
116 return;
117 };
118 if !self.in_feed() {
119 return;
120 }
121 let view = cx.entity().downgrade();
122 window.on_next_frame(move |_, cx| {
123 view.update(cx, |this, cx| {
124 let index = this.rows.borrow().iter().position(|row| row.key() == root_id);
125 if let Some(index) = index {
126 this.scroller
127 .update(cx, |scroller, cx| scroller.reveal_item_bottom(index, cx));
128 }
129 })
130 .ok();
131 });
132 }
133
134 pub(super) fn sync_reply_composer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
135 self.reply_root = None;
136 let (Some(composer), Some(conversation_id)) =
137 (self.reply_composer.clone(), self.conversation_id())
138 else {
139 return;
140 };
141 composer.update(cx, |composer, cx| {
142 composer.set_conversation(&conversation_id, "", window, cx);
143 composer.set_placeholder(REPLY_PLACEHOLDER, window, cx);
144 composer.set_text("", window, cx);
145 composer.set_reply(None, cx);
146 });
147 }
148
149 pub(super) fn open_reply_editor(
150 &mut self,
151 root_id: String,
152 quote: Option<ReplyPreview>,
153 window: &mut Window,
154 cx: &mut Context<Self>,
155 ) {
156 let composer = self.reply_composer(window, cx);
157 let previous = self.reply_root.replace(root_id.clone());
158 let changed = previous.as_deref() != Some(root_id.as_str());
159 composer.update(cx, |composer, cx| {
160 if changed {
161 composer.set_text("", window, cx);
162 }
163 composer.set_reply(quote, cx);
164 composer.focus(window, cx);
165 });
166 self.remeasure_posts(&[Some(root_id), previous], cx);
167 }
168
169 pub(super) fn close_reply_editor(&mut self, cx: &mut Context<Self>) {
170 if let Some(root_id) = self.reply_root.take() {
171 self.remeasure_posts(&[Some(root_id)], cx);
172 }
173 }
174
175 fn remeasure_posts(&mut self, root_ids: &[Option<String>], cx: &mut Context<Self>) {
176 let indices: Vec<usize> = self
177 .rows
178 .borrow()
179 .iter()
180 .enumerate()
181 .filter(|(_, row)| {
182 matches!(row, Row::Post(post) if root_ids.iter().flatten().any(|id| *id == post.root.key))
183 })
184 .map(|(index, _)| index)
185 .collect();
186 self.scroller.update(cx, |scroller, cx| {
187 for index in indices {
188 scroller.remeasure_items(index..index + 1, cx);
189 }
190 });
191 cx.notify();
192 }
193
194 fn on_reply_event(
195 &mut self,
196 _: &Entity<Composer>,
197 event: &ComposerEvent,
198 window: &mut Window,
199 cx: &mut Context<Self>,
200 ) {
201 self.report_composer_activity(event, cx);
202 match event {
203 ComposerEvent::Submit(outgoing) => {
204 let Some(root_id) = self.reply_root.clone() else {
205 return;
206 };
207 self.close_reply_editor(cx);
208 self.send_in_thread(root_id, (**outgoing).clone(), window, cx);
209 }
210 ComposerEvent::Typing(active) => {
211 let root_id = self.reply_root.clone();
212 self.send_typing_in(root_id, *active, cx);
213 }
214 ComposerEvent::Edited => self.keep_reply_editor_in_view(window, cx),
215 ComposerEvent::Schedule { .. }
216 | ComposerEvent::EditLast
217 | ComposerEvent::FocusMessages => {}
218 }
219 }
220
221 pub(super) fn stop_reply_typing(&mut self, cx: &mut Context<Self>) {
222 let Some(composer) = self.reply_composer.clone() else {
223 return;
224 };
225 if composer.update(cx, |composer, _| composer.stop_typing()) {
226 let root_id = self.reply_root.clone();
227 self.send_typing_in(root_id, false, cx);
228 }
229 }
230
231 pub(super) fn show_main_composer(&mut self, cx: &mut Context<Self>) {
232 if self.in_feed() {
233 self.new_post_open = true;
234 cx.notify();
235 }
236 }
237
238 pub(super) fn render_new_post(
239 &self,
240 window: &Window,
241 cx: &mut Context<Self>,
242 ) -> Option<AnyElement> {
243 if !self.in_feed() || self.pane != ChannelPane::Posts {
244 return None;
245 }
246 let proposal_card = self.render_proposal_card(cx);
247 if !self.new_post_open {
248 let view = cx.entity().downgrade();
249 let open: PostAction = Box::new(move |window, cx| {
250 view.update(cx, |this, cx| this.open_new_post(window, cx)).ok();
251 });
252 return Some(
253 v_flex()
254 .w_full()
255 .flex_none()
256 .children(proposal_card)
257 .child(
258 div()
259 .w_full()
260 .flex_none()
261 .px(px(20.))
262 .pt(px(12.))
263 .child(post_in_channel_card(&self.app.read(cx).directory, open)),
264 )
265 .into_any_element(),
266 );
267 }
268 let editing = self.composer.read(cx).is_editing();
269 let focused = self
270 .subject
271 .read(cx)
272 .focus_handle(cx)
273 .contains_focused(window, cx);
274 let subject = (!editing).then(|| {
275 div().w_full().px(px(20.)).pt(px(12.)).child(
276 div()
277 .w_full()
278 .h(px(36.))
279 .px(px(12.))
280 .flex()
281 .items_center()
282 .rounded(px(10.))
283 .bg(theme::surface_raised())
284 .border_1()
285 .border_color(if focused {
286 theme::accent()
287 } else {
288 transparent_black()
289 })
290 .child(
291 div()
292 .w_full()
293 .child(Input::new(&self.subject).appearance(false).bordered(false)),
294 ),
295 )
296 });
297 Some(
298 v_flex()
299 .w_full()
300 .flex_none()
301 .children(subject)
302 .children(proposal_card)
303 .child(self.composer.clone())
304 .child(
305 h_flex()
306 .w_full()
307 .px(px(20.))
308 .pb(px(12.))
309 .justify_end()
310 .child(
311 Button::new("cancel-new-post")
312 .ghost()
313 .compact()
314 .label("Cancel")
315 .on_click(cx.listener(|this, _, window, cx| {
316 this.cancel_new_post(window, cx)
317 })),
318 ),
319 )
320 .into_any_element(),
321 )
322 }
323
324 pub(super) fn cancel_new_post(&mut self, window: &mut Window, cx: &mut Context<Self>) {
325 let editing = self.composer.read(cx).is_editing();
326 if editing {
327 self.composer
328 .update(cx, |composer, cx| composer.cancel_edit(window, cx));
329 }
330 self.close_new_post(cx);
331 }
332
333 pub(super) fn on_escape(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
334 if self.close_new_folder(cx) {
335 return true;
336 }
337 if self.reply_root.is_some() {
338 self.close_reply_editor(cx);
339 return true;
340 }
341 if self.new_post_open && self.in_feed() {
342 self.cancel_new_post(window, cx);
343 return true;
344 }
345 if matches!(
346 self.current.as_ref().map(|current| &current.mode),
347 Some(ViewMode::Thread(_))
348 ) && !self.draft_active
349 {
350 self.back_to_threads(cx);
351 return true;
352 }
353 false
354 }
355
356 pub(super) fn enter_thread_mode(&mut self, root_id: String, cx: &mut Context<Self>) {
357 let Some(current) = self.current.as_mut() else {
358 return;
359 };
360 if current.mode == ViewMode::ThreadList {
361 let stash = FeedStash {
362 scroller: self.scroller.clone(),
363 rows: self.rows.clone(),
364 near_top: self.feed_at_top,
365 };
366 self.feed_stash = Some(stash);
367 self.scroller = cx.new(|cx| MessageScrollerState::new(0, cx));
368 self.rows = Rc::new(RefCell::new(Vec::new()));
369 }
370 current.mode = ViewMode::Thread(root_id);
371 self.reply_root = None;
372 }
373
374 pub(super) fn enter_feed_mode(&mut self) -> bool {
375 let Some(current) = self.current.as_mut() else {
376 return false;
377 };
378 current.mode = ViewMode::ThreadList;
379 match self.feed_stash.take() {
380 Some(stash) => {
381 self.scroller = stash.scroller;
382 self.rows = stash.rows;
383 self.feed_at_top = stash.near_top;
384 true
385 }
386 None => false,
387 }
388 }
389
390 pub(super) fn open_thread(
391 &mut self,
392 root_id: String,
393 window: &mut Window,
394 cx: &mut Context<Self>,
395 ) {
396 self.stop_typing(cx);
397 self.stop_reply_typing(cx);
398 self.enter_thread_mode(root_id.clone(), cx);
399 self.reload_pending(cx);
400 self.rebuild(true, cx);
401 self.refresh_thread(root_id, cx);
402 self.composer
403 .update(cx, |composer, cx| composer.focus(window, cx));
404 }
405
406 pub(super) fn back_to_threads(&mut self, cx: &mut Context<Self>) {
407 self.stop_typing(cx);
408 let restored = self.enter_feed_mode();
409 self.reload_pending(cx);
410 self.rebuild(!restored, cx);
411 }
412
413 pub(super) fn refresh_thread(&mut self, root_id: String, cx: &mut Context<Self>) {
414 let state = self.app.read(cx);
415 if state.mode.demo || state.mode.read_only {
416 return;
417 }
418 let (Some(engine), Some(conversation_id)) = (state.engine.clone(), self.conversation_id())
419 else {
420 return;
421 };
422 let receiver = {
423 let (conversation_id, root_id) = (conversation_id.clone(), root_id.clone());
424 runtime::spawn(async move { engine.refresh_thread(&conversation_id, &root_id).await })
425 };
426 cx.spawn(async move |this, cx| {
427 let result = receiver.await;
428 this.update(cx, |this, cx| {
429 this.finish_thread_refresh(&conversation_id, &root_id, result, cx)
430 })
431 .ok();
432 })
433 .detach();
434 }
435
436 fn finish_thread_refresh(
437 &mut self,
438 conversation_id: &str,
439 root_id: &str,
440 result: Result<
441 teams_core::Result<teams_core::Delta>,
442 tokio::sync::oneshot::error::RecvError,
443 >,
444 cx: &mut Context<Self>,
445 ) {
446 let still_open = self.current.as_ref().is_some_and(|current| {
447 current.selection.conversation_id() == conversation_id
448 && current.mode == ViewMode::Thread(root_id.to_owned())
449 });
450 if !still_open {
451 return;
452 }
453 let failure = match result {
454 Ok(Ok(_)) => None,
455 Ok(Err(error)) => Some(short_error(&error)),
456 Err(error) => Some(short_error(&error)),
457 };
458 if let Some(failure) = failure {
459 self.notice = Some(format!("Could not load all replies: {failure}"));
460 }
461 self.rebuild(false, cx);
462 }
463}