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;
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::row_hover()))
68 .hover(|row| row.bg(theme::row_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 conversation_id == NOTES_CHAT_ID {
79 Some("Not available in your notes")
80 } else if conversation_id.is_empty() {
81 Some("Not available in a new chat yet")
82 } else if self.editing.is_some() {
83 Some("Can't schedule while editing")
84 } else if !outgoing.mentions.is_empty() {
85 Some("Can't schedule messages with mentions yet")
86 } else if outgoing.has_attachments() || self.has_attachments(cx) {
87 Some("Can't schedule messages with images or files yet")
88 } else if self.reply.is_some() {
89 Some("Can't schedule replies yet")
90 } else if self.current_draft(cx).is_blank() {
91 Some("Nothing to schedule yet")
92 } else {
93 None
94 }
95 }
96
97 pub(super) fn open_schedule_menu(&mut self, cx: &mut Context<Self>) {
98 self.schedule = Some(SchedulePopover {
99 stage: Stage::Menu,
100 presets: Vec::new(),
101 highlighted: 0,
102 custom: None,
103 });
104 cx.notify();
105 }
106
107 pub(super) fn open_schedule_picker(&mut self, cx: &mut Context<Self>) {
108 if self.schedule_blocker(cx).is_some() || self.scheduling.is_some() {
109 self.open_schedule_menu(cx);
110 return;
111 }
112 self.schedule = Some(SchedulePopover {
113 stage: Stage::Picker,
114 presets: presets(Local::now()),
115 highlighted: 0,
116 custom: None,
117 });
118 cx.notify();
119 }
120
121 pub(super) fn close_schedule(&mut self, window: &mut Window, cx: &mut Context<Self>) {
122 if self.schedule.take().is_some() {
123 self.focus(window, cx);
124 cx.notify();
125 }
126 }
127
128 pub(super) fn move_schedule_highlight(
129 &mut self,
130 delta: isize,
131 window: &mut Window,
132 cx: &mut Context<Self>,
133 ) {
134 let Some(popover) = self.schedule.as_mut() else {
135 return;
136 };
137 if !matches!(popover.stage, Stage::Picker) {
138 return;
139 }
140 if popover.custom.is_some() {
141 self.step_custom_time(delta, window, cx);
142 return;
143 }
144 let count = popover.presets.len() + 1;
145 popover.highlighted =
146 (popover.highlighted as isize + delta).rem_euclid(count as isize) as usize;
147 cx.notify();
148 }
149
150 pub(super) fn activate_schedule_row(&mut self, window: &mut Window, cx: &mut Context<Self>) {
151 let Some(popover) = self.schedule.as_ref() else {
152 return;
153 };
154 let highlighted = popover.highlighted;
155 let on_custom_row = highlighted == popover.custom_index();
156 let custom_open = popover.custom.is_some();
157 match popover.stage {
158 Stage::Menu => {
159 if self.schedule_blocker(cx).is_none() {
160 self.open_schedule_picker(cx);
161 }
162 }
163 Stage::Picker if custom_open => self.confirm_custom(window, cx),
164 Stage::Picker if on_custom_row => self.expand_custom(window, cx),
165 Stage::Picker => self.schedule_preset(highlighted, window, cx),
166 }
167 }
168
169 fn schedule_preset(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
170 let Some(preset) = self
171 .schedule
172 .as_ref()
173 .and_then(|popover| popover.presets.get(index))
174 else {
175 return;
176 };
177 let at = preset.at;
178 if validate(at, Local::now()).is_err() {
179 if let Some(popover) = self.schedule.as_mut() {
180 popover.presets = presets(Local::now());
181 popover.highlighted = 0;
182 }
183 cx.notify();
184 return;
185 }
186 self.schedule_at(at, window, cx);
187 }
188
189 fn expand_custom(&mut self, window: &mut Window, cx: &mut Context<Self>) {
190 let time = format_time(default_custom_time(Local::now()));
191 let time_field = cx.new(|cx| {
192 InputState::new(window, cx)
193 .placeholder("HH:MM")
194 .default_value(time)
195 });
196 time_field.update(cx, |field, cx| {
197 field.focus(window, cx);
198 field.select_all(window, cx);
199 });
200 let edits = cx.subscribe(&time_field, |_, _, event: &InputEvent, cx| {
201 if matches!(event, InputEvent::Change) {
202 cx.notify();
203 }
204 });
205 if let Some(popover) = self.schedule.as_mut() {
206 popover.custom = Some(CustomForm {
207 day_index: 0,
208 time_field,
209 _edits: edits,
210 });
211 }
212 cx.notify();
213 }
214
215 fn step_custom_time(&mut self, steps: isize, window: &mut Window, cx: &mut Context<Self>) {
216 let Some(field) = self
217 .schedule
218 .as_ref()
219 .and_then(|popover| popover.custom.as_ref())
220 .map(|custom| custom.time_field.clone())
221 else {
222 return;
223 };
224 let current = parse_time(&field.read(cx).value()).unwrap_or_default();
225 let stepped = format_time(step_time(current, -(steps as i32)));
226 field.update(cx, |field, cx| field.set_value(&stepped, window, cx));
227 }
228
229 fn custom_choice(&self, cx: &App) -> Result<DateTime<Local>, &'static str> {
230 let custom = self
231 .schedule
232 .as_ref()
233 .and_then(|popover| popover.custom.as_ref())
234 .ok_or(BAD_TIME)?;
235 let now = Local::now();
236 let day = day_choices(now.date_naive())
237 .get(custom.day_index)
238 .map(|choice| choice.date)
239 .ok_or(BAD_TIME)?;
240 let at = custom_time(day, &custom.time_field.read(cx).value()).ok_or(BAD_TIME)?;
241 validate(at, now).map_err(ScheduleError::message)?;
242 Ok(at)
243 }
244
245 fn confirm_custom(&mut self, window: &mut Window, cx: &mut Context<Self>) {
246 if let Ok(at) = self.custom_choice(cx) {
247 self.schedule_at(at, window, cx);
248 }
249 }
250
251 fn schedule_at(&mut self, at: DateTime<Local>, window: &mut Window, cx: &mut Context<Self>) {
252 if self.scheduling.is_some() || self.schedule_blocker(cx).is_some() {
253 return;
254 }
255 let outgoing = self.compose(cx);
256 self.scheduling = Some(outgoing.html());
257 self.close_schedule(window, cx);
258 cx.emit(ComposerEvent::Schedule {
259 outgoing: Box::new(outgoing),
260 send_at: at.with_timezone(&Utc),
261 });
262 }
263
264 pub fn finish_schedule(
265 &mut self,
266 conversation_id: &str,
267 window: &mut Window,
268 cx: &mut Context<Self>,
269 ) {
270 let scheduled = self.scheduling.take();
271 if self.conversation_id.as_deref() != Some(conversation_id) {
272 self.app.read(cx).store.delete_draft(conversation_id).ok();
273 self.app
274 .update(cx, |state, cx| state.refresh_local_previews(cx));
275 return;
276 }
277 if scheduled.as_deref() != Some(self.compose(cx).html().as_str()) {
278 return;
279 }
280 self.load_draft(
281 teams_core::Draft::default(),
282 gpui_kit::component::input::InputContent::new(""),
283 window,
284 cx,
285 );
286 self.mention_inputs.clear();
287 self.tray.clear();
288 self.clear_stored_draft(cx);
289 self.reply = None;
290 self.close_popup();
291 cx.notify();
292 }
293
294 pub fn fail_schedule(&mut self, cx: &mut Context<Self>) {
295 self.scheduling = None;
296 cx.notify();
297 }
298
299 pub(super) fn render_schedule(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
300 let popover = self.schedule.as_ref()?;
301 let body = match popover.stage {
302 Stage::Menu => self.render_schedule_menu(cx),
303 Stage::Picker => self.render_schedule_picker(popover, cx),
304 };
305 Some(
306 v_flex()
307 .id("schedule-popover")
308 .absolute()
309 .bottom(relative(1.))
310 .right_0()
311 .mb(px(6.))
312 .w(px(match popover.stage {
313 Stage::Menu => MENU_WIDTH,
314 Stage::Picker => PICKER_WIDTH,
315 }))
316 .p(px(4.))
317 .rounded(px(8.))
318 .border_1()
319 .border_color(theme::border_strong())
320 .bg(theme::surface_raised())
321 .shadow_lg()
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(6.))
376 .my(px(4.))
377 .bg(theme::border_strong()),
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 .border_1()
407 .border_color(if selected {
408 theme::accent()
409 } else {
410 theme::border_strong()
411 })
412 .text_size(px(12.))
413 .cursor_pointer()
414 .when(selected, |chip| {
415 chip.bg(theme::accent()).text_color(theme::on_accent())
416 })
417 .when(!selected, |chip| {
418 chip.text_color(theme::text_soft())
419 .hover(|chip| chip.bg(theme::row_hover()))
420 })
421 .child(day.label)
422 .on_click(cx.listener(move |this, _, _, cx| {
423 if let Some(form) = this
424 .schedule
425 .as_mut()
426 .and_then(|popover| popover.custom.as_mut())
427 {
428 form.day_index = index;
429 }
430 cx.notify();
431 }))
432 });
433 let valid = choice.is_ok();
434 v_flex()
435 .gap(px(8.))
436 .p(px(10.))
437 .child(h_flex().flex_wrap().gap(px(6.)).children(chips))
438 .child(
439 h_flex()
440 .gap(px(10.))
441 .items_center()
442 .child(
443 div()
444 .w(px(TIME_FIELD_WIDTH))
445 .h(px(28.))
446 .rounded(px(6.))
447 .border_1()
448 .border_color(theme::accent())
449 .bg(theme::surface())
450 .child(
451 Input::new(&custom.time_field)
452 .appearance(false)
453 .bordered(false),
454 ),
455 )
456 .child(div().flex_1())
457 .child(
458 div()
459 .id("schedule-confirm")
460 .h(px(30.))
461 .px(px(14.))
462 .flex()
463 .items_center()
464 .rounded(px(6.))
465 .bg(theme::accent())
466 .text_color(theme::on_accent())
467 .text_size(px(13.))
468 .font_weight(FontWeight::SEMIBOLD)
469 .child("Schedule")
470 .when(!valid, |button| button.opacity(DISABLED_OPACITY))
471 .when(valid, |button| {
472 button.cursor_pointer().on_click(cx.listener(
473 |this, _, window, cx| this.confirm_custom(window, cx),
474 ))
475 }),
476 ),
477 )
478 .children(choice.err().map(|message| {
479 div()
480 .text_size(px(12.))
481 .text_color(theme::red_soft())
482 .child(message)
483 }))
484 }
485}