//! Ponos: «Taak maken van bericht» (dialoog) en het paneel «Mijn taken». //! //! Upstream-haak voor het paneel: `views/status_menu.rs` (instellingenmenu). use gpui_kit::assets::IconName; use gpui_kit::component::input::{Input, InputState, Textarea, TextareaState}; use gpui_kit::component::menu::{PopupMenu, PopupMenuItem}; use gpui_kit::component::scroll::ScrollableElement as _; use gpui_kit::component::{h_flex, v_flex}; use gpui_kit::prelude::FluentBuilder as _; use gpui_kit::*; use kvt_sleutels::ClientError; use kvt_sleutels::asclepius::{DESCRIPTION_MAX, MessageSource}; use kvt_sleutels::format::iso_date_nl; use kvt_sleutels::ponos::{PonosGroup, PonosTask}; use super::modal::{primary_button, secondary_button}; use super::{ Link, base_url, connect, error_text, forget_token, installed, is_demo, link, notice, open_external, read, token_and_client, update, }; use crate::app_state::AppHandle; use crate::i18n::tr; use crate::runtime; use crate::theme::{self, ElevatedSurface as _}; use crate::views::widgets::symbol; pub const KVT_PONOS_DIALOG_TAG: &str = "kvt-ponos-dialog"; pub const KVT_TASKS_PANEL_TAG: &str = "kvt-tasks-panel"; /// Laatst gekozen Ponos-groep (alleen een id, in de lokale opslag). const GROUP_META_KEY: &str = "kvt.ponos.group"; /// Ponos staat 200 tekens toe in de titel. const TITLE_MAX: usize = 200; const BACKDROP_OPACITY: f32 = 0.55; const PANEL_WIDTH: f32 = 520.; const PANEL_MARGIN: f32 = 32.; const PANEL_RADIUS: f32 = 10.; const PANEL_PADDING: f32 = 16.; const SECTION_GAP: f32 = 12.; const CLOSE_SIZE: f32 = 28.; const CHIP_HEIGHT: f32 = 28.; const FIELD_HEIGHT: f32 = 36.; const ROW_HEIGHT: f32 = 48.; const LIST_MAX_HEIGHT: f32 = 420.; #[derive(Clone)] pub(crate) enum TasksLoad { Loading, Loaded(Vec), Failed(ClientError), } #[derive(Clone)] enum Groups { Loading, Loaded(Vec), Failed(ClientError), } pub struct PonosDialog { source: MessageSource, groups: Groups, group: Option, title: Entity, description: Entity, saving: bool, error: Option, } fn remembered_group(cx: &App) -> Option { let handle = cx.try_global::()?; handle.0.read(cx).store.meta(GROUP_META_KEY).ok().flatten() } fn remember_group(group: &str, cx: &App) { if let Some(handle) = cx.try_global::() { let _ = handle.0.read(cx).store.set_meta(GROUP_META_KEY, group); } } pub(super) fn open_create(source: MessageSource, window: &mut Window, cx: &mut App) { if !installed(cx) { return; } let dialog = cx.new(|cx| PonosDialog::new(source, window, cx)); update(cx, |kvt| kvt.ponos_dialog = Some(dialog.clone())); if is_demo(cx) { dialog.update(cx, |dialog, cx| { dialog.set_groups(Ok(super::demo::ponos_groups()), cx) }); return; } let Some((token, client)) = token_and_client(cx) else { return; }; let loading = runtime::spawn(async move { client.ponos_groups(&token).await }); let weak = dialog.downgrade(); cx.spawn(async move |cx| { let result = loading.await.unwrap_or(Err(ClientError::Unavailable)); cx.update(|cx| { if result == Err(ClientError::Unauthorized) { forget_token(cx); } weak.update(cx, |dialog, cx| dialog.set_groups(result, cx)) .ok(); }); }) .detach(); } fn close_create(cx: &mut App) { update(cx, |kvt| kvt.ponos_dialog = None); } impl PonosDialog { fn new(source: MessageSource, window: &mut Window, cx: &mut Context) -> Self { let title_text = source.title(TITLE_MAX); let description_text = source.description(DESCRIPTION_MAX); let title = cx.new(|cx| { InputState::new(window, cx) .placeholder(tr("kvt.ponos.title")) .default_value(title_text) }); let description = cx.new(|cx| { TextareaState::new(window, cx) .auto_grow(4, 10) .placeholder(tr("kvt.ponos.description")) .default_value(description_text) }); title.update(cx, |input, cx| input.focus(window, cx)); PonosDialog { source, groups: Groups::Loading, group: remembered_group(cx), title, description, saving: false, error: None, } } fn set_groups(&mut self, result: Result, ClientError>, cx: &mut Context) { self.groups = match result { Ok(groups) => { let known = self .group .as_ref() .is_some_and(|chosen| groups.iter().any(|group| &group.id == chosen)); if !known { self.group = (groups.len() == 1).then(|| groups[0].id.clone()); } Groups::Loaded(groups) } Err(error) => Groups::Failed(error), }; cx.notify(); } fn save(&mut self, cx: &mut Context) { if self.saving { return; } let title = self.title.read(cx).value().trim().to_owned(); let description = self.description.read(cx).value().trim().to_owned(); let Some(group) = self.group.clone() else { self.error = Some(tr("kvt.ponos.pick_group")); cx.notify(); return; }; if title.is_empty() || description.is_empty() { self.error = Some(tr("kvt.ponos.fill_in")); cx.notify(); return; } remember_group(&group, cx); if is_demo(cx) { close_create(cx); notice(tr("kvt.ponos.created"), cx); return; } let Some((token, client)) = token_and_client(cx) else { return; }; self.saving = true; self.error = None; cx.notify(); let creating = runtime::spawn(async move { client .ponos_create_task(&token, &group, &title, &description) .await }); cx.spawn(async move |this, cx| { let result = creating.await.unwrap_or(Err(ClientError::Unavailable)); cx.update(|cx| match result { Ok(_) => { close_create(cx); notice(tr("kvt.ponos.created"), cx); refresh_tasks_if_open(cx); } Err(error) => { if error == ClientError::Unauthorized { forget_token(cx); } this.update(cx, |this, cx| { this.saving = false; this.error = Some(ponos_error(&error)); cx.notify(); }) .ok(); } }); }) .detach(); } fn groups(&self, cx: &mut Context) -> AnyElement { if !matches!(link(cx), Link::Linked(_)) { return not_linked().into_any_element(); } match &self.groups { Groups::Loading => muted(tr("kvt.card.loading")).into_any_element(), Groups::Failed(error) => muted(ponos_error(error)).into_any_element(), Groups::Loaded(groups) if groups.is_empty() => { muted(tr("kvt.ponos.no_groups")).into_any_element() } Groups::Loaded(groups) => h_flex() .w_full() .flex_wrap() .gap(px(6.)) .children(groups.iter().enumerate().map(|(index, group)| { let id = group.id.clone(); chip( format!("kvt-ponos-group-{index}").into(), group.name.clone(), self.group.as_deref() == Some(group.id.as_str()), ) .on_click(cx.listener(move |this, _, _, cx| { this.group = Some(id.clone()); this.error = None; cx.notify(); })) })) .into_any_element(), } } } impl Render for PonosDialog { fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { let ready = matches!(self.groups, Groups::Loaded(ref groups) if !groups.is_empty()); let from = if self.source.sender.is_empty() { String::new() } else { format!("{} · {}", self.source.sender, self.source.sent_at) }; layer("kvt-ponos", |cx| close_create(cx)).child( panel(KVT_PONOS_DIALOG_TAG) .child(header(tr("kvt.ponos.dialog_title"), from, |cx| { close_create(cx) })) .child(label(tr("kvt.ponos.group"))) .child(self.groups(cx)) .child(label(tr("kvt.ponos.title"))) .child( field().child( div() .flex_1() .child(Input::new(&self.title).appearance(false).bordered(false)), ), ) .child(label(tr("kvt.ponos.description"))) .child(Textarea::new(&self.description)) .children(self.error.clone().map(|error| { div() .text_size(px(13.)) .text_color(theme::red_soft()) .child(error) })) .child( h_flex() .w_full() .gap(px(8.)) .justify_end() .child( secondary_button("kvt-ponos-cancel", "close", tr("common.cancel")) .on_click(|_, _, cx| close_create(cx)), ) .when(ready, |row| { row.child( primary_button( "kvt-ponos-save", tr(if self.saving { "kvt.ponos.saving" } else { "kvt.ponos.save" }), ) .on_click(cx.listener(|this, _, _, cx| this.save(cx))), ) }), ), ) } } // --- Mijn taken ------------------------------------------------------------- /// Regel «Mijn taken in Ponos» in het instellingenmenu (`…` rechtsboven). pub fn extend_settings_menu(popup: PopupMenu, cx: &App) -> PopupMenu { if !installed(cx) { return popup; } popup.separator().item( PopupMenuItem::new(tr("kvt.tasks.menu")) .icon(IconName::ClipboardCheck) .on_click(|_, _, cx| open_tasks(cx)), ) } pub(crate) fn open_tasks(cx: &mut App) { update(cx, |kvt| kvt.tasks = Some(TasksLoad::Loading)); load_tasks(cx); } fn close_tasks(cx: &mut App) { update(cx, |kvt| kvt.tasks = None); } fn refresh_tasks_if_open(cx: &mut App) { if read(cx, |kvt| kvt.tasks.is_some()).unwrap_or(false) { load_tasks(cx); } } fn load_tasks(cx: &mut App) { if is_demo(cx) { let tasks = read(cx, |kvt| kvt.demo_tasks.clone()).unwrap_or_default(); update(cx, |kvt| kvt.tasks = Some(TasksLoad::Loaded(tasks))); return; } let Some((token, client)) = token_and_client(cx) else { return; }; let loading = runtime::spawn(async move { client.ponos_my_tasks(&token).await }); cx.spawn(async move |cx| { let result = loading.await.unwrap_or(Err(ClientError::Unavailable)); cx.update(|cx| { if result == Err(ClientError::Unauthorized) { forget_token(cx); } let load = match result { Ok(tasks) => TasksLoad::Loaded(tasks), Err(error) => TasksLoad::Failed(error), }; update(cx, |kvt| { if kvt.tasks.is_some() { kvt.tasks = Some(load); } }); }); }) .detach(); } fn complete(task: PonosTask, cx: &mut App) { let remove = |kvt: &mut super::Kvt, id: &str| { if let Some(TasksLoad::Loaded(tasks)) = kvt.tasks.as_mut() { tasks.retain(|task| task.id != id); } kvt.demo_tasks.retain(|task| task.id != id); }; if is_demo(cx) { update(cx, |kvt| remove(kvt, &task.id)); notice(tr("kvt.tasks.completed"), cx); return; } let Some((token, client)) = token_and_client(cx) else { return; }; let (group, id) = (task.group().to_owned(), task.id.clone()); let completing = runtime::spawn({ let id = id.clone(); async move { client.ponos_complete_task(&token, &group, &id).await } }); cx.spawn(async move |cx| { let result = completing.await.unwrap_or(Err(ClientError::Unavailable)); cx.update(|cx| match result { Ok(()) => { update(cx, |kvt| remove(kvt, &id)); notice(tr("kvt.tasks.completed"), cx); } Err(error) => { if error == ClientError::Unauthorized { forget_token(cx); } notice(ponos_error(&error), cx); } }); }) .detach(); } pub fn render_tasks(cx: &App) -> Option { let load = read(cx, |kvt| kvt.tasks.clone()).flatten()?; let body = if !matches!(link(cx), Link::Linked(_)) { not_linked().into_any_element() } else { match load { TasksLoad::Loading => muted(tr("kvt.card.loading")).into_any_element(), TasksLoad::Failed(error) => muted(ponos_error(&error)).into_any_element(), TasksLoad::Loaded(tasks) if tasks.is_empty() => { muted(tr("kvt.tasks.empty")).into_any_element() } TasksLoad::Loaded(tasks) => v_flex() .id("kvt-tasks-list") .w_full() .max_h(px(LIST_MAX_HEIGHT)) .overflow_y_scrollbar() .children( tasks .into_iter() .enumerate() .map(|(index, task)| task_row(index, task)), ) .into_any_element(), } }; let ponos = format!("{}/ponos/", base_url()); Some( layer("kvt-tasks", |cx| close_tasks(cx)) .child( panel(KVT_TASKS_PANEL_TAG) .child(header(tr("kvt.tasks.title"), String::new(), |cx| { close_tasks(cx) })) .child(body) .child( h_flex() .w_full() .gap(px(8.)) .child( secondary_button( "kvt-tasks-open", "open_in_new", tr("kvt.tasks.open_ponos"), ) .on_click(move |_, _, cx| open_external(&ponos, cx)), ) .child( secondary_button( "kvt-tasks-refresh", "refresh", tr("kvt.card.refresh"), ) .on_click(|_, _, cx| open_tasks(cx)), ), ), ) .into_any_element(), ) } fn task_row(index: usize, task: PonosTask) -> AnyElement { let today = chrono::Local::now() .date_naive() .format("%Y-%m-%d") .to_string(); let overdue = !task.due_date.is_empty() && task.due_date.as_str() < today.as_str(); let mut detail = Vec::new(); if !task.home_group_name.is_empty() { detail.push(task.home_group_name.clone()); } if task.status == "in_progress" { detail.push(tr("kvt.tasks.in_progress")); } let due = iso_date_nl(&task.due_date); let url = task.url(&base_url()); let done = task.clone(); h_flex() .id(ElementId::Name(format!("kvt-task-{index}").into())) .w_full() .h(px(ROW_HEIGHT)) .flex_none() .px(px(8.)) .gap(px(10.)) .items_center() .rounded(px(6.)) .cursor_pointer() .hover(|row| row.bg(theme::popup_hover())) .on_click(move |_, _, cx| open_external(&url, cx)) .child( div() .id(ElementId::Name(format!("kvt-task-done-{index}").into())) .size(px(CLOSE_SIZE)) .flex_none() .flex() .items_center() .justify_center() .rounded_full() .hover(|button| button.bg(theme::row_hover())) .on_click(move |_, _, cx| { cx.stop_propagation(); complete(done.clone(), cx); }) .child(symbol("check_circle", 18., theme::text_muted())), ) .child( v_flex() .flex_1() .min_w_0() .child( div() .truncate() .text_size(px(13.)) .text_color(theme::text()) .child(task.title.clone()), ) .when(!detail.is_empty(), |column| { column.child( div() .truncate() .text_size(px(12.)) .text_color(theme::text_muted()) .child(detail.join(" · ")), ) }), ) .children(due.map(|due| { div() .flex_none() .text_size(px(12.)) .text_color(if overdue { theme::red_soft() } else { theme::text_muted() }) .child(due) })) .into_any_element() } // --- gedeelde bouwstenen ---------------------------------------------------- fn ponos_error(error: &ClientError) -> String { match error { ClientError::Forbidden => tr("kvt.ponos.forbidden"), ClientError::NotFound | ClientError::BadRequest => tr("kvt.ponos.failed"), other => error_text(other), } } fn layer(id: &'static str, close: fn(&mut App)) -> Stateful
{ div() .id(SharedString::from(format!("{id}-layer"))) .absolute() .top_0() .left_0() .size_full() .flex() .items_center() .justify_center() .child( div() .id(SharedString::from(format!("{id}-backdrop"))) .absolute() .top_0() .left_0() .size_full() .bg(black().opacity(BACKDROP_OPACITY)) .occlude() .on_click(move |_, _, cx| close(cx)), ) } fn panel(tag: &'static str) -> Div { v_flex() .debug_selector(move || tag.into()) .w(px(PANEL_WIDTH)) .max_w(relative(1.)) .max_h(relative(1.)) .m(px(PANEL_MARGIN)) .p(px(PANEL_PADDING)) .gap(px(SECTION_GAP)) .rounded(px(PANEL_RADIUS)) .dialog_surface() .text_color(theme::text()) .occlude() } fn header(title: String, detail: String, close: fn(&mut App)) -> Div { h_flex() .w_full() .items_center() .gap(px(SECTION_GAP)) .child( v_flex() .flex_1() .min_w_0() .child( div() .text_size(px(15.)) .font_weight(FontWeight::SEMIBOLD) .child(title), ) .when(!detail.is_empty(), |column| { column.child( div() .truncate() .text_size(px(12.)) .text_color(theme::text_muted()) .child(detail), ) }), ) .child( div() .id("kvt-dialog-close") .size(px(CLOSE_SIZE)) .flex_none() .flex() .items_center() .justify_center() .rounded_full() .cursor_pointer() .hover(|button| button.bg(theme::popup_hover())) .on_click(move |_, _, cx| close(cx)) .child(symbol("close", 16., theme::text_muted())), ) } fn label(text: String) -> Div { div() .text_size(px(12.)) .font_weight(FontWeight::SEMIBOLD) .text_color(theme::text_muted()) .child(text) } fn muted(text: String) -> Div { div() .w_full() .py(px(8.)) .text_size(px(13.)) .text_color(theme::text_muted()) .child(text) } fn field() -> Div { h_flex() .w_full() .h(px(FIELD_HEIGHT)) .flex_none() .px(px(10.)) .items_center() .rounded(px(6.)) .bg(theme::popup_hover()) } fn chip(id: SharedString, label: String, selected: bool) -> Stateful
{ h_flex() .id(id) .h(px(CHIP_HEIGHT)) .flex_none() .px(px(12.)) .items_center() .rounded_full() .text_size(px(13.)) .cursor_pointer() .map(|chip| { if selected { chip.bg(theme::accent()) .text_color(theme::on_accent()) .font_weight(FontWeight::SEMIBOLD) } else { chip.bg(theme::popup_hover()) .text_color(theme::text()) .hover(|chip| chip.bg(theme::row_hover())) } }) .child(label) } fn not_linked() -> Div { v_flex() .w_full() .gap(px(8.)) .child(muted(tr("kvt.card.sign_in"))) .child( primary_button("kvt-tasks-connect", tr("kvt.settings.connect")) .self_start() .on_click(|_, _, cx| connect(cx)), ) }