BlueGit

ict rusty-teams

Files

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

post.rs

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