BlueGit

ict rusty-teams

Files

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

schedule.rs

schedule.rs 16.6 KiB Download Raw
1use chrono::{DateTime, Local, Utc};
2use gpui_kit::component::input::{Input, InputEvent, InputState};
3use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
4use gpui_kit::prelude::FluentBuilder as _;
5use gpui_kit::*;
6use teams_core::NOTES_CHAT_ID;
7
8use super::{Composer, ComposerEvent};
9use crate::schedule_time::{
10 DayChoice, Preset, PresetKind, ScheduleError, custom_time, day_choices, default_custom_time,
11 format_time, parse_time, presets, step_time, validate,
12};
13use crate::theme::{self, ElevatedSurface as _};
14use crate::views::widgets::symbol;
15
16const MENU_WIDTH: f32 = 190.;
17const PICKER_WIDTH: f32 = 300.;
18const ROW_HEIGHT: f32 = 32.;
19const ICON_SIZE: f32 = 18.;
20const DISABLED_OPACITY: f32 = 0.4;
21const TIME_FIELD_WIDTH: f32 = 84.;
22const BAD_TIME: &str = "Enter a time like 14:30.";
23
24pub(super) enum Stage {
25 Menu,
26 Picker,
27}
28
29pub(super) struct CustomForm {
30 day_index: usize,
31 time_field: Entity<InputState>,
32 _edits: Subscription,
33}
34
35pub(super) struct SchedulePopover {
36 stage: Stage,
37 presets: Vec<Preset>,
38 highlighted: usize,
39 custom: Option<CustomForm>,
40}
41
42impl SchedulePopover {
43 fn custom_index(&self) -> usize {
44 self.presets.len()
45 }
46}
47
48fn preset_glyph(kind: PresetKind) -> &'static str {
49 match kind {
50 PresetKind::LaterToday => "schedule",
51 PresetKind::TomorrowMorning => "wb_sunny",
52 PresetKind::MondayMorning => "work",
53 }
54}
55
56fn menu_row(id: ElementId, highlighted: bool) -> Stateful<Div> {
57 h_flex()
58 .id(id)
59 .h(px(ROW_HEIGHT))
60 .flex_none()
61 .px(px(10.))
62 .gap(px(10.))
63 .items_center()
64 .rounded(px(6.))
65 .text_size(px(13.))
66 .text_color(theme::text())
67 .cursor_pointer()
68 .when(highlighted, |row| row.bg(theme::popup_hover()))
69 .hover(|row| row.bg(theme::popup_hover()))
70}
71
72impl Composer {
73 pub(super) fn schedule_blocker(&self, cx: &App) -> Option<&'static str> {
74 let state = self.app.read(cx);
75 let conversation_id = self.conversation_id.as_deref().unwrap_or_default();
76 let outgoing = self.compose(cx);
77 if state.mode.read_only && !state.mode.demo {
78 Some("Read-only mode")
79 } else if self.inline {
80 Some("Open the conversation to schedule a reply")
81 } else if conversation_id == NOTES_CHAT_ID {
82 Some("Not available in your notes")
83 } else if conversation_id.is_empty() {
84 Some("Not available in a new chat yet")
85 } else if self.editing.is_some() {
86 Some("Can't schedule while editing")
87 } else if !outgoing.mentions.is_empty() {
88 Some("Can't schedule messages with mentions yet")
89 } else if outgoing.has_attachments() || self.has_attachments(cx) {
90 Some("Can't schedule messages with images or files yet")
91 } else if self.reply.is_some() {
92 Some("Can't schedule replies yet")
93 } else if self.current_draft(cx).is_blank() {
94 Some("Nothing to schedule yet")
95 } else {
96 None
97 }
98 }
99
100 pub(super) fn open_schedule_menu(&mut self, cx: &mut Context<Self>) {
101 self.schedule = Some(SchedulePopover {
102 stage: Stage::Menu,
103 presets: Vec::new(),
104 highlighted: 0,
105 custom: None,
106 });
107 cx.notify();
108 }
109
110 pub(super) fn open_schedule_picker(&mut self, cx: &mut Context<Self>) {
111 if self.schedule_blocker(cx).is_some() || self.scheduling.is_some() {
112 self.open_schedule_menu(cx);
113 return;
114 }
115 self.schedule = Some(SchedulePopover {
116 stage: Stage::Picker,
117 presets: presets(Local::now()),
118 highlighted: 0,
119 custom: None,
120 });
121 cx.notify();
122 }
123
124 pub(super) fn close_schedule(&mut self, window: &mut Window, cx: &mut Context<Self>) {
125 if self.schedule.take().is_some() {
126 self.focus(window, cx);
127 cx.notify();
128 }
129 }
130
131 pub(super) fn move_schedule_highlight(
132 &mut self,
133 delta: isize,
134 window: &mut Window,
135 cx: &mut Context<Self>,
136 ) {
137 let Some(popover) = self.schedule.as_mut() else {
138 return;
139 };
140 if !matches!(popover.stage, Stage::Picker) {
141 return;
142 }
143 if popover.custom.is_some() {
144 self.step_custom_time(delta, window, cx);
145 return;
146 }
147 let count = popover.presets.len() + 1;
148 popover.highlighted =
149 (popover.highlighted as isize + delta).rem_euclid(count as isize) as usize;
150 cx.notify();
151 }
152
153 pub(super) fn activate_schedule_row(&mut self, window: &mut Window, cx: &mut Context<Self>) {
154 let Some(popover) = self.schedule.as_ref() else {
155 return;
156 };
157 let highlighted = popover.highlighted;
158 let on_custom_row = highlighted == popover.custom_index();
159 let custom_open = popover.custom.is_some();
160 match popover.stage {
161 Stage::Menu => {
162 if self.schedule_blocker(cx).is_none() {
163 self.open_schedule_picker(cx);
164 }
165 }
166 Stage::Picker if custom_open => self.confirm_custom(window, cx),
167 Stage::Picker if on_custom_row => self.expand_custom(window, cx),
168 Stage::Picker => self.schedule_preset(highlighted, window, cx),
169 }
170 }
171
172 fn schedule_preset(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
173 let Some(preset) = self
174 .schedule
175 .as_ref()
176 .and_then(|popover| popover.presets.get(index))
177 else {
178 return;
179 };
180 let at = preset.at;
181 if validate(at, Local::now()).is_err() {
182 if let Some(popover) = self.schedule.as_mut() {
183 popover.presets = presets(Local::now());
184 popover.highlighted = 0;
185 }
186 cx.notify();
187 return;
188 }
189 self.schedule_at(at, window, cx);
190 }
191
192 fn expand_custom(&mut self, window: &mut Window, cx: &mut Context<Self>) {
193 let time = format_time(default_custom_time(Local::now()));
194 let time_field = cx.new(|cx| {
195 InputState::new(window, cx)
196 .placeholder("HH:MM")
197 .default_value(time)
198 });
199 time_field.update(cx, |field, cx| {
200 field.focus(window, cx);
201 field.select_all(window, cx);
202 });
203 let edits = cx.subscribe(&time_field, |_, _, event: &InputEvent, cx| {
204 if matches!(event, InputEvent::Change) {
205 cx.notify();
206 }
207 });
208 if let Some(popover) = self.schedule.as_mut() {
209 popover.custom = Some(CustomForm {
210 day_index: 0,
211 time_field,
212 _edits: edits,
213 });
214 }
215 cx.notify();
216 }
217
218 fn step_custom_time(&mut self, steps: isize, window: &mut Window, cx: &mut Context<Self>) {
219 let Some(field) = self
220 .schedule
221 .as_ref()
222 .and_then(|popover| popover.custom.as_ref())
223 .map(|custom| custom.time_field.clone())
224 else {
225 return;
226 };
227 let current = parse_time(&field.read(cx).value()).unwrap_or_default();
228 let stepped = format_time(step_time(current, -(steps as i32)));
229 field.update(cx, |field, cx| field.set_value(&stepped, window, cx));
230 }
231
232 fn custom_choice(&self, cx: &App) -> Result<DateTime<Local>, &'static str> {
233 let custom = self
234 .schedule
235 .as_ref()
236 .and_then(|popover| popover.custom.as_ref())
237 .ok_or(BAD_TIME)?;
238 let now = Local::now();
239 let day = day_choices(now.date_naive())
240 .get(custom.day_index)
241 .map(|choice| choice.date)
242 .ok_or(BAD_TIME)?;
243 let at = custom_time(day, &custom.time_field.read(cx).value()).ok_or(BAD_TIME)?;
244 validate(at, now).map_err(ScheduleError::message)?;
245 Ok(at)
246 }
247
248 fn confirm_custom(&mut self, window: &mut Window, cx: &mut Context<Self>) {
249 if let Ok(at) = self.custom_choice(cx) {
250 self.schedule_at(at, window, cx);
251 }
252 }
253
254 fn schedule_at(&mut self, at: DateTime<Local>, window: &mut Window, cx: &mut Context<Self>) {
255 if self.scheduling.is_some() || self.schedule_blocker(cx).is_some() {
256 return;
257 }
258 let outgoing = self.compose(cx);
259 self.scheduling = Some(outgoing.html());
260 self.close_schedule(window, cx);
261 cx.emit(ComposerEvent::Schedule {
262 outgoing: Box::new(outgoing),
263 send_at: at.with_timezone(&Utc),
264 });
265 }
266
267 pub fn finish_schedule(
268 &mut self,
269 conversation_id: &str,
270 window: &mut Window,
271 cx: &mut Context<Self>,
272 ) {
273 let scheduled = self.scheduling.take();
274 if self.conversation_id.as_deref() != Some(conversation_id) {
275 self.app.read(cx).store.delete_draft(conversation_id).ok();
276 self.app
277 .update(cx, |state, cx| state.refresh_local_previews(cx));
278 return;
279 }
280 if scheduled.as_deref() != Some(self.compose(cx).html().as_str()) {
281 return;
282 }
283 self.load_draft(
284 teams_core::Draft::default(),
285 gpui_kit::component::input::InputContent::new(""),
286 window,
287 cx,
288 );
289 self.mention_inputs.clear();
290 self.tray.clear();
291 self.clear_stored_draft(cx);
292 self.reply = None;
293 self.close_popup();
294 cx.notify();
295 }
296
297 pub fn fail_schedule(&mut self, cx: &mut Context<Self>) {
298 self.scheduling = None;
299 cx.notify();
300 }
301
302 pub(super) fn render_schedule(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
303 let popover = self.schedule.as_ref()?;
304 let body = match popover.stage {
305 Stage::Menu => self.render_schedule_menu(cx),
306 Stage::Picker => self.render_schedule_picker(popover, cx),
307 };
308 Some(
309 v_flex()
310 .id("schedule-popover")
311 .absolute()
312 .bottom(relative(1.))
313 .right_0()
314 .mb(px(6.))
315 .w(px(match popover.stage {
316 Stage::Menu => MENU_WIDTH,
317 Stage::Picker => PICKER_WIDTH,
318 }))
319 .p(px(4.))
320 .rounded(px(10.))
321 .flyout_surface()
322 .occlude()
323 .on_mouse_down_out(
324 cx.listener(|this, _, window, cx| this.close_schedule(window, cx)),
325 )
326 .child(body)
327 .into_any_element(),
328 )
329 }
330
331 fn render_schedule_menu(&self, cx: &mut Context<Self>) -> Div {
332 let blocker = self.schedule_blocker(cx);
333 let row = menu_row("schedule-send-entry".into(), true)
334 .child(symbol("schedule_send", ICON_SIZE, theme::text_soft()))
335 .child("Schedule send");
336 let row = match blocker {
337 Some(reason) => row
338 .opacity(DISABLED_OPACITY)
339 .cursor_default()
340 .tooltip(move |window, cx| Tooltip::new(reason).build(window, cx)),
341 None => row.on_click(cx.listener(|this, _, _, cx| this.open_schedule_picker(cx))),
342 };
343 v_flex().child(row)
344 }
345
346 fn render_schedule_picker(&self, popover: &SchedulePopover, cx: &mut Context<Self>) -> Div {
347 let mut list = v_flex();
348 for (index, preset) in popover.presets.iter().enumerate() {
349 list = list.child(
350 menu_row(
351 ElementId::Name(format!("schedule-preset-{index}").into()),
352 index == popover.highlighted && popover.custom.is_none(),
353 )
354 .child(symbol(
355 preset_glyph(preset.kind),
356 ICON_SIZE,
357 theme::text_soft(),
358 ))
359 .child(div().flex_1().child(preset.label))
360 .child(
361 div()
362 .text_size(px(12.))
363 .text_color(theme::text_faint())
364 .child(preset.time_label.clone()),
365 )
366 .on_click(
367 cx.listener(move |this, _, window, cx| this.schedule_preset(index, window, cx)),
368 ),
369 );
370 }
371 list = list
372 .child(
373 div()
374 .h(px(1.))
375 .mx(px(-4.))
376 .my(px(4.))
377 .bg(theme::popup_hover()),
378 )
379 .child(
380 menu_row(
381 "schedule-custom".into(),
382 popover.highlighted == popover.custom_index() && popover.custom.is_none(),
383 )
384 .child(symbol("event", ICON_SIZE, theme::text_soft()))
385 .child("Custom...")
386 .on_click(cx.listener(|this, _, window, cx| this.expand_custom(window, cx))),
387 );
388 if let Some(custom) = popover.custom.as_ref() {
389 list = list.child(self.render_custom_form(custom, cx));
390 }
391 list
392 }
393
394 fn render_custom_form(&self, custom: &CustomForm, cx: &mut Context<Self>) -> Div {
395 let choice = self.custom_choice(cx);
396 let days: Vec<DayChoice> = day_choices(Local::now().date_naive());
397 let chips = days.into_iter().enumerate().map(|(index, day)| {
398 let selected = index == custom.day_index;
399 div()
400 .id(ElementId::Name(format!("schedule-day-{index}").into()))
401 .h(px(26.))
402 .px(px(8.))
403 .flex()
404 .items_center()
405 .rounded(px(6.))
406 .text_size(px(12.))
407 .cursor_pointer()
408 .when(selected, |chip| {
409 chip.bg(theme::accent()).text_color(theme::on_accent())
410 })
411 .when(!selected, |chip| {
412 chip.bg(theme::popup_hover())
413 .text_color(theme::text_soft())
414 .hover(|chip| chip.bg(theme::border_strong()))
415 })
416 .child(day.label)
417 .on_click(cx.listener(move |this, _, _, cx| {
418 if let Some(form) = this
419 .schedule
420 .as_mut()
421 .and_then(|popover| popover.custom.as_mut())
422 {
423 form.day_index = index;
424 }
425 cx.notify();
426 }))
427 });
428 let valid = choice.is_ok();
429 v_flex()
430 .gap(px(8.))
431 .p(px(10.))
432 .child(h_flex().flex_wrap().gap(px(6.)).children(chips))
433 .child(
434 h_flex()
435 .gap(px(10.))
436 .items_center()
437 .child(
438 div()
439 .w(px(TIME_FIELD_WIDTH))
440 .h(px(28.))
441 .rounded(px(6.))
442 .border_1()
443 .border_color(theme::accent())
444 .bg(theme::popup_hover())
445 .child(
446 Input::new(&custom.time_field)
447 .appearance(false)
448 .bordered(false),
449 ),
450 )
451 .child(div().flex_1())
452 .child(
453 div()
454 .id("schedule-confirm")
455 .h(px(30.))
456 .px(px(14.))
457 .flex()
458 .items_center()
459 .rounded(px(6.))
460 .bg(theme::accent())
461 .text_color(theme::on_accent())
462 .text_size(px(13.))
463 .font_weight(FontWeight::SEMIBOLD)
464 .child("Schedule")
465 .when(!valid, |button| button.opacity(DISABLED_OPACITY))
466 .when(valid, |button| {
467 button.cursor_pointer().on_click(cx.listener(
468 |this, _, window, cx| this.confirm_custom(window, cx),
469 ))
470 }),
471 ),
472 )
473 .children(choice.err().map(|message| {
474 div()
475 .text_size(px(12.))
476 .text_color(theme::red_soft())
477 .child(message)
478 }))
479 }
480}