BlueGit

ict rusty-teams

Files

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

post.rs

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