BlueGit

ict rusty-teams

Files

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

feed.rs

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