BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / views / composer / post.rs

post.rs

post.rs 19.7 KiB Download Raw
1use gpui_kit::component::input::{Input, InputEvent, InputState};
2use gpui_kit::component::tooltip::Tooltip;
3use gpui_kit::component::{Sizable as _, Size, h_flex, v_flex};
4use gpui_kit::prelude::FluentBuilder as _;
5use gpui_kit::*;
6
7use crate::banner_image::prepare_banner_image;
8use teams_core::{AnnouncementBanner, BannerBackground};
9
10use super::{COMPOSER_BUTTON_SIZE, COMPOSER_ICON_SIZE, Composer, ComposerEvent};
11use crate::runtime;
12use crate::theme;
13use crate::views::announcement_banner::{
14 BANNER_COLORS, banner_fill, banner_frame, color_label, headline_style,
15};
16use crate::views::avatar::person_avatar;
17use crate::views::widgets::symbol;
18
19pub const POST_CARD_HEADER_TAG: &str = "composer/post/header";
20pub const POST_CARD_SUBJECT_TAG: &str = "composer/post/subject";
21pub const POST_CARD_DIVIDER_TAG: &str = "composer/post/divider";
22pub const POST_CARD_FOOTER_TAG: &str = "composer/post/footer";
23pub const POST_CARD_SEND_TAG: &str = "composer/post/send";
24pub const POST_ANNOUNCEMENT_TAG: &str = "composer/post/announcement";
25pub const POST_ANNOUNCEMENT_TOGGLE_TAG: &str = "composer/post/announcement-toggle";
26pub const POST_AUDIENCE_TAG: &str = "composer/post/audience";
27const DEMO_AUDIENCE: usize = 24;
28const AUDIENCE_HEIGHT: f32 = 32.;
29const ANNOUNCEMENT_TOOLTIP: &str = "Announcement";
30const BANNER_IMAGE_TOOLTIP: &str = "Upload an image";
31const HEADLINE_PLACEHOLDER: &str = "Type a headline";
32pub const SUBJECT_PLACEHOLDER: &str = "Add a subject";
33const SUBHEADING_PLACEHOLDER: &str = "Add a subheading";
34const HEADLINE_SIZE: f32 = 32.;
35const COMPOSER_BANNER_HEIGHT: f32 = 240.;
36const HEADLINE_LINE: f32 = 1.25;
37const SWATCH_SIZE: f32 = 18.;
38const SWATCH_RING: f32 = 2.;
39const SWATCH_GAP: f32 = 6.;
40const SWATCH_INSET: f32 = 8.;
41const POST_LABEL: &str = "Post";
42const CLOSE_TOOLTIP: &str = "Close";
43const AUTHOR_AVATAR: f32 = 24.;
44const CARD_INSET: f32 = 12.;
45const SUBJECT_SIZE: f32 = 18.;
46const INPUT_TEXT_SCALE: f32 = 0.875;
47const SUBJECT_INSET: f32 = 8.;
48const TEXT_INSET: f32 = 16.;
49
50pub(super) struct AnnouncementDraft {
51 pub(super) headline: Entity<InputState>,
52 color: &'static str,
53 image: Option<String>,
54 _changes: Subscription,
55}
56
57impl AnnouncementDraft {
58 fn background(&self) -> BannerBackground {
59 match &self.image {
60 Some(path) => BannerBackground::LocalImage(path.clone()),
61 None => BannerBackground::Color(self.color.to_owned()),
62 }
63 }
64}
65
66pub fn audience_hint(count: usize) -> String {
67 match count {
68 1 => "1 person will see your message.".to_owned(),
69 count => format!("{count} people will see your message."),
70 }
71}
72
73impl Composer {
74 /// Shows the channel post layout with `subject` above the body, or the chat layout when `None`.
75 pub fn set_post_layout(&mut self, subject: Option<Entity<InputState>>, cx: &mut Context<Self>) {
76 let changed = self.post_subject.as_ref().map(Entity::entity_id)
77 != subject.as_ref().map(Entity::entity_id);
78 self.post_subject = subject;
79 if self.post_subject.is_none() {
80 self.announcement = None;
81 }
82 if changed {
83 self.schedule_draft_save(cx);
84 cx.notify();
85 }
86 }
87
88 pub(super) fn post_layout(&self) -> bool {
89 self.post_subject.is_some() && self.editing.is_none()
90 }
91
92 pub(super) fn post_subject_text(&self, cx: &App) -> Option<String> {
93 let subject = self.post_subject.as_ref().filter(|_| self.post_layout())?;
94 let text = subject.read(cx).value().trim().to_owned();
95 (!text.is_empty()).then_some(text)
96 }
97
98 /// Saves the draft with its post subject and banner before the post card closes.
99 pub fn leave_conversation(&mut self, next_conversation_id: &str, cx: &mut Context<Self>) {
100 if self.conversation_id.as_deref() != Some(next_conversation_id) {
101 self.save_draft_now(cx);
102 self.conversation_id = None;
103 }
104 }
105
106 pub(super) fn announcement_banner(&self, cx: &App) -> Option<AnnouncementBanner> {
107 let draft = self.announcement.as_ref().filter(|_| self.post_layout())?;
108 let title = draft.headline.read(cx).value().trim().to_owned();
109 (!title.is_empty()).then(|| AnnouncementBanner {
110 title,
111 background: draft.background(),
112 })
113 }
114
115 pub(super) fn restore_announcement(
116 &mut self,
117 banner: Option<&AnnouncementBanner>,
118 window: &mut Window,
119 cx: &mut Context<Self>,
120 ) {
121 match banner {
122 Some(banner) => {
123 let color = match &banner.background {
124 BannerBackground::Color(color) => BANNER_COLORS
125 .into_iter()
126 .find(|known| known == color)
127 .unwrap_or(BANNER_COLORS[0]),
128 BannerBackground::Image(_) | BannerBackground::LocalImage(_) => {
129 BANNER_COLORS[0]
130 }
131 };
132 self.open_announcement(color, window, cx);
133 if let Some(draft) = self.announcement.as_mut() {
134 if let BannerBackground::LocalImage(path) = &banner.background {
135 draft.image = Some(path.clone());
136 }
137 let title = banner.title.clone();
138 draft
139 .headline
140 .update(cx, |input, cx| input.set_value(title, window, cx));
141 }
142 }
143 None => self.close_announcement(window, cx),
144 }
145 }
146
147 pub fn begin_announcement(&mut self, window: &mut Window, cx: &mut Context<Self>) {
148 if self.announcement.is_none() {
149 self.toggle_announcement(window, cx);
150 }
151 }
152
153 pub(super) fn toggle_announcement(&mut self, window: &mut Window, cx: &mut Context<Self>) {
154 if self.announcement.is_some() {
155 self.close_announcement(window, cx);
156 self.focus(window, cx);
157 } else {
158 self.open_announcement(BANNER_COLORS[0], window, cx);
159 if let Some(draft) = &self.announcement {
160 draft
161 .headline
162 .update(cx, |input, cx| input.focus(window, cx));
163 }
164 }
165 }
166
167 fn open_announcement(
168 &mut self,
169 color: &'static str,
170 window: &mut Window,
171 cx: &mut Context<Self>,
172 ) {
173 let headline = cx.new(|cx| InputState::new(window, cx).placeholder(HEADLINE_PLACEHOLDER));
174 let changes = cx.subscribe(&headline, |this, _, event: &InputEvent, cx| {
175 if matches!(event, InputEvent::Change) {
176 this.schedule_draft_save(cx);
177 }
178 });
179 self.announcement = Some(AnnouncementDraft {
180 headline,
181 color,
182 image: None,
183 _changes: changes,
184 });
185 self.set_subject_placeholder(SUBHEADING_PLACEHOLDER, window, cx);
186 self.load_audience(cx);
187 self.schedule_draft_save(cx);
188 cx.notify();
189 }
190
191 fn pick_banner_image(&mut self, window: &mut Window, cx: &mut Context<Self>) {
192 let receiver = cx.prompt_for_paths(PathPromptOptions {
193 files: true,
194 directories: false,
195 multiple: false,
196 prompt: None,
197 });
198 cx.spawn_in(window, async move |this, cx| {
199 let Ok(Ok(Some(paths))) = receiver.await else {
200 return;
201 };
202 let Some(source) = paths.into_iter().next() else {
203 return;
204 };
205 let prepared = cx
206 .background_executor()
207 .spawn(async move { prepare_banner_image(&source) })
208 .await;
209 this.update(cx, |this, cx| match prepared {
210 Ok(path) => {
211 if let Some(draft) = this.announcement.as_mut() {
212 draft.image = Some(path.to_string_lossy().into_owned());
213 this.schedule_draft_save(cx);
214 cx.notify();
215 }
216 }
217 Err(error) => log::warn!("banner image: {error}"),
218 })
219 .ok();
220 })
221 .detach();
222 }
223
224 pub(super) fn close_announcement(&mut self, window: &mut Window, cx: &mut Context<Self>) {
225 if self.announcement.take().is_some() {
226 self.set_subject_placeholder(SUBJECT_PLACEHOLDER, window, cx);
227 self.schedule_draft_save(cx);
228 cx.notify();
229 }
230 }
231
232 fn load_audience(&mut self, cx: &mut Context<Self>) {
233 let Some(channel_id) = self.conversation_id.clone() else {
234 return;
235 };
236 if self
237 .audience
238 .as_ref()
239 .is_some_and(|(id, _)| *id == channel_id)
240 {
241 return;
242 }
243 let state = self.app.read(cx);
244 if state.mode.demo {
245 self.audience = Some((channel_id, DEMO_AUDIENCE));
246 return;
247 }
248 let Some(engine) = state.engine.clone() else {
249 return;
250 };
251 let lookup = channel_id.clone();
252 let receiver = runtime::spawn(async move { engine.channel_member_count(&lookup).await });
253 cx.spawn(async move |this, cx| {
254 let Ok(Ok(count)) = receiver.await else {
255 return;
256 };
257 this.update(cx, |this, cx| {
258 if this.conversation_id.as_deref() == Some(channel_id.as_str()) {
259 this.audience = Some((channel_id, count));
260 cx.notify();
261 }
262 })
263 .ok();
264 })
265 .detach();
266 }
267
268 pub(super) fn render_audience_hint(&self) -> Option<Div> {
269 self.announcement.as_ref().filter(|_| self.post_layout())?;
270 let (channel_id, count) = self.audience.as_ref()?;
271 (self.conversation_id.as_ref() == Some(channel_id)).then(|| {
272 h_flex()
273 .debug_selector(|| POST_AUDIENCE_TAG.into())
274 .w_full()
275 .h(px(AUDIENCE_HEIGHT))
276 .mb(px(8.))
277 .px(px(CARD_INSET))
278 .items_center()
279 .rounded(px(10.))
280 .bg(theme::surface_raised())
281 .text_size(px(12.))
282 .text_color(theme::text_muted())
283 .child(audience_hint(*count))
284 })
285 }
286
287 pub fn sync_subject_placeholder(&self, window: &mut Window, cx: &mut Context<Self>) {
288 let placeholder = if self.announcement.is_some() {
289 SUBHEADING_PLACEHOLDER
290 } else {
291 SUBJECT_PLACEHOLDER
292 };
293 self.set_subject_placeholder(placeholder, window, cx);
294 }
295
296 fn set_subject_placeholder(
297 &self,
298 placeholder: &'static str,
299 window: &mut Window,
300 cx: &mut Context<Self>,
301 ) {
302 if let Some(subject) = &self.post_subject {
303 subject.update(cx, |input, cx| {
304 input.set_placeholder(placeholder, window, cx)
305 });
306 }
307 }
308
309 pub(super) fn render_announcement_toggle(
310 &self,
311 cx: &mut Context<Self>,
312 ) -> Option<Stateful<Div>> {
313 if !self.post_layout() {
314 return None;
315 }
316 let active = self.announcement.is_some();
317 Some(
318 div()
319 .id("composer-post-announcement")
320 .debug_selector(|| POST_ANNOUNCEMENT_TOGGLE_TAG.into())
321 .size(px(COMPOSER_BUTTON_SIZE))
322 .flex_none()
323 .flex()
324 .items_center()
325 .justify_center()
326 .rounded(px(6.))
327 .cursor_pointer()
328 .when(active, |button| button.bg(theme::popup_hover()))
329 .hover(|button| button.bg(theme::popup_hover()))
330 .tooltip(|window, cx| Tooltip::new(ANNOUNCEMENT_TOOLTIP).build(window, cx))
331 .child(symbol(
332 "campaign",
333 COMPOSER_ICON_SIZE,
334 if active {
335 theme::accent_soft()
336 } else {
337 theme::text_muted()
338 },
339 ))
340 .on_mouse_down(MouseButton::Left, |_, window, cx| {
341 window.prevent_default();
342 cx.stop_propagation();
343 })
344 .on_click(cx.listener(|this, _, window, cx| this.toggle_announcement(window, cx))),
345 )
346 }
347
348 fn render_announcement(&self, cx: &mut Context<Self>) -> Option<Div> {
349 let draft = self.announcement.as_ref()?;
350 let directory = &self.app.read(cx).directory;
351 let swatches = h_flex()
352 .absolute()
353 .right(px(SWATCH_INSET))
354 .bottom(px(SWATCH_INSET))
355 .gap(px(SWATCH_GAP))
356 .children(BANNER_COLORS.into_iter().map(|color| {
357 let selected = color == draft.color && draft.image.is_none();
358 div()
359 .id(ElementId::Name(format!("composer-banner-{color}").into()))
360 .size(px(SWATCH_SIZE))
361 .rounded_full()
362 .border(px(SWATCH_RING))
363 .border_color(if selected {
364 white()
365 } else {
366 white().opacity(0.4)
367 })
368 .bg(banner_fill(color))
369 .cursor_pointer()
370 .tooltip(move |window, cx| Tooltip::new(color_label(color)).build(window, cx))
371 .on_click(cx.listener(move |this, _, _, cx| {
372 if let Some(draft) = this.announcement.as_mut() {
373 draft.color = color;
374 draft.image = None;
375 this.schedule_draft_save(cx);
376 cx.notify();
377 }
378 }))
379 }))
380 .child({
381 let selected = draft.image.is_some();
382 div()
383 .id("composer-banner-image")
384 .size(px(SWATCH_SIZE))
385 .flex()
386 .items_center()
387 .justify_center()
388 .rounded_full()
389 .border(px(SWATCH_RING))
390 .border_color(if selected {
391 white()
392 } else {
393 white().opacity(0.4)
394 })
395 .bg(black().opacity(0.35))
396 .cursor_pointer()
397 .tooltip(|window, cx| Tooltip::new(BANNER_IMAGE_TOOLTIP).build(window, cx))
398 .child(symbol("image", SWATCH_SIZE - 6., white()))
399 .on_click(cx.listener(|this, _, window, cx| this.pick_banner_image(window, cx)))
400 });
401 Some(
402 div()
403 .debug_selector(|| POST_ANNOUNCEMENT_TAG.into())
404 .w_full()
405 .px(px(CARD_INSET))
406 .pt(px(CARD_INSET))
407 .child(
408 banner_frame(&draft.background(), directory)
409 .h(px(COMPOSER_BANNER_HEIGHT))
410 .child(
411 headline_style(div().w_full()).child(
412 Input::new(&draft.headline)
413 .appearance(false)
414 .bordered(false)
415 .text_center()
416 .h(px(HEADLINE_SIZE * HEADLINE_LINE))
417 .line_height(px(HEADLINE_SIZE * HEADLINE_LINE))
418 .with_size(Size::Size(px(HEADLINE_SIZE / INPUT_TEXT_SCALE))),
419 ),
420 )
421 .child(swatches),
422 ),
423 )
424 }
425
426 pub(super) fn render_post_header(&self, cx: &mut Context<Self>) -> Option<Div> {
427 let subject = self
428 .post_subject
429 .clone()
430 .filter(|_| self.editing.is_none())?;
431 let directory = &self.app.read(cx).directory;
432 let author = directory.me.as_ref().map(|me| {
433 h_flex()
434 .gap(px(8.))
435 .items_center()
436 .child(person_avatar(
437 directory,
438 Some(&me.user_id),
439 &me.display_name,
440 AUTHOR_AVATAR,
441 ))
442 .child(
443 div()
444 .text_size(px(13.))
445 .font_weight(FontWeight::SEMIBOLD)
446 .text_color(theme::text_strong())
447 .child(me.display_name.clone()),
448 )
449 });
450 let close = div()
451 .id("composer-post-close")
452 .size(px(28.))
453 .flex_none()
454 .flex()
455 .items_center()
456 .justify_center()
457 .rounded(px(6.))
458 .cursor_pointer()
459 .hover(|button| button.bg(theme::popup_hover()))
460 .tooltip(|window, cx| Tooltip::new(CLOSE_TOOLTIP).build(window, cx))
461 .child(symbol("close", 18., theme::text_muted()))
462 .on_click(cx.listener(|_, _, _, cx| cx.emit(ComposerEvent::ClosePost)));
463 Some(
464 v_flex()
465 .w_full()
466 .child(
467 h_flex()
468 .debug_selector(|| POST_CARD_HEADER_TAG.into())
469 .w_full()
470 .pl(px(TEXT_INSET))
471 .pr(px(CARD_INSET))
472 .pt(px(CARD_INSET))
473 .items_center()
474 .children(author)
475 .child(div().flex_1())
476 .child(close),
477 )
478 .children(self.render_announcement(cx))
479 .child(
480 div()
481 .debug_selector(|| POST_CARD_SUBJECT_TAG.into())
482 .w_full()
483 .px(px(SUBJECT_INSET))
484 .py(px(6.))
485 .font_weight(FontWeight::SEMIBOLD)
486 .child(
487 Input::new(&subject)
488 .appearance(false)
489 .bordered(false)
490 .with_size(Size::Size(px(SUBJECT_SIZE / INPUT_TEXT_SCALE))),
491 ),
492 )
493 .child(
494 div()
495 .debug_selector(|| POST_CARD_DIVIDER_TAG.into())
496 .w_full()
497 .h(px(1.))
498 .bg(theme::border()),
499 ),
500 )
501 }
502
503 pub(super) fn render_post_footer(
504 &self,
505 actions: impl IntoElement,
506 can_send: bool,
507 cx: &mut Context<Self>,
508 ) -> Div {
509 h_flex()
510 .debug_selector(|| POST_CARD_FOOTER_TAG.into())
511 .w_full()
512 .px(px(CARD_INSET))
513 .pb(px(CARD_INSET))
514 .items_center()
515 .child(actions)
516 .child(div().flex_1())
517 .child(
518 div()
519 .id("composer-post-send")
520 .debug_selector(|| POST_CARD_SEND_TAG.into())
521 .h(px(COMPOSER_BUTTON_SIZE))
522 .px(px(14.))
523 .flex()
524 .items_center()
525 .rounded(px(6.))
526 .bg(theme::accent())
527 .text_size(px(13.))
528 .font_weight(FontWeight::SEMIBOLD)
529 .text_color(theme::on_accent())
530 .child(POST_LABEL)
531 .when(!can_send, |button| button.opacity(0.4))
532 .when(can_send, |button| {
533 button.cursor_pointer().on_click(
534 cx.listener(|this, _, window, cx| this.submit_current(window, cx)),
535 )
536 }),
537 )
538 }
539}