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