BlueGit

ict rusty-teams

Files

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

board.rs

board.rs 49.6 KiB Download Raw
1//! Ponos-bord in het hoofdpaneel: de tegel «Ponos» in de navigatierail, direct
2//! onder Agents (Tim). Links alle groepen die je in Ponos ziet (eerst
3//! «Mijn Taken», je persoonlijke groep), rechts het bord met de kolommen van
4//! Ponos. Taken maken, bewerken, afronden en slepen tussen en binnen kolommen.
5//!
6//! Upstream-haken: `views/rail.rs` (tegel), `views/sidebar.rs` (`SidebarTab::Ponos`),
7//! `views/shell.rs` (hoofdpaneel). Zie KVT-FORK.md.
8
9use std::collections::HashMap;
10
11use gpui_kit::component::input::{Input, InputState, Textarea, TextareaState};
12use gpui_kit::component::scroll::ScrollableElement as _;
13use gpui_kit::component::{h_flex, v_flex};
14use gpui_kit::prelude::FluentBuilder as _;
15use gpui_kit::*;
16use kvt_sleutels::format::{iso_date_nl, parse_date_input};
17use kvt_sleutels::ponos::{
18 MY_TASKS_GROUP, PonosGroup, PonosNavigation, PonosTask, STATUS_DONE, STATUSES, TaskInput,
19 apply_move, column, drop_position, group_url, name_from_email,
20};
21use kvt_sleutels::{CardsClient, ClientError};
22
23use super::modal::{primary_button, secondary_button};
24use super::tasks::{chip, field, label, muted, not_linked, ponos_error};
25use super::{Link, base_url, forget_token, is_demo, link, notice, open_external, token_and_client};
26use crate::app_state::AppHandle;
27use crate::i18n::tr;
28use crate::runtime;
29use crate::theme::{self, ElevatedSurface as _};
30use crate::views::widgets::symbol;
31
32pub const KVT_BOARD_TAG: &str = "kvt-ponos-board";
33/// Laatst gekozen groep op het bord (alleen een id, in de lokale opslag).
34const BOARD_GROUP_META_KEY: &str = "kvt.ponos.board_group";
35const TITLE_MAX: usize = 200;
36const HEADER_HEIGHT: f32 = 60.;
37const PAGE_PADDING: f32 = 20.;
38const GROUPS_WIDTH: f32 = 240.;
39const GROUP_ROW_HEIGHT: f32 = 36.;
40const COLUMN_MIN_WIDTH: f32 = 220.;
41const COLUMN_GAP: f32 = 12.;
42const CARD_GAP: f32 = 8.;
43const RADIUS: f32 = 10.;
44const EDITOR_WIDTH: f32 = 560.;
45const BACKDROP_OPACITY: f32 = 0.55;
46
47#[derive(Clone)]
48enum Nav {
49 NotLinked,
50 Loading,
51 Loaded(PonosNavigation),
52 Failed(ClientError),
53}
54
55#[derive(Clone)]
56enum Tasks {
57 Loading,
58 Loaded(Vec<PonosTask>),
59 Failed(ClientError),
60}
61
62#[derive(Clone)]
63struct DraggedTask {
64 id: String,
65 title: String,
66 from_status: String,
67}
68
69struct TaskGhost {
70 title: String,
71}
72
73impl Render for TaskGhost {
74 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
75 div()
76 .w(px(COLUMN_MIN_WIDTH))
77 .px(px(12.))
78 .py(px(10.))
79 .rounded(px(8.))
80 .flyout_surface()
81 .text_size(px(13.))
82 .text_color(theme::text())
83 .truncate()
84 .child(self.title.clone())
85 }
86}
87
88struct Editor {
89 /// `None`: nieuwe taak.
90 task: Option<PonosTask>,
91 status: String,
92 assignee: String,
93 target_group: Option<String>,
94 title: Entity<InputState>,
95 description: Entity<TextareaState>,
96 due: Entity<InputState>,
97 saving: bool,
98 error: Option<String>,
99}
100
101pub struct PonosBoard {
102 nav: Nav,
103 group: Option<String>,
104 tasks: Tasks,
105 generation: u64,
106 editor: Option<Editor>,
107 /// Alleen `--demo`: verzonnen taken per groep.
108 demo: HashMap<String, Vec<PonosTask>>,
109}
110
111/// Het bord als element van het hoofdpaneel (eenmalig aangemaakt).
112pub fn board_view(cx: &mut App) -> AnyElement {
113 let existing = super::read(cx, |kvt| kvt.board.clone()).flatten();
114 let board = match existing {
115 Some(board) => board,
116 None => {
117 let board = cx.new(PonosBoard::new);
118 if cx.has_global::<super::Kvt>() {
119 cx.global_mut::<super::Kvt>().board = Some(board.clone());
120 }
121 board
122 }
123 };
124 div()
125 .flex_1()
126 .min_w_0()
127 .h_full()
128 .child(board)
129 .into_any_element()
130}
131
132/// De tegel is geopend: vers ophalen (bij de eerste keer laadt `new`).
133pub fn board_opened(cx: &mut App) {
134 if let Some(board) = super::read(cx, |kvt| kvt.board.clone()).flatten() {
135 board.update(cx, |board, cx| board.reload(cx));
136 }
137}
138
139/// Na «Taak maken in Ponos» vanuit een bericht.
140pub(super) fn refresh_board_if_open(cx: &mut App) {
141 board_opened(cx);
142}
143
144fn remembered_group(cx: &App) -> Option<String> {
145 let handle = cx.try_global::<AppHandle>()?;
146 handle
147 .0
148 .read(cx)
149 .store
150 .meta(BOARD_GROUP_META_KEY)
151 .ok()
152 .flatten()
153}
154
155fn remember_group(group: &str, cx: &App) {
156 if let Some(handle) = cx.try_global::<AppHandle>() {
157 let _ = handle
158 .0
159 .read(cx)
160 .store
161 .set_meta(BOARD_GROUP_META_KEY, group);
162 }
163}
164
165/// Gekozen groep als die nog bestaat, anders de eerste (Mijn Taken).
166fn pick_group(wanted: Option<&str>, navigation: &PonosNavigation) -> Option<String> {
167 wanted
168 .filter(|wanted| navigation.groups.iter().any(|group| group.id == *wanted))
169 .map(str::to_owned)
170 .or_else(|| navigation.groups.first().map(|group| group.id.clone()))
171}
172
173fn status_fallback(status: &str) -> String {
174 tr(match status {
175 "in_progress" => "kvt.board_status.in_progress",
176 STATUS_DONE => "kvt.board_status.done",
177 _ => "kvt.board_status.todo",
178 })
179}
180
181impl PonosBoard {
182 fn new(cx: &mut Context<Self>) -> Self {
183 let demo = if is_demo(cx) {
184 super::demo::board_tasks()
185 } else {
186 HashMap::new()
187 };
188 let mut board = PonosBoard {
189 nav: Nav::Loading,
190 group: remembered_group(cx),
191 tasks: Tasks::Loading,
192 generation: 0,
193 editor: None,
194 demo,
195 };
196 board.reload(cx);
197 board
198 }
199
200 fn navigation(&self) -> Option<&PonosNavigation> {
201 match &self.nav {
202 Nav::Loaded(navigation) => Some(navigation),
203 _ => None,
204 }
205 }
206
207 fn current_group(&self) -> Option<&PonosGroup> {
208 let group = self.group.as_deref()?;
209 self.navigation()?
210 .groups
211 .iter()
212 .find(|candidate| candidate.id == group)
213 }
214
215 fn user_email(&self) -> String {
216 self.navigation()
217 .map(|navigation| navigation.user_email.clone())
218 .unwrap_or_default()
219 }
220
221 fn status_label(&self, status: &str) -> String {
222 match self.navigation() {
223 Some(navigation) => navigation.status_label(status, || status_fallback(status)),
224 None => status_fallback(status),
225 }
226 }
227
228 // --- laden ------------------------------------------------------------
229
230 fn reload(&mut self, cx: &mut Context<Self>) {
231 self.generation += 1;
232 if is_demo(cx) {
233 let navigation = super::demo::board_navigation(&self.demo);
234 self.group = pick_group(self.group.as_deref(), &navigation);
235 self.tasks = Tasks::Loaded(self.demo_tasks());
236 self.nav = Nav::Loaded(navigation);
237 cx.notify();
238 return;
239 }
240 let Some((token, client)) = token_and_client(cx) else {
241 self.nav = Nav::NotLinked;
242 cx.notify();
243 return;
244 };
245 if !matches!(self.nav, Nav::Loaded(_)) {
246 self.nav = Nav::Loading;
247 }
248 let generation = self.generation;
249 let wanted = self.group.clone();
250 let loading = runtime::spawn(async move {
251 let navigation = client.ponos_navigation(&token).await?;
252 let group = pick_group(wanted.as_deref(), &navigation);
253 let tasks = match &group {
254 Some(group) => client.ponos_tasks(&token, group).await,
255 None => Ok(Vec::new()),
256 };
257 Ok::<_, ClientError>((navigation, group, tasks))
258 });
259 cx.spawn(async move |this, cx| {
260 let result = loading.await.unwrap_or(Err(ClientError::Unavailable));
261 cx.update(|cx| {
262 let unauthorized = matches!(&result, Err(ClientError::Unauthorized))
263 || matches!(&result, Ok((_, _, Err(ClientError::Unauthorized))));
264 if unauthorized {
265 forget_token(cx);
266 }
267 this.update(cx, |this, cx| {
268 if this.generation != generation {
269 return;
270 }
271 match result {
272 Ok((navigation, group, tasks)) => {
273 this.group = group;
274 this.tasks = match tasks {
275 Ok(tasks) => Tasks::Loaded(tasks),
276 Err(error) => Tasks::Failed(error),
277 };
278 this.nav = Nav::Loaded(navigation);
279 }
280 Err(ClientError::Unauthorized) => this.nav = Nav::NotLinked,
281 Err(error) => this.nav = Nav::Failed(error),
282 }
283 cx.notify();
284 })
285 .ok();
286 });
287 })
288 .detach();
289 }
290
291 fn select_group(&mut self, group: String, cx: &mut Context<Self>) {
292 if self.group.as_deref() == Some(group.as_str()) {
293 return;
294 }
295 remember_group(&group, cx);
296 self.group = Some(group);
297 self.tasks = Tasks::Loading;
298 self.editor = None;
299 self.reload(cx);
300 }
301
302 // --- demo -------------------------------------------------------------
303
304 fn demo_tasks(&self) -> Vec<PonosTask> {
305 let Some(group) = self.group.as_deref() else {
306 return Vec::new();
307 };
308 if group == MY_TASKS_GROUP {
309 let mut mine: Vec<PonosTask> = self
310 .demo
311 .values()
312 .flatten()
313 .filter(|task| task.assignee_email == super::demo::BOARD_USER)
314 .cloned()
315 .collect();
316 mine.sort_by(|a, b| a.id.cmp(&b.id));
317 return mine;
318 }
319 self.demo.get(group).cloned().unwrap_or_default()
320 }
321
322 fn demo_task_mut(&mut self, id: &str) -> Option<&mut PonosTask> {
323 self.demo.values_mut().flatten().find(|task| task.id == id)
324 }
325
326 // --- acties -----------------------------------------------------------
327
328 /// Een schrijfactie bij Ponos; daarna altijd opnieuw laden.
329 fn submit<Fut>(
330 &mut self,
331 cx: &mut Context<Self>,
332 done: Option<String>,
333 job: impl FnOnce(String, CardsClient) -> Fut,
334 ) where
335 Fut: std::future::Future<Output = Result<(), ClientError>> + Send + 'static,
336 {
337 let Some((token, client)) = token_and_client(cx) else {
338 self.reload(cx);
339 return;
340 };
341 let running = runtime::spawn(job(token, client));
342 cx.spawn(async move |this, cx| {
343 let result = running.await.unwrap_or(Err(ClientError::Unavailable));
344 cx.update(|cx| {
345 match &result {
346 Ok(()) => {
347 if let Some(done) = done {
348 notice(done, cx);
349 }
350 }
351 Err(error) => {
352 if *error == ClientError::Unauthorized {
353 forget_token(cx);
354 }
355 notice(ponos_error(error), cx);
356 }
357 }
358 this.update(cx, |this, cx| {
359 if result.is_ok() {
360 this.editor = None;
361 } else if let Some(editor) = this.editor.as_mut() {
362 editor.saving = false;
363 }
364 this.reload(cx);
365 })
366 .ok();
367 });
368 })
369 .detach();
370 }
371
372 fn drop_task(
373 &mut self,
374 dragged: &DraggedTask,
375 status: &'static str,
376 before: Option<usize>,
377 cx: &mut Context<Self>,
378 ) {
379 let Some(group) = self.group.clone() else {
380 return;
381 };
382 let Tasks::Loaded(tasks) = &mut self.tasks else {
383 return;
384 };
385 let position = drop_position(tasks, &dragged.id, status, before);
386 let unchanged = dragged.from_status == status
387 && column(tasks, status).position(|task| task.id == dragged.id) == Some(position);
388 if unchanged || !apply_move(tasks, &dragged.id, status, position) {
389 return;
390 }
391 cx.notify();
392 let id = dragged.id.clone();
393 if is_demo(cx) {
394 if let Some(task) = self.demo_task_mut(&id) {
395 task.status = status.to_owned();
396 }
397 if group != MY_TASKS_GROUP
398 && let Some(list) = self.demo.get_mut(&group)
399 {
400 apply_move(list, &id, status, position);
401 }
402 return;
403 }
404 let virtual_group = group == MY_TASKS_GROUP;
405 let status_changed = dragged.from_status != status;
406 if virtual_group && !status_changed {
407 // «Mijn Taken» heeft geen eigen volgorde in Ponos.
408 return;
409 }
410 self.submit(cx, None, move |token, client| async move {
411 if virtual_group {
412 client.ponos_set_status(&token, &group, &id, status).await?;
413 } else {
414 client
415 .ponos_reorder_task(&token, &group, &id, status, position)
416 .await?;
417 }
418 Ok(())
419 });
420 }
421
422 fn open_editor(
423 &mut self,
424 task: Option<PonosTask>,
425 status: &str,
426 window: &mut Window,
427 cx: &mut Context<Self>,
428 ) {
429 let (title_text, description_text, due_text) = match &task {
430 Some(task) => (
431 task.title.clone(),
432 task.description.clone(),
433 iso_date_nl(&task.due_date).unwrap_or_default(),
434 ),
435 None => Default::default(),
436 };
437 let title = cx.new(|cx| {
438 InputState::new(window, cx)
439 .placeholder(tr("kvt.ponos.title"))
440 .default_value(title_text)
441 });
442 let description = cx.new(|cx| {
443 TextareaState::new(window, cx)
444 .auto_grow(4, 10)
445 .placeholder(tr("kvt.ponos.description"))
446 .default_value(description_text)
447 });
448 let due = cx.new(|cx| {
449 InputState::new(window, cx)
450 .placeholder(tr("kvt.board.due_placeholder"))
451 .default_value(due_text)
452 });
453 title.update(cx, |input, cx| input.focus(window, cx));
454 let assignee = match &task {
455 Some(task) => task.assignee_email.clone(),
456 // Nieuw in «Mijn Taken» kan niet; elders standaard niemand.
457 None => String::new(),
458 };
459 self.editor = Some(Editor {
460 status: task
461 .as_ref()
462 .map_or_else(|| status.to_owned(), |task| task.status.clone()),
463 assignee,
464 target_group: None,
465 task,
466 title,
467 description,
468 due,
469 saving: false,
470 error: None,
471 });
472 cx.notify();
473 }
474
475 fn save_editor(&mut self, cx: &mut Context<Self>) {
476 let Some(group) = self.group.clone() else {
477 return;
478 };
479 let Some(editor) = self.editor.as_mut() else {
480 return;
481 };
482 if editor.saving {
483 return;
484 }
485 let title: String = editor
486 .title
487 .read(cx)
488 .value()
489 .trim()
490 .chars()
491 .take(TITLE_MAX)
492 .collect();
493 let description = editor.description.read(cx).value().trim().to_owned();
494 if title.is_empty() || description.is_empty() {
495 editor.error = Some(tr("kvt.ponos.fill_in"));
496 cx.notify();
497 return;
498 }
499 let Some(due_date) = parse_date_input(&editor.due.read(cx).value()) else {
500 editor.error = Some(tr("kvt.board.bad_date"));
501 cx.notify();
502 return;
503 };
504 let input = TaskInput {
505 title,
506 description,
507 due_date,
508 assignee_email: editor.assignee.clone(),
509 target_group: editor.target_group.clone(),
510 };
511 let status = editor.status.clone();
512 let existing = editor.task.clone();
513 editor.saving = true;
514 editor.error = None;
515 cx.notify();
516
517 if is_demo(cx) {
518 self.save_demo(&group, existing, input, status);
519 self.editor = None;
520 notice(tr("kvt.board.saved"), cx);
521 self.reload(cx);
522 return;
523 }
524 let done = tr(if existing.is_some() {
525 "kvt.board.saved"
526 } else {
527 "kvt.ponos.created"
528 });
529 self.submit(cx, Some(done), move |token, client| async move {
530 match existing {
531 Some(task) => {
532 let saved = client
533 .ponos_update_task(&token, &group, &task.id, &input)
534 .await?;
535 if saved.status != status {
536 let home = input.target_group.as_deref().unwrap_or(&group);
537 client
538 .ponos_set_status(&token, home, &saved.id, &status)
539 .await?;
540 }
541 }
542 None => {
543 let created = client.ponos_create(&token, &group, &input).await?;
544 if created.status != status {
545 client
546 .ponos_set_status(&token, &group, &created.id, &status)
547 .await?;
548 }
549 }
550 }
551 Ok(())
552 });
553 }
554
555 fn save_demo(
556 &mut self,
557 group: &str,
558 existing: Option<PonosTask>,
559 input: TaskInput,
560 status: String,
561 ) {
562 match existing {
563 Some(task) => {
564 let home = task.group().to_owned();
565 let Some(list) = self.demo.get_mut(&home) else {
566 return;
567 };
568 let Some(index) = list.iter().position(|other| other.id == task.id) else {
569 return;
570 };
571 let mut updated = list.remove(index);
572 updated.title = input.title;
573 updated.description = input.description;
574 updated.due_date = input.due_date;
575 updated.assignee_email = input.assignee_email;
576 let target = input.target_group.unwrap_or(home.clone());
577 if target == home && updated.status == status {
578 list.insert(index, updated);
579 return;
580 }
581 updated.status = status;
582 updated.group_id = target.clone();
583 updated.home_group_id = target.clone();
584 self.demo.entry(target).or_default().push(updated);
585 }
586 None => {
587 let id = format!(
588 "demo-board-{}",
589 self.demo.values().map(Vec::len).sum::<usize>() + 1
590 );
591 let task = PonosTask {
592 id,
593 group_id: group.to_owned(),
594 home_group_id: group.to_owned(),
595 title: input.title,
596 status,
597 due_date: input.due_date,
598 description: input.description,
599 assignee_email: input.assignee_email,
600 ..super::demo::empty_task()
601 };
602 self.demo.entry(group.to_owned()).or_default().push(task);
603 }
604 }
605 }
606
607 fn complete_from_editor(&mut self, cx: &mut Context<Self>) {
608 let Some(group) = self.group.clone() else {
609 return;
610 };
611 let Some(task) = self.editor.as_ref().and_then(|editor| editor.task.clone()) else {
612 return;
613 };
614 if is_demo(cx) {
615 if let Some(demo) = self.demo_task_mut(&task.id) {
616 demo.status = STATUS_DONE.to_owned();
617 }
618 self.editor = None;
619 notice(tr("kvt.tasks.completed"), cx);
620 self.reload(cx);
621 return;
622 }
623 if let Some(editor) = self.editor.as_mut() {
624 editor.saving = true;
625 }
626 self.submit(
627 cx,
628 Some(tr("kvt.tasks.completed")),
629 move |token, client| async move {
630 client.ponos_complete_task(&token, &group, &task.id).await
631 },
632 );
633 }
634
635 // --- weergave ---------------------------------------------------------
636
637 fn groups_list(&self, cx: &mut Context<Self>) -> AnyElement {
638 let Some(navigation) = self.navigation() else {
639 return div().into_any_element();
640 };
641 v_flex()
642 .id("kvt-board-groups")
643 .w(px(GROUPS_WIDTH))
644 .h_full()
645 .flex_none()
646 .p(px(8.))
647 .gap(px(2.))
648 .border_r_1()
649 .border_color(theme::border())
650 .overflow_y_scrollbar()
651 .children(navigation.groups.iter().enumerate().map(|(index, group)| {
652 let selected = self.group.as_deref() == Some(group.id.as_str());
653 let id = group.id.clone();
654 h_flex()
655 .id(ElementId::Name(format!("kvt-board-group-{index}").into()))
656 .w_full()
657 .h(px(GROUP_ROW_HEIGHT))
658 .flex_none()
659 .px(px(10.))
660 .gap(px(8.))
661 .items_center()
662 .rounded(px(6.))
663 .cursor_pointer()
664 .text_size(px(13.))
665 .map(|row| {
666 if selected {
667 row.bg(theme::selection())
668 .text_color(theme::text_strong())
669 .font_weight(FontWeight::SEMIBOLD)
670 } else {
671 row.text_color(theme::text())
672 .hover(|row| row.bg(theme::row_hover()))
673 }
674 })
675 .on_click(cx.listener(move |this, _, _, cx| this.select_group(id.clone(), cx)))
676 .child(symbol(
677 if group.is_virtual { "person" } else { "group" },
678 16.,
679 if selected {
680 theme::accent_text()
681 } else {
682 theme::text_muted()
683 },
684 ))
685 .child(
686 div()
687 .flex_1()
688 .min_w_0()
689 .truncate()
690 .child(group.name.clone()),
691 )
692 .when(group.task_count > 0, |row| {
693 row.child(
694 div()
695 .flex_none()
696 .text_size(px(12.))
697 .text_color(theme::text_muted())
698 .child(group.task_count.to_string()),
699 )
700 })
701 }))
702 .into_any_element()
703 }
704
705 fn header(&self, cx: &mut Context<Self>) -> Div {
706 let group = self.current_group();
707 let title = group.map_or_else(|| tr("kvt.board.title"), |group| group.name.clone());
708 let can_create = group.is_some_and(PonosGroup::accepts_new_tasks)
709 && matches!(self.tasks, Tasks::Loaded(_));
710 let url = match self.group.as_deref() {
711 Some(group) => group_url(&base_url(), group),
712 None => format!("{}/ponos/", base_url()),
713 };
714 h_flex()
715 .h(px(HEADER_HEIGHT))
716 .flex_none()
717 .px(px(PAGE_PADDING))
718 .gap(px(8.))
719 .items_center()
720 .child(
721 div()
722 .flex_1()
723 .min_w_0()
724 .truncate()
725 .text_size(px(16.))
726 .font_weight(FontWeight::BOLD)
727 .text_color(theme::text())
728 .child(title),
729 )
730 .when(can_create, |row| {
731 row.child(
732 primary_button("kvt-board-new", tr("kvt.board.new_task")).on_click(
733 cx.listener(|this, _, window, cx| {
734 this.open_editor(None, STATUSES[0], window, cx)
735 }),
736 ),
737 )
738 })
739 .child(
740 secondary_button("kvt-board-refresh", "refresh", tr("kvt.card.refresh"))
741 .on_click(cx.listener(|this, _, _, cx| this.reload(cx))),
742 )
743 .child(
744 secondary_button("kvt-board-open", "open_in_new", tr("kvt.tasks.open_ponos"))
745 .on_click(move |_, _, cx| open_external(&url, cx)),
746 )
747 }
748
749 fn columns(&self, cx: &mut Context<Self>) -> AnyElement {
750 let tasks = match &self.tasks {
751 Tasks::Loading => {
752 return muted(tr("kvt.card.loading"))
753 .px(px(PAGE_PADDING))
754 .into_any_element();
755 }
756 Tasks::Failed(error) => {
757 return muted(ponos_error(error))
758 .px(px(PAGE_PADDING))
759 .into_any_element();
760 }
761 Tasks::Loaded(tasks) => tasks,
762 };
763 let group = self.current_group();
764 let editable = group.is_some_and(PonosGroup::editable);
765 let can_create = group.is_some_and(PonosGroup::accepts_new_tasks);
766 let me = self.user_email();
767 h_flex()
768 .id("kvt-board-columns")
769 .flex_1()
770 .min_h_0()
771 .w_full()
772 .px(px(PAGE_PADDING))
773 .pb(px(PAGE_PADDING))
774 .gap(px(COLUMN_GAP))
775 .items_start()
776 .overflow_x_scrollbar()
777 .children(
778 STATUSES
779 .iter()
780 .map(|&status| self.column(tasks, status, editable, can_create, &me, cx)),
781 )
782 .into_any_element()
783 }
784
785 fn column(
786 &self,
787 tasks: &[PonosTask],
788 status: &'static str,
789 editable: bool,
790 can_create: bool,
791 me: &str,
792 cx: &mut Context<Self>,
793 ) -> AnyElement {
794 let cards: Vec<&PonosTask> = column(tasks, status).collect();
795 let today = chrono::Local::now().format("%Y-%m-%d").to_string();
796 let dot = match status {
797 "in_progress" => theme::accent(),
798 STATUS_DONE => theme::green(),
799 _ => theme::text_faint(),
800 };
801 v_flex()
802 .id(ElementId::Name(format!("kvt-board-column-{status}").into()))
803 .debug_selector(move || format!("kvt-board/column/{status}"))
804 .flex_1()
805 .min_w(px(COLUMN_MIN_WIDTH))
806 .h_full()
807 .p(px(10.))
808 .gap(px(CARD_GAP))
809 .rounded(px(RADIUS))
810 .bg(theme::surface())
811 .drag_over::<DraggedTask>(|style, _, _, _| style.bg(theme::drop_background()))
812 .on_drop(cx.listener(move |this, dragged: &DraggedTask, _, cx| {
813 this.drop_task(dragged, status, None, cx)
814 }))
815 .child(
816 h_flex()
817 .w_full()
818 .h(px(28.))
819 .flex_none()
820 .gap(px(8.))
821 .items_center()
822 .child(div().size(px(8.)).flex_none().rounded_full().bg(dot))
823 .child(
824 div()
825 .flex_1()
826 .min_w_0()
827 .truncate()
828 .text_size(px(13.))
829 .font_weight(FontWeight::SEMIBOLD)
830 .text_color(theme::text())
831 .child(self.status_label(status)),
832 )
833 .child(
834 div()
835 .text_size(px(12.))
836 .text_color(theme::text_muted())
837 .child(cards.len().to_string()),
838 )
839 .when(can_create, |row| {
840 row.child(
841 div()
842 .id(ElementId::Name(format!("kvt-board-add-{status}").into()))
843 .size(px(24.))
844 .flex_none()
845 .flex()
846 .items_center()
847 .justify_center()
848 .rounded_full()
849 .cursor_pointer()
850 .hover(|button| button.bg(theme::row_hover()))
851 .on_click(cx.listener(move |this, _, window, cx| {
852 this.open_editor(None, status, window, cx)
853 }))
854 .child(symbol("add", 16., theme::text_muted())),
855 )
856 }),
857 )
858 .child(
859 v_flex()
860 .id(ElementId::Name(format!("kvt-board-cards-{status}").into()))
861 .w_full()
862 .flex_1()
863 .min_h(px(80.))
864 .gap(px(CARD_GAP))
865 .overflow_y_scrollbar()
866 .when(cards.is_empty(), |list| {
867 list.child(
868 div()
869 .w_full()
870 .py(px(16.))
871 .text_center()
872 .text_size(px(12.))
873 .text_color(theme::text_faint())
874 .child(tr("kvt.board.empty_column")),
875 )
876 })
877 .children(cards.iter().enumerate().map(|(index, task)| {
878 self.card(task, status, index, editable, me, &today, cx)
879 })),
880 )
881 .into_any_element()
882 }
883
884 #[allow(clippy::too_many_arguments)]
885 fn card(
886 &self,
887 task: &PonosTask,
888 status: &'static str,
889 index: usize,
890 editable: bool,
891 me: &str,
892 today: &str,
893 cx: &mut Context<Self>,
894 ) -> AnyElement {
895 let movable = editable && task.can_edit;
896 let overdue =
897 status != STATUS_DONE && !task.due_date.is_empty() && task.due_date.as_str() < today;
898 let due = iso_date_nl(&task.due_date);
899 let assignee = if task.assignee_email.is_empty() {
900 None
901 } else if task.assignee_email.eq_ignore_ascii_case(me) {
902 Some(tr("kvt.board.assignee_me"))
903 } else {
904 Some(name_from_email(&task.assignee_email))
905 };
906 let in_my_tasks = self.group.as_deref() == Some(MY_TASKS_GROUP);
907 let open = task.clone();
908 let dragged = DraggedTask {
909 id: task.id.clone(),
910 title: task.title.clone(),
911 from_status: task.status.clone(),
912 };
913 v_flex()
914 .id(ElementId::Name(
915 format!("kvt-board-card-{}", task.id).into(),
916 ))
917 .w_full()
918 .flex_none()
919 .px(px(12.))
920 .py(px(10.))
921 .gap(px(6.))
922 .rounded(px(8.))
923 .bg(theme::surface_raised())
924 .cursor_pointer()
925 .hover(|card| card.bg(theme::popup_hover()))
926 .on_click(cx.listener(move |this, _, window, cx| {
927 this.open_editor(Some(open.clone()), &open.status, window, cx)
928 }))
929 .when(movable, |card| {
930 card.on_drag(dragged, |dragged, _, _, cx| {
931 let title = dragged.title.clone();
932 cx.new(|_| TaskGhost { title })
933 })
934 .drag_over::<DraggedTask>(|style, _, _, _| style.bg(theme::drop_background()))
935 .on_drop(cx.listener(
936 move |this, dragged: &DraggedTask, _, cx| {
937 cx.stop_propagation();
938 this.drop_task(dragged, status, Some(index), cx)
939 },
940 ))
941 })
942 .when(in_my_tasks && !task.home_group_name.is_empty(), |card| {
943 card.child(
944 div()
945 .truncate()
946 .text_size(px(11.))
947 .text_color(theme::text_muted())
948 .child(task.home_group_name.clone()),
949 )
950 })
951 .child(
952 div()
953 .text_size(px(13.))
954 .line_height(px(18.))
955 .text_color(if status == STATUS_DONE {
956 theme::text_muted()
957 } else {
958 theme::text()
959 })
960 .when(status == STATUS_DONE, |text| text.line_through())
961 .child(task.title.clone()),
962 )
963 .child(
964 h_flex()
965 .w_full()
966 .flex_wrap()
967 .gap(px(8.))
968 .items_center()
969 .text_size(px(11.))
970 .text_color(theme::text_muted())
971 .when(!task.category_label.is_empty(), |row| {
972 row.child(
973 div()
974 .px(px(6.))
975 .py(px(1.))
976 .rounded(px(4.))
977 .bg(theme::selection())
978 .text_color(theme::text_strong())
979 .child(task.category_label.clone()),
980 )
981 })
982 .children(due.map(|due| {
983 h_flex()
984 .gap(px(3.))
985 .items_center()
986 .text_color(if overdue {
987 theme::red_soft()
988 } else {
989 theme::text_muted()
990 })
991 .child(symbol(
992 "event",
993 12.,
994 if overdue {
995 theme::red_soft()
996 } else {
997 theme::text_muted()
998 },
999 ))
1000 .child(due)
1001 }))
1002 .when(task.checklist_total > 0, |row| {
1003 row.child(
1004 h_flex()
1005 .gap(px(3.))
1006 .items_center()
1007 .child(symbol("check", 12., theme::text_muted()))
1008 .child(format!("{}/{}", task.checklist_done, task.checklist_total)),
1009 )
1010 })
1011 .children(assignee.map(|assignee| {
1012 h_flex()
1013 .gap(px(3.))
1014 .items_center()
1015 .child(symbol("person", 12., theme::text_muted()))
1016 .child(assignee)
1017 })),
1018 )
1019 .into_any_element()
1020 }
1021
1022 fn editor_layer(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
1023 let editor = self.editor.as_ref()?;
1024 let navigation = self.navigation()?;
1025 let me = navigation.user_email.clone();
1026 let existing = editor.task.clone();
1027 let editable = existing.as_ref().is_none_or(|task| task.can_edit);
1028 let home = existing
1029 .as_ref()
1030 .map(|task| task.group().to_owned())
1031 .or_else(|| self.group.clone())
1032 .unwrap_or_default();
1033 let target = editor.target_group.clone().unwrap_or_else(|| home.clone());
1034 let title = tr(if existing.is_some() {
1035 "kvt.board.edit_task"
1036 } else {
1037 "kvt.ponos.dialog_title"
1038 });
1039 let detail = existing
1040 .as_ref()
1041 .filter(|task| !task.home_group_name.is_empty())
1042 .map(|task| task.home_group_name.clone())
1043 .unwrap_or_default();
1044 let url = existing.as_ref().map(|task| task.url(&base_url()));
1045 let move_groups: Vec<PonosGroup> = navigation
1046 .groups
1047 .iter()
1048 .filter(|group| !group.is_virtual && group.has_task_access)
1049 .cloned()
1050 .collect();
1051 let other_assignee = (!editor.assignee.is_empty()
1052 && !editor.assignee.eq_ignore_ascii_case(&me))
1053 .then(|| name_from_email(&editor.assignee));
1054 let assignee_is_me = !me.is_empty() && editor.assignee.eq_ignore_ascii_case(&me);
1055
1056 let status_chips =
1057 h_flex()
1058 .w_full()
1059 .flex_wrap()
1060 .gap(px(6.))
1061 .children(STATUSES.iter().enumerate().map(|(index, &status)| {
1062 chip(
1063 format!("kvt-board-status-{index}").into(),
1064 self.status_label(status),
1065 editor.status == status,
1066 )
1067 .on_click(cx.listener(move |this, _, _, cx| {
1068 if let Some(editor) = this.editor.as_mut() {
1069 editor.status = status.to_owned();
1070 cx.notify();
1071 }
1072 }))
1073 }));
1074 let assignee_chips = h_flex()
1075 .w_full()
1076 .flex_wrap()
1077 .gap(px(6.))
1078 .child(
1079 chip(
1080 "kvt-board-assignee-none".into(),
1081 tr("kvt.board.assignee_none"),
1082 editor.assignee.is_empty(),
1083 )
1084 .on_click(cx.listener(|this, _, _, cx| {
1085 if let Some(editor) = this.editor.as_mut() {
1086 editor.assignee.clear();
1087 cx.notify();
1088 }
1089 })),
1090 )
1091 .when(!me.is_empty(), |row| {
1092 let me = me.clone();
1093 row.child(
1094 chip(
1095 "kvt-board-assignee-me".into(),
1096 tr("kvt.board.assignee_me"),
1097 assignee_is_me,
1098 )
1099 .on_click(cx.listener(move |this, _, _, cx| {
1100 if let Some(editor) = this.editor.as_mut() {
1101 editor.assignee = me.clone();
1102 cx.notify();
1103 }
1104 })),
1105 )
1106 })
1107 .children(
1108 other_assignee.map(|name| chip("kvt-board-assignee-other".into(), name, true)),
1109 );
1110 let group_chips =
1111 (existing.is_some() && move_groups.len() > 1).then(|| {
1112 h_flex().w_full().flex_wrap().gap(px(6.)).children(
1113 move_groups.iter().enumerate().map(|(index, group)| {
1114 let id = group.id.clone();
1115 let home = home.clone();
1116 chip(
1117 format!("kvt-board-move-{index}").into(),
1118 group.name.clone(),
1119 group.id == target,
1120 )
1121 .on_click(cx.listener(move |this, _, _, cx| {
1122 if let Some(editor) = this.editor.as_mut() {
1123 editor.target_group = (id != home).then(|| id.clone());
1124 cx.notify();
1125 }
1126 }))
1127 }),
1128 )
1129 });
1130 let can_complete = existing
1131 .as_ref()
1132 .is_some_and(|task| task.status != STATUS_DONE && task.can_edit);
1133
1134 let panel = v_flex()
1135 .debug_selector(|| "kvt-board-editor".into())
1136 .w(px(EDITOR_WIDTH))
1137 .max_w(relative(1.))
1138 .max_h(relative(0.92))
1139 .m(px(32.))
1140 .p(px(16.))
1141 .gap(px(10.))
1142 .rounded(px(RADIUS))
1143 .dialog_surface()
1144 .text_color(theme::text())
1145 .occlude()
1146 .child(
1147 h_flex()
1148 .w_full()
1149 .items_center()
1150 .gap(px(12.))
1151 .child(
1152 v_flex()
1153 .flex_1()
1154 .min_w_0()
1155 .child(
1156 div()
1157 .text_size(px(15.))
1158 .font_weight(FontWeight::SEMIBOLD)
1159 .child(title),
1160 )
1161 .when(!detail.is_empty(), |column| {
1162 column.child(
1163 div()
1164 .truncate()
1165 .text_size(px(12.))
1166 .text_color(theme::text_muted())
1167 .child(detail),
1168 )
1169 }),
1170 )
1171 .child(
1172 div()
1173 .id("kvt-board-editor-close")
1174 .size(px(28.))
1175 .flex_none()
1176 .flex()
1177 .items_center()
1178 .justify_center()
1179 .rounded_full()
1180 .cursor_pointer()
1181 .hover(|button| button.bg(theme::popup_hover()))
1182 .on_click(cx.listener(|this, _, _, cx| {
1183 this.editor = None;
1184 cx.notify();
1185 }))
1186 .child(symbol("close", 16., theme::text_muted())),
1187 ),
1188 )
1189 .child(label(tr("kvt.ponos.title")))
1190 .child(
1191 field().child(
1192 div()
1193 .flex_1()
1194 .child(Input::new(&editor.title).appearance(false).bordered(false)),
1195 ),
1196 )
1197 .child(label(tr("kvt.ponos.description")))
1198 .child(Textarea::new(&editor.description))
1199 .child(label(tr("kvt.board.status")))
1200 .child(status_chips)
1201 .child(label(tr("kvt.board.due")))
1202 .child(
1203 field().child(
1204 div()
1205 .flex_1()
1206 .child(Input::new(&editor.due).appearance(false).bordered(false)),
1207 ),
1208 )
1209 .child(label(tr("kvt.board.assignee")))
1210 .child(assignee_chips)
1211 .when_some(group_chips, |panel, chips| {
1212 panel.child(label(tr("kvt.ponos.group"))).child(chips)
1213 })
1214 .children(editor.error.clone().map(|error| {
1215 div()
1216 .text_size(px(13.))
1217 .text_color(theme::red_soft())
1218 .child(error)
1219 }))
1220 .child(
1221 h_flex()
1222 .w_full()
1223 .gap(px(8.))
1224 .items_center()
1225 .children(url.map(|url| {
1226 secondary_button(
1227 "kvt-board-editor-open",
1228 "open_in_new",
1229 tr("kvt.tasks.open_ponos"),
1230 )
1231 .on_click(move |_, _, cx| open_external(&url, cx))
1232 }))
1233 .child(div().flex_1())
1234 .when(can_complete, |row| {
1235 row.child(
1236 secondary_button(
1237 "kvt-board-complete",
1238 "check_circle",
1239 tr("kvt.board.complete"),
1240 )
1241 .on_click(cx.listener(|this, _, _, cx| this.complete_from_editor(cx))),
1242 )
1243 })
1244 .child(
1245 secondary_button("kvt-board-cancel", "close", tr("common.cancel"))
1246 .on_click(cx.listener(|this, _, _, cx| {
1247 this.editor = None;
1248 cx.notify();
1249 })),
1250 )
1251 .when(editable, |row| {
1252 row.child(
1253 primary_button(
1254 "kvt-board-save",
1255 tr(if editor.saving {
1256 "kvt.ponos.saving"
1257 } else {
1258 "kvt.board.save"
1259 }),
1260 )
1261 .on_click(cx.listener(|this, _, _, cx| this.save_editor(cx))),
1262 )
1263 }),
1264 );
1265 Some(
1266 div()
1267 .id("kvt-board-editor-layer")
1268 .on_key_down(cx.listener(|this, event: &KeyDownEvent, _, cx| {
1269 if event.keystroke.key == "escape" {
1270 cx.stop_propagation();
1271 this.editor = None;
1272 cx.notify();
1273 }
1274 }))
1275 .absolute()
1276 .top_0()
1277 .left_0()
1278 .size_full()
1279 .flex()
1280 .items_center()
1281 .justify_center()
1282 .child(
1283 div()
1284 .id("kvt-board-editor-backdrop")
1285 .absolute()
1286 .top_0()
1287 .left_0()
1288 .size_full()
1289 .bg(black().opacity(BACKDROP_OPACITY))
1290 .occlude()
1291 .on_click(cx.listener(|this, _, _, cx| {
1292 this.editor = None;
1293 cx.notify();
1294 })),
1295 )
1296 .child(panel)
1297 .into_any_element(),
1298 )
1299 }
1300}
1301
1302impl Render for PonosBoard {
1303 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1304 let linked = matches!(link(cx), Link::Linked(_));
1305 if !linked && !is_demo(cx) {
1306 // Ontkoppeld: na opnieuw koppelen vers laden, niets van de oude token tonen.
1307 self.nav = Nav::NotLinked;
1308 self.editor = None;
1309 } else if matches!(self.nav, Nav::NotLinked) {
1310 self.reload(cx);
1311 }
1312 let body = match (&self.nav, linked) {
1313 (_, false) => v_flex()
1314 .p(px(PAGE_PADDING))
1315 .max_w(px(EDITOR_WIDTH))
1316 .child(not_linked())
1317 .into_any_element(),
1318 (Nav::NotLinked | Nav::Loading, _) => muted(tr("kvt.card.loading"))
1319 .px(px(PAGE_PADDING))
1320 .into_any_element(),
1321 (Nav::Failed(error), _) => muted(ponos_error(error))
1322 .px(px(PAGE_PADDING))
1323 .into_any_element(),
1324 (Nav::Loaded(_), _) => h_flex()
1325 .flex_1()
1326 .min_h_0()
1327 .w_full()
1328 .child(self.groups_list(cx))
1329 .child(
1330 v_flex()
1331 .flex_1()
1332 .min_w_0()
1333 .h_full()
1334 .child(self.header(cx))
1335 .child(self.columns(cx)),
1336 )
1337 .into_any_element(),
1338 };
1339 let page_title = (!matches!(self.nav, Nav::Loaded(_)) || !linked).then(|| {
1340 h_flex()
1341 .h(px(HEADER_HEIGHT))
1342 .flex_none()
1343 .px(px(PAGE_PADDING))
1344 .items_center()
1345 .child(
1346 div()
1347 .text_size(px(16.))
1348 .font_weight(FontWeight::BOLD)
1349 .text_color(theme::text())
1350 .child(tr("kvt.board.title")),
1351 )
1352 });
1353 v_flex()
1354 .debug_selector(|| KVT_BOARD_TAG.into())
1355 .relative()
1356 .size_full()
1357 .rounded(px(RADIUS))
1358 .bg(theme::surface())
1359 .overflow_hidden()
1360 .children(page_title)
1361 .child(body)
1362 .children(self.editor_layer(cx))
1363 }
1364}
1365
1366#[cfg(test)]
1367mod tests {
1368 use super::pick_group;
1369 use kvt_sleutels::ponos::{PonosGroup, PonosNavigation};
1370
1371 fn group(id: &str) -> PonosGroup {
1372 PonosGroup {
1373 id: id.to_owned(),
1374 name: id.to_owned(),
1375 is_virtual: false,
1376 can_create_tasks: true,
1377 has_task_access: true,
1378 task_count: 0,
1379 }
1380 }
1381
1382 #[test]
1383 fn remembered_group_wins_when_it_still_exists() {
1384 let navigation = PonosNavigation {
1385 groups: vec![group("__my_tasks__"), group("g1")],
1386 ..Default::default()
1387 };
1388 assert_eq!(pick_group(Some("g1"), &navigation).as_deref(), Some("g1"));
1389 assert_eq!(
1390 pick_group(Some("weg"), &navigation).as_deref(),
1391 Some("__my_tasks__")
1392 );
1393 assert_eq!(pick_group(None, &PonosNavigation::default()), None);
1394 }
1395}