BlueGit

ict rusty-teams

Files

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

schedule.rs

schedule.rs 16.7 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 self.importance = store::MessageImportance::Normal;
259 let outgoing = self.compose(cx);
260 self.scheduling = Some(outgoing.html());
261 self.close_schedule(window, cx);
262 cx.emit(ComposerEvent::Schedule {
263 outgoing: Box::new(outgoing),
264 send_at: at.with_timezone(&Utc),
265 });
266 }
267
268 pub fn finish_schedule(
269 &mut self,
270 conversation_id: &str,
271 window: &mut Window,
272 cx: &mut Context<Self>,
273 ) {
274 let scheduled = self.scheduling.take();
275 if self.conversation_id.as_deref() != Some(conversation_id) {
276 self.app.read(cx).store.delete_draft(conversation_id).ok();
277 self.app
278 .update(cx, |state, cx| state.refresh_local_previews(cx));
279 return;
280 }
281 if scheduled.as_deref() != Some(self.compose(cx).html().as_str()) {
282 return;
283 }
284 self.load_draft(
285 teams_core::Draft::default(),
286 gpui_kit::component::input::InputContent::new(""),
287 window,
288 cx,
289 );
290 self.mention_inputs.clear();
291 self.tray.clear();
292 self.clear_stored_draft(cx);
293 self.reply = None;
294 self.close_popup();
295 cx.notify();
296 }
297
298 pub fn fail_schedule(&mut self, cx: &mut Context<Self>) {
299 self.scheduling = None;
300 cx.notify();
301 }
302
303 pub(super) fn render_schedule(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
304 let popover = self.schedule.as_ref()?;
305 let body = match popover.stage {
306 Stage::Menu => self.render_schedule_menu(cx),
307 Stage::Picker => self.render_schedule_picker(popover, cx),
308 };
309 Some(
310 v_flex()
311 .id("schedule-popover")
312 .absolute()
313 .bottom(relative(1.))
314 .right_0()
315 .mb(px(6.))
316 .w(px(match popover.stage {
317 Stage::Menu => MENU_WIDTH,
318 Stage::Picker => PICKER_WIDTH,
319 }))
320 .p(px(4.))
321 .rounded(px(10.))
322 .flyout_surface()
323 .occlude()
324 .on_mouse_down_out(
325 cx.listener(|this, _, window, cx| this.close_schedule(window, cx)),
326 )
327 .child(body)
328 .into_any_element(),
329 )
330 }
331
332 fn render_schedule_menu(&self, cx: &mut Context<Self>) -> Div {
333 let blocker = self.schedule_blocker(cx);
334 let row = menu_row("schedule-send-entry".into(), true)
335 .child(symbol("schedule_send", ICON_SIZE, theme::text_soft()))
336 .child("Schedule send");
337 let row = match blocker {
338 Some(reason) => row
339 .opacity(DISABLED_OPACITY)
340 .cursor_default()
341 .tooltip(move |window, cx| Tooltip::new(reason).build(window, cx)),
342 None => row.on_click(cx.listener(|this, _, _, cx| this.open_schedule_picker(cx))),
343 };
344 v_flex().child(row)
345 }
346
347 fn render_schedule_picker(&self, popover: &SchedulePopover, cx: &mut Context<Self>) -> Div {
348 let mut list = v_flex();
349 for (index, preset) in popover.presets.iter().enumerate() {
350 list = list.child(
351 menu_row(
352 ElementId::Name(format!("schedule-preset-{index}").into()),
353 index == popover.highlighted && popover.custom.is_none(),
354 )
355 .child(symbol(
356 preset_glyph(preset.kind),
357 ICON_SIZE,
358 theme::text_soft(),
359 ))
360 .child(div().flex_1().child(preset.label))
361 .child(
362 div()
363 .text_size(px(12.))
364 .text_color(theme::text_faint())
365 .child(preset.time_label.clone()),
366 )
367 .on_click(
368 cx.listener(move |this, _, window, cx| this.schedule_preset(index, window, cx)),
369 ),
370 );
371 }
372 list = list
373 .child(
374 div()
375 .h(px(1.))
376 .mx(px(-4.))
377 .my(px(4.))
378 .bg(theme::popup_hover()),
379 )
380 .child(
381 menu_row(
382 "schedule-custom".into(),
383 popover.highlighted == popover.custom_index() && popover.custom.is_none(),
384 )
385 .child(symbol("event", ICON_SIZE, theme::text_soft()))
386 .child("Custom...")
387 .on_click(cx.listener(|this, _, window, cx| this.expand_custom(window, cx))),
388 );
389 if let Some(custom) = popover.custom.as_ref() {
390 list = list.child(self.render_custom_form(custom, cx));
391 }
392 list
393 }
394
395 fn render_custom_form(&self, custom: &CustomForm, cx: &mut Context<Self>) -> Div {
396 let choice = self.custom_choice(cx);
397 let days: Vec<DayChoice> = day_choices(Local::now().date_naive());
398 let chips = days.into_iter().enumerate().map(|(index, day)| {
399 let selected = index == custom.day_index;
400 div()
401 .id(ElementId::Name(format!("schedule-day-{index}").into()))
402 .h(px(26.))
403 .px(px(8.))
404 .flex()
405 .items_center()
406 .rounded(px(6.))
407 .text_size(px(12.))
408 .cursor_pointer()
409 .when(selected, |chip| {
410 chip.bg(theme::accent()).text_color(theme::on_accent())
411 })
412 .when(!selected, |chip| {
413 chip.bg(theme::popup_hover())
414 .text_color(theme::text_soft())
415 .hover(|chip| chip.bg(theme::border_strong()))
416 })
417 .child(day.label)
418 .on_click(cx.listener(move |this, _, _, cx| {
419 if let Some(form) = this
420 .schedule
421 .as_mut()
422 .and_then(|popover| popover.custom.as_mut())
423 {
424 form.day_index = index;
425 }
426 cx.notify();
427 }))
428 });
429 let valid = choice.is_ok();
430 v_flex()
431 .gap(px(8.))
432 .p(px(10.))
433 .child(h_flex().flex_wrap().gap(px(6.)).children(chips))
434 .child(
435 h_flex()
436 .gap(px(10.))
437 .items_center()
438 .child(
439 div()
440 .w(px(TIME_FIELD_WIDTH))
441 .h(px(28.))
442 .rounded(px(6.))
443 .border_1()
444 .border_color(theme::accent())
445 .bg(theme::popup_hover())
446 .child(
447 Input::new(&custom.time_field)
448 .appearance(false)
449 .bordered(false),
450 ),
451 )
452 .child(div().flex_1())
453 .child(
454 div()
455 .id("schedule-confirm")
456 .h(px(30.))
457 .px(px(14.))
458 .flex()
459 .items_center()
460 .rounded(px(6.))
461 .bg(theme::accent())
462 .text_color(theme::on_accent())
463 .text_size(px(13.))
464 .font_weight(FontWeight::SEMIBOLD)
465 .child("Schedule")
466 .when(!valid, |button| button.opacity(DISABLED_OPACITY))
467 .when(valid, |button| {
468 button.cursor_pointer().on_click(cx.listener(
469 |this, _, window, cx| this.confirm_custom(window, cx),
470 ))
471 }),
472 ),
473 )
474 .children(choice.err().map(|message| {
475 div()
476 .text_size(px(12.))
477 .text_color(theme::red_soft())
478 .child(message)
479 }))
480 }
481}