BlueGit

ict rusty-teams

Files

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

feed.rs

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