BlueGit

ict rusty-teams

Files

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

schedule.rs

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