BlueGit

ict rusty-teams

Files

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

feed.rs

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