BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / views / add_people_dialog.rs

add_people_dialog.rs

add_people_dialog.rs 10.3 KiB Download Raw
1use chatsvc::{HistoryShare, MAX_HISTORY_DAYS};
2use gpui_kit::component::button::{Button, ButtonVariants as _};
3use gpui_kit::component::dialog::{Dialog, DialogFooter};
4use gpui_kit::component::input::{Input, InputEvent, InputState};
5use gpui_kit::component::radio::Radio;
6use gpui_kit::component::{Disableable as _, WindowExt as _, h_flex, v_flex};
7use gpui_kit::prelude::FluentBuilder as _;
8use gpui_kit::*;
9use store::MemberRecord;
10
11use super::new_chat::{NewChatDraft, Pick};
12use crate::app_state::AppState;
13use crate::i18n::tr;
14use crate::theme;
15
16const DIALOG_WIDTH: f32 = 480.;
17const TITLE: &str = "Add people";
18const FIELD_RADIUS: f32 = 6.;
19const DAYS_FIELD_WIDTH: f32 = 64.;
20const DEFAULT_DAYS: &str = "1";
21const SECTION_GAP: f32 = 12.;
22const OPTION_GAP: f32 = 8.;
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum HistoryChoice {
26 None,
27 Days,
28 All,
29}
30
31/// Teams accepts 1 to 999 days and disables Add for anything else.
32pub fn history_share(choice: HistoryChoice, days_text: &str) -> Option<HistoryShare> {
33 match choice {
34 HistoryChoice::None => Some(HistoryShare::None),
35 HistoryChoice::All => Some(HistoryShare::All),
36 HistoryChoice::Days => {
37 let digits: String = days_text.chars().filter(char::is_ascii_digit).collect();
38 let days: u32 = digits.parse().ok()?;
39 (1..=MAX_HISTORY_DAYS)
40 .contains(&days)
41 .then_some(HistoryShare::Days(days))
42 }
43 }
44}
45
46/// Everyone of the new group chat after adding to a 1:1: the other member first, then the picks.
47pub fn group_chat_people(
48 members: &[MemberRecord],
49 my_user_id: Option<&str>,
50 picks: &[Pick],
51) -> Vec<MemberRecord> {
52 members
53 .iter()
54 .filter(|member| member.user_id.is_some() && member.user_id.as_deref() != my_user_id)
55 .cloned()
56 .chain(picks.iter().map(member_of))
57 .collect()
58}
59
60fn member_of(pick: &Pick) -> MemberRecord {
61 MemberRecord {
62 user_id: Some(pick.user_id.clone()),
63 display_name: pick.name.clone(),
64 }
65}
66
67struct AddPeopleForm {
68 app: Entity<AppState>,
69 chat_id: String,
70 one_on_one: bool,
71 people: Entity<NewChatDraft>,
72 days: Entity<InputState>,
73 choice: HistoryChoice,
74 _subscriptions: Vec<Subscription>,
75}
76
77impl AddPeopleForm {
78 fn new(
79 app: Entity<AppState>,
80 chat_id: String,
81 one_on_one: bool,
82 window: &mut Window,
83 cx: &mut Context<Self>,
84 ) -> Self {
85 let members: Vec<String> = app
86 .read(cx)
87 .sidebar
88 .chats
89 .iter()
90 .find(|chat| chat.id == chat_id)
91 .map(|chat| {
92 chat.members
93 .iter()
94 .filter_map(|member| member.user_id.clone())
95 .collect()
96 })
97 .unwrap_or_default();
98 let people_app = app.clone();
99 let people = cx.new(|cx| {
100 NewChatDraft::new(people_app, window, cx)
101 .compact()
102 .excluding(members)
103 });
104 let days = cx.new(|cx| {
105 let mut input = InputState::new(window, cx);
106 input.set_value(DEFAULT_DAYS, window, cx);
107 input
108 });
109 let subscriptions = vec![
110 cx.observe(&people, |_, _, cx| cx.notify()),
111 cx.subscribe_in(&days, window, |form, _, event: &InputEvent, _, cx| {
112 if matches!(event, InputEvent::Focus) {
113 form.choice = HistoryChoice::Days;
114 }
115 cx.notify();
116 }),
117 ];
118 AddPeopleForm {
119 app,
120 chat_id,
121 one_on_one,
122 people,
123 days,
124 choice: HistoryChoice::None,
125 _subscriptions: subscriptions,
126 }
127 }
128
129 fn share(&self, cx: &App) -> Option<HistoryShare> {
130 history_share(self.choice, &self.days.read(cx).value())
131 }
132
133 fn can_add(&self, cx: &App) -> bool {
134 !self.people.read(cx).chips().is_empty() && (self.one_on_one || self.share(cx).is_some())
135 }
136
137 fn choose(&mut self, choice: HistoryChoice, cx: &mut Context<Self>) {
138 self.choice = choice;
139 cx.notify();
140 }
141
142 fn submit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
143 if !self.can_add(cx) {
144 return;
145 }
146 let picks = self.people.read(cx).chips().to_vec();
147 let chat_id = self.chat_id.clone();
148 if self.one_on_one {
149 self.app.update(cx, |state, cx| {
150 let my_user_id = state.directory.me.as_ref().map(|me| me.user_id.clone());
151 let members = state
152 .sidebar
153 .chats
154 .iter()
155 .find(|chat| chat.id == chat_id)
156 .map(|chat| chat.members.clone())
157 .unwrap_or_default();
158 let people = group_chat_people(&members, my_user_id.as_deref(), &picks);
159 state.start_group_chat_with(people, cx);
160 });
161 } else {
162 let share = self.share(cx).unwrap_or_default();
163 let people = picks.iter().map(member_of).collect();
164 self.app.update(cx, |state, cx| {
165 state.add_chat_members(&chat_id, people, share, cx)
166 });
167 }
168 window.close_dialog(cx);
169 }
170
171 fn history_options(&self, cx: &mut Context<Self>) -> Div {
172 let form = cx.entity();
173 let option = |id: &'static str, label: &'static str, choice: HistoryChoice| {
174 let form = form.clone();
175 Radio::new(id)
176 .label(label)
177 .checked(self.choice == choice)
178 .on_click(move |_, _, cx| form.update(cx, |form, cx| form.choose(choice, cx)))
179 };
180 v_flex()
181 .debug_selector(|| "add-people/history".into())
182 .gap(px(OPTION_GAP))
183 .child(option(
184 "add-people-no-history",
185 "Don't include chat history",
186 HistoryChoice::None,
187 ))
188 .child(
189 h_flex()
190 .gap(px(OPTION_GAP))
191 .items_center()
192 .child(option(
193 "add-people-some-history",
194 "Include history from the past number of days:",
195 HistoryChoice::Days,
196 ))
197 .child(
198 div()
199 .w(px(DAYS_FIELD_WIDTH))
200 .flex_none()
201 .child(Input::new(&self.days)),
202 ),
203 )
204 .child(option(
205 "add-people-all-history",
206 "Include all chat history",
207 HistoryChoice::All,
208 ))
209 }
210}
211
212impl Render for AddPeopleForm {
213 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
214 v_flex()
215 .debug_selector(|| "add-people".into())
216 .gap(px(SECTION_GAP))
217 .child(
218 div()
219 .debug_selector(|| "add-people/people".into())
220 .rounded(px(FIELD_RADIUS))
221 .bg(theme::surface_raised())
222 .child(self.people.clone()),
223 )
224 .when(!self.one_on_one, |column| {
225 column.child(self.history_options(cx))
226 })
227 }
228}
229
230pub fn open_add_people(
231 app: &Entity<AppState>,
232 chat_id: &str,
233 one_on_one: bool,
234 window: &mut Window,
235 cx: &mut App,
236) {
237 let (app, chat_id) = (app.clone(), chat_id.to_owned());
238 let form = cx.new(|cx| AddPeopleForm::new(app, chat_id, one_on_one, window, cx));
239 let people = form.read(cx).people.clone();
240 window.open_dialog(cx, move |dialog: Dialog, _, cx| {
241 let submit_form = form.clone();
242 let can_add = form.read(cx).can_add(cx);
243 let footer = DialogFooter::new()
244 .child(
245 Button::new("add-people-cancel")
246 .label(tr("common.cancel"))
247 .on_click(|_, window, cx| window.close_dialog(cx)),
248 )
249 .child(
250 Button::new("add-people-confirm")
251 .primary()
252 .label(tr("common.add"))
253 .disabled(!can_add)
254 .on_click(move |_, window, cx| {
255 submit_form.update(cx, |form, cx| form.submit(window, cx));
256 }),
257 );
258 dialog
259 .title(TITLE)
260 .w(px(DIALOG_WIDTH))
261 .child(form.clone())
262 .footer(footer)
263 });
264 window.defer(cx, move |window, cx| {
265 people.update(cx, |draft, cx| draft.focus_query(window, cx));
266 });
267}
268
269#[cfg(test)]
270mod tests {
271 use chatsvc::HistoryShare;
272 use store::MemberRecord;
273
274 use super::{HistoryChoice, Pick, group_chat_people, history_share};
275
276 fn member(user_id: &str, name: &str) -> MemberRecord {
277 MemberRecord {
278 user_id: Some(user_id.to_owned()),
279 display_name: name.to_owned(),
280 }
281 }
282
283 #[test]
284 fn history_choice_maps_to_the_share_teams_sends() {
285 assert_eq!(
286 history_share(HistoryChoice::None, "abc"),
287 Some(HistoryShare::None)
288 );
289 assert_eq!(
290 history_share(HistoryChoice::All, ""),
291 Some(HistoryShare::All)
292 );
293 assert_eq!(
294 history_share(HistoryChoice::Days, "14"),
295 Some(HistoryShare::Days(14))
296 );
297 }
298
299 #[test]
300 fn day_counts_outside_one_to_999_disable_adding() {
301 assert_eq!(history_share(HistoryChoice::Days, ""), None);
302 assert_eq!(history_share(HistoryChoice::Days, "0"), None);
303 assert_eq!(history_share(HistoryChoice::Days, "1000"), None);
304 assert_eq!(
305 history_share(HistoryChoice::Days, "999"),
306 Some(HistoryShare::Days(999))
307 );
308 }
309
310 #[test]
311 fn one_on_one_becomes_a_group_with_the_other_member_and_the_picks() {
312 let members = [member("me", "Daniel"), member("ann", "Ann")];
313 let picks = [Pick {
314 user_id: "bob".to_owned(),
315 name: "Bob".to_owned(),
316 mail: None,
317 organization: None,
318 }];
319 let people = group_chat_people(&members, Some("me"), &picks);
320 assert_eq!(people, [member("ann", "Ann"), member("bob", "Bob")]);
321 }
322}