BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / kvt / tasks.rs

tasks.rs

tasks.rs 22.5 KiB Download Raw
1//! Ponos: «Taak maken van bericht» (dialoog) en het paneel «Mijn taken».
2//!
3//! Upstream-haak voor het paneel: `views/status_menu.rs` (instellingenmenu).
4
5use gpui_kit::assets::IconName;
6use gpui_kit::component::input::{Input, InputState, Textarea, TextareaState};
7use gpui_kit::component::menu::{PopupMenu, PopupMenuItem};
8use gpui_kit::component::scroll::ScrollableElement as _;
9use gpui_kit::component::{h_flex, v_flex};
10use gpui_kit::prelude::FluentBuilder as _;
11use gpui_kit::*;
12use kvt_sleutels::ClientError;
13use kvt_sleutels::asclepius::{DESCRIPTION_MAX, MessageSource};
14use kvt_sleutels::format::iso_date_nl;
15use kvt_sleutels::ponos::{PonosGroup, PonosTask};
16
17use super::modal::{primary_button, secondary_button};
18use super::{
19 Link, base_url, connect, error_text, forget_token, installed, is_demo, link, notice,
20 open_external, read, token_and_client, update,
21};
22use crate::app_state::AppHandle;
23use crate::i18n::tr;
24use crate::runtime;
25use crate::theme::{self, ElevatedSurface as _};
26use crate::views::widgets::symbol;
27
28pub const KVT_PONOS_DIALOG_TAG: &str = "kvt-ponos-dialog";
29pub const KVT_TASKS_PANEL_TAG: &str = "kvt-tasks-panel";
30/// Laatst gekozen Ponos-groep (alleen een id, in de lokale opslag).
31const GROUP_META_KEY: &str = "kvt.ponos.group";
32/// Ponos staat 200 tekens toe in de titel.
33const TITLE_MAX: usize = 200;
34const BACKDROP_OPACITY: f32 = 0.55;
35const PANEL_WIDTH: f32 = 520.;
36const PANEL_MARGIN: f32 = 32.;
37const PANEL_RADIUS: f32 = 10.;
38const PANEL_PADDING: f32 = 16.;
39const SECTION_GAP: f32 = 12.;
40const CLOSE_SIZE: f32 = 28.;
41const CHIP_HEIGHT: f32 = 28.;
42const FIELD_HEIGHT: f32 = 36.;
43const ROW_HEIGHT: f32 = 48.;
44const LIST_MAX_HEIGHT: f32 = 420.;
45
46#[derive(Clone)]
47pub(crate) enum TasksLoad {
48 Loading,
49 Loaded(Vec<PonosTask>),
50 Failed(ClientError),
51}
52
53#[derive(Clone)]
54enum Groups {
55 Loading,
56 Loaded(Vec<PonosGroup>),
57 Failed(ClientError),
58}
59
60pub struct PonosDialog {
61 source: MessageSource,
62 groups: Groups,
63 group: Option<String>,
64 title: Entity<InputState>,
65 description: Entity<TextareaState>,
66 saving: bool,
67 error: Option<String>,
68}
69
70fn remembered_group(cx: &App) -> Option<String> {
71 let handle = cx.try_global::<AppHandle>()?;
72 handle.0.read(cx).store.meta(GROUP_META_KEY).ok().flatten()
73}
74
75fn remember_group(group: &str, cx: &App) {
76 if let Some(handle) = cx.try_global::<AppHandle>() {
77 let _ = handle.0.read(cx).store.set_meta(GROUP_META_KEY, group);
78 }
79}
80
81pub(super) fn open_create(source: MessageSource, window: &mut Window, cx: &mut App) {
82 if !installed(cx) {
83 return;
84 }
85 let dialog = cx.new(|cx| PonosDialog::new(source, window, cx));
86 update(cx, |kvt| kvt.ponos_dialog = Some(dialog.clone()));
87 if is_demo(cx) {
88 dialog.update(cx, |dialog, cx| {
89 dialog.set_groups(Ok(super::demo::ponos_groups()), cx)
90 });
91 return;
92 }
93 let Some((token, client)) = token_and_client(cx) else {
94 return;
95 };
96 let loading = runtime::spawn(async move { client.ponos_groups(&token).await });
97 let weak = dialog.downgrade();
98 cx.spawn(async move |cx| {
99 let result = loading.await.unwrap_or(Err(ClientError::Unavailable));
100 cx.update(|cx| {
101 if result == Err(ClientError::Unauthorized) {
102 forget_token(cx);
103 }
104 weak.update(cx, |dialog, cx| dialog.set_groups(result, cx))
105 .ok();
106 });
107 })
108 .detach();
109}
110
111fn close_create(cx: &mut App) {
112 update(cx, |kvt| kvt.ponos_dialog = None);
113}
114
115impl PonosDialog {
116 fn new(source: MessageSource, window: &mut Window, cx: &mut Context<Self>) -> Self {
117 let title_text = source.title(TITLE_MAX);
118 let description_text = source.description(DESCRIPTION_MAX);
119 let title = cx.new(|cx| {
120 InputState::new(window, cx)
121 .placeholder(tr("kvt.ponos.title"))
122 .default_value(title_text)
123 });
124 let description = cx.new(|cx| {
125 TextareaState::new(window, cx)
126 .auto_grow(4, 10)
127 .placeholder(tr("kvt.ponos.description"))
128 .default_value(description_text)
129 });
130 title.update(cx, |input, cx| input.focus(window, cx));
131 PonosDialog {
132 source,
133 groups: Groups::Loading,
134 group: remembered_group(cx),
135 title,
136 description,
137 saving: false,
138 error: None,
139 }
140 }
141
142 fn set_groups(&mut self, result: Result<Vec<PonosGroup>, ClientError>, cx: &mut Context<Self>) {
143 self.groups = match result {
144 Ok(groups) => {
145 let known = self
146 .group
147 .as_ref()
148 .is_some_and(|chosen| groups.iter().any(|group| &group.id == chosen));
149 if !known {
150 self.group = (groups.len() == 1).then(|| groups[0].id.clone());
151 }
152 Groups::Loaded(groups)
153 }
154 Err(error) => Groups::Failed(error),
155 };
156 cx.notify();
157 }
158
159 fn save(&mut self, cx: &mut Context<Self>) {
160 if self.saving {
161 return;
162 }
163 let title = self.title.read(cx).value().trim().to_owned();
164 let description = self.description.read(cx).value().trim().to_owned();
165 let Some(group) = self.group.clone() else {
166 self.error = Some(tr("kvt.ponos.pick_group"));
167 cx.notify();
168 return;
169 };
170 if title.is_empty() || description.is_empty() {
171 self.error = Some(tr("kvt.ponos.fill_in"));
172 cx.notify();
173 return;
174 }
175 remember_group(&group, cx);
176 if is_demo(cx) {
177 close_create(cx);
178 notice(tr("kvt.ponos.created"), cx);
179 return;
180 }
181 let Some((token, client)) = token_and_client(cx) else {
182 return;
183 };
184 self.saving = true;
185 self.error = None;
186 cx.notify();
187 let creating = runtime::spawn(async move {
188 client
189 .ponos_create_task(&token, &group, &title, &description)
190 .await
191 });
192 cx.spawn(async move |this, cx| {
193 let result = creating.await.unwrap_or(Err(ClientError::Unavailable));
194 cx.update(|cx| match result {
195 Ok(_) => {
196 close_create(cx);
197 notice(tr("kvt.ponos.created"), cx);
198 refresh_tasks_if_open(cx);
199 }
200 Err(error) => {
201 if error == ClientError::Unauthorized {
202 forget_token(cx);
203 }
204 this.update(cx, |this, cx| {
205 this.saving = false;
206 this.error = Some(ponos_error(&error));
207 cx.notify();
208 })
209 .ok();
210 }
211 });
212 })
213 .detach();
214 }
215
216 fn groups(&self, cx: &mut Context<Self>) -> AnyElement {
217 if !matches!(link(cx), Link::Linked(_)) {
218 return not_linked().into_any_element();
219 }
220 match &self.groups {
221 Groups::Loading => muted(tr("kvt.card.loading")).into_any_element(),
222 Groups::Failed(error) => muted(ponos_error(error)).into_any_element(),
223 Groups::Loaded(groups) if groups.is_empty() => {
224 muted(tr("kvt.ponos.no_groups")).into_any_element()
225 }
226 Groups::Loaded(groups) => h_flex()
227 .w_full()
228 .flex_wrap()
229 .gap(px(6.))
230 .children(groups.iter().enumerate().map(|(index, group)| {
231 let id = group.id.clone();
232 chip(
233 format!("kvt-ponos-group-{index}").into(),
234 group.name.clone(),
235 self.group.as_deref() == Some(group.id.as_str()),
236 )
237 .on_click(cx.listener(move |this, _, _, cx| {
238 this.group = Some(id.clone());
239 this.error = None;
240 cx.notify();
241 }))
242 }))
243 .into_any_element(),
244 }
245 }
246}
247
248impl Render for PonosDialog {
249 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
250 let ready = matches!(self.groups, Groups::Loaded(ref groups) if !groups.is_empty());
251 let from = if self.source.sender.is_empty() {
252 String::new()
253 } else {
254 format!("{} · {}", self.source.sender, self.source.sent_at)
255 };
256 layer("kvt-ponos", |cx| close_create(cx)).child(
257 panel(KVT_PONOS_DIALOG_TAG)
258 .child(header(tr("kvt.ponos.dialog_title"), from, |cx| {
259 close_create(cx)
260 }))
261 .child(label(tr("kvt.ponos.group")))
262 .child(self.groups(cx))
263 .child(label(tr("kvt.ponos.title")))
264 .child(
265 field().child(
266 div()
267 .flex_1()
268 .child(Input::new(&self.title).appearance(false).bordered(false)),
269 ),
270 )
271 .child(label(tr("kvt.ponos.description")))
272 .child(Textarea::new(&self.description))
273 .children(self.error.clone().map(|error| {
274 div()
275 .text_size(px(13.))
276 .text_color(theme::red_soft())
277 .child(error)
278 }))
279 .child(
280 h_flex()
281 .w_full()
282 .gap(px(8.))
283 .justify_end()
284 .child(
285 secondary_button("kvt-ponos-cancel", "close", tr("common.cancel"))
286 .on_click(|_, _, cx| close_create(cx)),
287 )
288 .when(ready, |row| {
289 row.child(
290 primary_button(
291 "kvt-ponos-save",
292 tr(if self.saving {
293 "kvt.ponos.saving"
294 } else {
295 "kvt.ponos.save"
296 }),
297 )
298 .on_click(cx.listener(|this, _, _, cx| this.save(cx))),
299 )
300 }),
301 ),
302 )
303 }
304}
305
306// --- Mijn taken -------------------------------------------------------------
307
308/// Regel «Mijn taken in Ponos» in het instellingenmenu (`…` rechtsboven).
309pub fn extend_settings_menu(popup: PopupMenu, cx: &App) -> PopupMenu {
310 if !installed(cx) {
311 return popup;
312 }
313 popup.separator().item(
314 PopupMenuItem::new(tr("kvt.tasks.menu"))
315 .icon(IconName::ClipboardCheck)
316 .on_click(|_, _, cx| open_tasks(cx)),
317 )
318}
319
320pub(crate) fn open_tasks(cx: &mut App) {
321 update(cx, |kvt| kvt.tasks = Some(TasksLoad::Loading));
322 load_tasks(cx);
323}
324
325fn close_tasks(cx: &mut App) {
326 update(cx, |kvt| kvt.tasks = None);
327}
328
329fn refresh_tasks_if_open(cx: &mut App) {
330 if read(cx, |kvt| kvt.tasks.is_some()).unwrap_or(false) {
331 load_tasks(cx);
332 }
333}
334
335fn load_tasks(cx: &mut App) {
336 if is_demo(cx) {
337 let tasks = read(cx, |kvt| kvt.demo_tasks.clone()).unwrap_or_default();
338 update(cx, |kvt| kvt.tasks = Some(TasksLoad::Loaded(tasks)));
339 return;
340 }
341 let Some((token, client)) = token_and_client(cx) else {
342 return;
343 };
344 let loading = runtime::spawn(async move { client.ponos_my_tasks(&token).await });
345 cx.spawn(async move |cx| {
346 let result = loading.await.unwrap_or(Err(ClientError::Unavailable));
347 cx.update(|cx| {
348 if result == Err(ClientError::Unauthorized) {
349 forget_token(cx);
350 }
351 let load = match result {
352 Ok(tasks) => TasksLoad::Loaded(tasks),
353 Err(error) => TasksLoad::Failed(error),
354 };
355 update(cx, |kvt| {
356 if kvt.tasks.is_some() {
357 kvt.tasks = Some(load);
358 }
359 });
360 });
361 })
362 .detach();
363}
364
365fn complete(task: PonosTask, cx: &mut App) {
366 let remove = |kvt: &mut super::Kvt, id: &str| {
367 if let Some(TasksLoad::Loaded(tasks)) = kvt.tasks.as_mut() {
368 tasks.retain(|task| task.id != id);
369 }
370 kvt.demo_tasks.retain(|task| task.id != id);
371 };
372 if is_demo(cx) {
373 update(cx, |kvt| remove(kvt, &task.id));
374 notice(tr("kvt.tasks.completed"), cx);
375 return;
376 }
377 let Some((token, client)) = token_and_client(cx) else {
378 return;
379 };
380 let (group, id) = (task.group().to_owned(), task.id.clone());
381 let completing = runtime::spawn({
382 let id = id.clone();
383 async move { client.ponos_complete_task(&token, &group, &id).await }
384 });
385 cx.spawn(async move |cx| {
386 let result = completing.await.unwrap_or(Err(ClientError::Unavailable));
387 cx.update(|cx| match result {
388 Ok(()) => {
389 update(cx, |kvt| remove(kvt, &id));
390 notice(tr("kvt.tasks.completed"), cx);
391 }
392 Err(error) => {
393 if error == ClientError::Unauthorized {
394 forget_token(cx);
395 }
396 notice(ponos_error(&error), cx);
397 }
398 });
399 })
400 .detach();
401}
402
403pub fn render_tasks(cx: &App) -> Option<AnyElement> {
404 let load = read(cx, |kvt| kvt.tasks.clone()).flatten()?;
405 let body = if !matches!(link(cx), Link::Linked(_)) {
406 not_linked().into_any_element()
407 } else {
408 match load {
409 TasksLoad::Loading => muted(tr("kvt.card.loading")).into_any_element(),
410 TasksLoad::Failed(error) => muted(ponos_error(&error)).into_any_element(),
411 TasksLoad::Loaded(tasks) if tasks.is_empty() => {
412 muted(tr("kvt.tasks.empty")).into_any_element()
413 }
414 TasksLoad::Loaded(tasks) => v_flex()
415 .id("kvt-tasks-list")
416 .w_full()
417 .max_h(px(LIST_MAX_HEIGHT))
418 .overflow_y_scrollbar()
419 .children(
420 tasks
421 .into_iter()
422 .enumerate()
423 .map(|(index, task)| task_row(index, task)),
424 )
425 .into_any_element(),
426 }
427 };
428 let ponos = format!("{}/ponos/", base_url());
429 Some(
430 layer("kvt-tasks", |cx| close_tasks(cx))
431 .child(
432 panel(KVT_TASKS_PANEL_TAG)
433 .child(header(tr("kvt.tasks.title"), String::new(), |cx| {
434 close_tasks(cx)
435 }))
436 .child(body)
437 .child(
438 h_flex()
439 .w_full()
440 .gap(px(8.))
441 .child(
442 secondary_button(
443 "kvt-tasks-open",
444 "open_in_new",
445 tr("kvt.tasks.open_ponos"),
446 )
447 .on_click(move |_, _, cx| open_external(&ponos, cx)),
448 )
449 .child(
450 secondary_button(
451 "kvt-tasks-refresh",
452 "refresh",
453 tr("kvt.card.refresh"),
454 )
455 .on_click(|_, _, cx| open_tasks(cx)),
456 ),
457 ),
458 )
459 .into_any_element(),
460 )
461}
462
463fn task_row(index: usize, task: PonosTask) -> AnyElement {
464 let today = chrono::Local::now()
465 .date_naive()
466 .format("%Y-%m-%d")
467 .to_string();
468 let overdue = !task.due_date.is_empty() && task.due_date.as_str() < today.as_str();
469 let mut detail = Vec::new();
470 if !task.home_group_name.is_empty() {
471 detail.push(task.home_group_name.clone());
472 }
473 if task.status == "in_progress" {
474 detail.push(tr("kvt.tasks.in_progress"));
475 }
476 let due = iso_date_nl(&task.due_date);
477 let url = task.url(&base_url());
478 let done = task.clone();
479 h_flex()
480 .id(ElementId::Name(format!("kvt-task-{index}").into()))
481 .w_full()
482 .h(px(ROW_HEIGHT))
483 .flex_none()
484 .px(px(8.))
485 .gap(px(10.))
486 .items_center()
487 .rounded(px(6.))
488 .cursor_pointer()
489 .hover(|row| row.bg(theme::popup_hover()))
490 .on_click(move |_, _, cx| open_external(&url, cx))
491 .child(
492 div()
493 .id(ElementId::Name(format!("kvt-task-done-{index}").into()))
494 .size(px(CLOSE_SIZE))
495 .flex_none()
496 .flex()
497 .items_center()
498 .justify_center()
499 .rounded_full()
500 .hover(|button| button.bg(theme::row_hover()))
501 .on_click(move |_, _, cx| {
502 cx.stop_propagation();
503 complete(done.clone(), cx);
504 })
505 .child(symbol("check_circle", 18., theme::text_muted())),
506 )
507 .child(
508 v_flex()
509 .flex_1()
510 .min_w_0()
511 .child(
512 div()
513 .truncate()
514 .text_size(px(13.))
515 .text_color(theme::text())
516 .child(task.title.clone()),
517 )
518 .when(!detail.is_empty(), |column| {
519 column.child(
520 div()
521 .truncate()
522 .text_size(px(12.))
523 .text_color(theme::text_muted())
524 .child(detail.join(" · ")),
525 )
526 }),
527 )
528 .children(due.map(|due| {
529 div()
530 .flex_none()
531 .text_size(px(12.))
532 .text_color(if overdue {
533 theme::red_soft()
534 } else {
535 theme::text_muted()
536 })
537 .child(due)
538 }))
539 .into_any_element()
540}
541
542// --- gedeelde bouwstenen ----------------------------------------------------
543
544fn ponos_error(error: &ClientError) -> String {
545 match error {
546 ClientError::Forbidden => tr("kvt.ponos.forbidden"),
547 ClientError::NotFound | ClientError::BadRequest => tr("kvt.ponos.failed"),
548 other => error_text(other),
549 }
550}
551
552fn layer(id: &'static str, close: fn(&mut App)) -> Stateful<Div> {
553 div()
554 .id(SharedString::from(format!("{id}-layer")))
555 .absolute()
556 .top_0()
557 .left_0()
558 .size_full()
559 .flex()
560 .items_center()
561 .justify_center()
562 .child(
563 div()
564 .id(SharedString::from(format!("{id}-backdrop")))
565 .absolute()
566 .top_0()
567 .left_0()
568 .size_full()
569 .bg(black().opacity(BACKDROP_OPACITY))
570 .occlude()
571 .on_click(move |_, _, cx| close(cx)),
572 )
573}
574
575fn panel(tag: &'static str) -> Div {
576 v_flex()
577 .debug_selector(move || tag.into())
578 .w(px(PANEL_WIDTH))
579 .max_w(relative(1.))
580 .max_h(relative(1.))
581 .m(px(PANEL_MARGIN))
582 .p(px(PANEL_PADDING))
583 .gap(px(SECTION_GAP))
584 .rounded(px(PANEL_RADIUS))
585 .dialog_surface()
586 .text_color(theme::text())
587 .occlude()
588}
589
590fn header(title: String, detail: String, close: fn(&mut App)) -> Div {
591 h_flex()
592 .w_full()
593 .items_center()
594 .gap(px(SECTION_GAP))
595 .child(
596 v_flex()
597 .flex_1()
598 .min_w_0()
599 .child(
600 div()
601 .text_size(px(15.))
602 .font_weight(FontWeight::SEMIBOLD)
603 .child(title),
604 )
605 .when(!detail.is_empty(), |column| {
606 column.child(
607 div()
608 .truncate()
609 .text_size(px(12.))
610 .text_color(theme::text_muted())
611 .child(detail),
612 )
613 }),
614 )
615 .child(
616 div()
617 .id("kvt-dialog-close")
618 .size(px(CLOSE_SIZE))
619 .flex_none()
620 .flex()
621 .items_center()
622 .justify_center()
623 .rounded_full()
624 .cursor_pointer()
625 .hover(|button| button.bg(theme::popup_hover()))
626 .on_click(move |_, _, cx| close(cx))
627 .child(symbol("close", 16., theme::text_muted())),
628 )
629}
630
631fn label(text: String) -> Div {
632 div()
633 .text_size(px(12.))
634 .font_weight(FontWeight::SEMIBOLD)
635 .text_color(theme::text_muted())
636 .child(text)
637}
638
639fn muted(text: String) -> Div {
640 div()
641 .w_full()
642 .py(px(8.))
643 .text_size(px(13.))
644 .text_color(theme::text_muted())
645 .child(text)
646}
647
648fn field() -> Div {
649 h_flex()
650 .w_full()
651 .h(px(FIELD_HEIGHT))
652 .flex_none()
653 .px(px(10.))
654 .items_center()
655 .rounded(px(6.))
656 .bg(theme::popup_hover())
657}
658
659fn chip(id: SharedString, label: String, selected: bool) -> Stateful<Div> {
660 h_flex()
661 .id(id)
662 .h(px(CHIP_HEIGHT))
663 .flex_none()
664 .px(px(12.))
665 .items_center()
666 .rounded_full()
667 .text_size(px(13.))
668 .cursor_pointer()
669 .map(|chip| {
670 if selected {
671 chip.bg(theme::accent())
672 .text_color(theme::on_accent())
673 .font_weight(FontWeight::SEMIBOLD)
674 } else {
675 chip.bg(theme::popup_hover())
676 .text_color(theme::text())
677 .hover(|chip| chip.bg(theme::row_hover()))
678 }
679 })
680 .child(label)
681}
682
683fn not_linked() -> Div {
684 v_flex()
685 .w_full()
686 .gap(px(8.))
687 .child(muted(tr("kvt.card.sign_in")))
688 .child(
689 primary_button("kvt-tasks-connect", tr("kvt.settings.connect"))
690 .self_start()
691 .on_click(|_, _, cx| connect(cx)),
692 )
693}