BlueGit

ict rusty-teams

Files

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

tasks.rs

tasks.rs 14.3 KiB Download Raw
1//! Ponos: «Taak maken van bericht» (dialoog) en gedeelde bouwstenen voor het
2//! bord (`board.rs`). Het oude paneel «Mijn taken» (…-menu) is vervangen door
3//! de tegel Ponos in de navigatierail.
4
5use gpui_kit::component::input::{Input, InputState, Textarea, TextareaState};
6use gpui_kit::component::{h_flex, v_flex};
7use gpui_kit::prelude::FluentBuilder as _;
8use gpui_kit::*;
9use kvt_sleutels::ClientError;
10use kvt_sleutels::asclepius::{DESCRIPTION_MAX, MessageSource};
11use kvt_sleutels::ponos::PonosGroup;
12
13use super::modal::{primary_button, secondary_button};
14use super::{
15 Link, connect, error_text, forget_token, installed, is_demo, link, notice, token_and_client,
16 update,
17};
18use crate::app_state::AppHandle;
19use crate::i18n::tr;
20use crate::runtime;
21use crate::theme::{self, ElevatedSurface as _};
22use crate::views::widgets::symbol;
23
24pub const KVT_PONOS_DIALOG_TAG: &str = "kvt-ponos-dialog";
25/// Laatst gekozen Ponos-groep (alleen een id, in de lokale opslag).
26const GROUP_META_KEY: &str = "kvt.ponos.group";
27/// Ponos staat 200 tekens toe in de titel.
28const TITLE_MAX: usize = 200;
29const BACKDROP_OPACITY: f32 = 0.55;
30const PANEL_WIDTH: f32 = 520.;
31const PANEL_MARGIN: f32 = 32.;
32const PANEL_RADIUS: f32 = 10.;
33const PANEL_PADDING: f32 = 16.;
34const SECTION_GAP: f32 = 12.;
35const CLOSE_SIZE: f32 = 28.;
36const CHIP_HEIGHT: f32 = 28.;
37const FIELD_HEIGHT: f32 = 36.;
38
39#[derive(Clone)]
40enum Groups {
41 Loading,
42 Loaded(Vec<PonosGroup>),
43 Failed(ClientError),
44}
45
46pub struct PonosDialog {
47 source: MessageSource,
48 groups: Groups,
49 group: Option<String>,
50 title: Entity<InputState>,
51 description: Entity<TextareaState>,
52 saving: bool,
53 error: Option<String>,
54}
55
56fn remembered_group(cx: &App) -> Option<String> {
57 let handle = cx.try_global::<AppHandle>()?;
58 handle.0.read(cx).store.meta(GROUP_META_KEY).ok().flatten()
59}
60
61fn remember_group(group: &str, cx: &App) {
62 if let Some(handle) = cx.try_global::<AppHandle>() {
63 let _ = handle.0.read(cx).store.set_meta(GROUP_META_KEY, group);
64 }
65}
66
67pub(super) fn open_create(source: MessageSource, window: &mut Window, cx: &mut App) {
68 if !installed(cx) {
69 return;
70 }
71 let dialog = cx.new(|cx| PonosDialog::new(source, window, cx));
72 update(cx, |kvt| kvt.ponos_dialog = Some(dialog.clone()));
73 if is_demo(cx) {
74 dialog.update(cx, |dialog, cx| {
75 dialog.set_groups(Ok(super::demo::ponos_groups()), cx)
76 });
77 return;
78 }
79 let Some((token, client)) = token_and_client(cx) else {
80 return;
81 };
82 let loading = runtime::spawn(async move { client.ponos_groups(&token).await });
83 let weak = dialog.downgrade();
84 cx.spawn(async move |cx| {
85 let result = loading.await.unwrap_or(Err(ClientError::Unavailable));
86 cx.update(|cx| {
87 if result == Err(ClientError::Unauthorized) {
88 forget_token(cx);
89 }
90 weak.update(cx, |dialog, cx| dialog.set_groups(result, cx))
91 .ok();
92 });
93 })
94 .detach();
95}
96
97fn close_create(cx: &mut App) {
98 update(cx, |kvt| kvt.ponos_dialog = None);
99}
100
101impl PonosDialog {
102 fn new(source: MessageSource, window: &mut Window, cx: &mut Context<Self>) -> Self {
103 let title_text = source.title(TITLE_MAX);
104 let description_text = source.description(DESCRIPTION_MAX);
105 let title = cx.new(|cx| {
106 InputState::new(window, cx)
107 .placeholder(tr("kvt.ponos.title"))
108 .default_value(title_text)
109 });
110 let description = cx.new(|cx| {
111 TextareaState::new(window, cx)
112 .auto_grow(4, 10)
113 .placeholder(tr("kvt.ponos.description"))
114 .default_value(description_text)
115 });
116 title.update(cx, |input, cx| input.focus(window, cx));
117 PonosDialog {
118 source,
119 groups: Groups::Loading,
120 group: remembered_group(cx),
121 title,
122 description,
123 saving: false,
124 error: None,
125 }
126 }
127
128 fn set_groups(&mut self, result: Result<Vec<PonosGroup>, ClientError>, cx: &mut Context<Self>) {
129 self.groups = match result {
130 Ok(groups) => {
131 let known = self
132 .group
133 .as_ref()
134 .is_some_and(|chosen| groups.iter().any(|group| &group.id == chosen));
135 if !known {
136 self.group = (groups.len() == 1).then(|| groups[0].id.clone());
137 }
138 Groups::Loaded(groups)
139 }
140 Err(error) => Groups::Failed(error),
141 };
142 cx.notify();
143 }
144
145 fn save(&mut self, cx: &mut Context<Self>) {
146 if self.saving {
147 return;
148 }
149 let title = self.title.read(cx).value().trim().to_owned();
150 let description = self.description.read(cx).value().trim().to_owned();
151 let Some(group) = self.group.clone() else {
152 self.error = Some(tr("kvt.ponos.pick_group"));
153 cx.notify();
154 return;
155 };
156 if title.is_empty() || description.is_empty() {
157 self.error = Some(tr("kvt.ponos.fill_in"));
158 cx.notify();
159 return;
160 }
161 remember_group(&group, cx);
162 if is_demo(cx) {
163 close_create(cx);
164 notice(tr("kvt.ponos.created"), cx);
165 return;
166 }
167 let Some((token, client)) = token_and_client(cx) else {
168 return;
169 };
170 self.saving = true;
171 self.error = None;
172 cx.notify();
173 let creating = runtime::spawn(async move {
174 client
175 .ponos_create_task(&token, &group, &title, &description)
176 .await
177 });
178 cx.spawn(async move |this, cx| {
179 let result = creating.await.unwrap_or(Err(ClientError::Unavailable));
180 cx.update(|cx| match result {
181 Ok(_) => {
182 close_create(cx);
183 notice(tr("kvt.ponos.created"), cx);
184 super::board::refresh_board_if_open(cx);
185 }
186 Err(error) => {
187 if error == ClientError::Unauthorized {
188 forget_token(cx);
189 }
190 this.update(cx, |this, cx| {
191 this.saving = false;
192 this.error = Some(ponos_error(&error));
193 cx.notify();
194 })
195 .ok();
196 }
197 });
198 })
199 .detach();
200 }
201
202 fn groups(&self, cx: &mut Context<Self>) -> AnyElement {
203 if !matches!(link(cx), Link::Linked(_)) {
204 return not_linked().into_any_element();
205 }
206 match &self.groups {
207 Groups::Loading => muted(tr("kvt.card.loading")).into_any_element(),
208 Groups::Failed(error) => muted(ponos_error(error)).into_any_element(),
209 Groups::Loaded(groups) if groups.is_empty() => {
210 muted(tr("kvt.ponos.no_groups")).into_any_element()
211 }
212 Groups::Loaded(groups) => h_flex()
213 .w_full()
214 .flex_wrap()
215 .gap(px(6.))
216 .children(groups.iter().enumerate().map(|(index, group)| {
217 let id = group.id.clone();
218 chip(
219 format!("kvt-ponos-group-{index}").into(),
220 group.name.clone(),
221 self.group.as_deref() == Some(group.id.as_str()),
222 )
223 .on_click(cx.listener(move |this, _, _, cx| {
224 this.group = Some(id.clone());
225 this.error = None;
226 cx.notify();
227 }))
228 }))
229 .into_any_element(),
230 }
231 }
232}
233
234impl Render for PonosDialog {
235 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
236 let ready = matches!(self.groups, Groups::Loaded(ref groups) if !groups.is_empty());
237 let from = if self.source.sender.is_empty() {
238 String::new()
239 } else {
240 format!("{} · {}", self.source.sender, self.source.sent_at)
241 };
242 layer("kvt-ponos", |cx| close_create(cx)).child(
243 panel(KVT_PONOS_DIALOG_TAG)
244 .child(header(tr("kvt.ponos.dialog_title"), from, |cx| {
245 close_create(cx)
246 }))
247 .child(label(tr("kvt.ponos.group")))
248 .child(self.groups(cx))
249 .child(label(tr("kvt.ponos.title")))
250 .child(
251 field().child(
252 div()
253 .flex_1()
254 .child(Input::new(&self.title).appearance(false).bordered(false)),
255 ),
256 )
257 .child(label(tr("kvt.ponos.description")))
258 .child(Textarea::new(&self.description))
259 .children(self.error.clone().map(|error| {
260 div()
261 .text_size(px(13.))
262 .text_color(theme::red_soft())
263 .child(error)
264 }))
265 .child(
266 h_flex()
267 .w_full()
268 .gap(px(8.))
269 .justify_end()
270 .child(
271 secondary_button("kvt-ponos-cancel", "close", tr("common.cancel"))
272 .on_click(|_, _, cx| close_create(cx)),
273 )
274 .when(ready, |row| {
275 row.child(
276 primary_button(
277 "kvt-ponos-save",
278 tr(if self.saving {
279 "kvt.ponos.saving"
280 } else {
281 "kvt.ponos.save"
282 }),
283 )
284 .on_click(cx.listener(|this, _, _, cx| this.save(cx))),
285 )
286 }),
287 ),
288 )
289 }
290}
291
292// --- gedeelde bouwstenen ----------------------------------------------------
293
294pub(super) fn ponos_error(error: &ClientError) -> String {
295 match error {
296 ClientError::Forbidden => tr("kvt.ponos.forbidden"),
297 ClientError::NotFound | ClientError::BadRequest => tr("kvt.ponos.failed"),
298 other => error_text(other),
299 }
300}
301
302fn layer(id: &'static str, close: fn(&mut App)) -> Stateful<Div> {
303 div()
304 .id(SharedString::from(format!("{id}-layer")))
305 .absolute()
306 .top_0()
307 .left_0()
308 .size_full()
309 .flex()
310 .items_center()
311 .justify_center()
312 .child(
313 div()
314 .id(SharedString::from(format!("{id}-backdrop")))
315 .absolute()
316 .top_0()
317 .left_0()
318 .size_full()
319 .bg(black().opacity(BACKDROP_OPACITY))
320 .occlude()
321 .on_click(move |_, _, cx| close(cx)),
322 )
323}
324
325fn panel(tag: &'static str) -> Div {
326 v_flex()
327 .debug_selector(move || tag.into())
328 .w(px(PANEL_WIDTH))
329 .max_w(relative(1.))
330 .max_h(relative(1.))
331 .m(px(PANEL_MARGIN))
332 .p(px(PANEL_PADDING))
333 .gap(px(SECTION_GAP))
334 .rounded(px(PANEL_RADIUS))
335 .dialog_surface()
336 .text_color(theme::text())
337 .occlude()
338}
339
340fn header(title: String, detail: String, close: fn(&mut App)) -> Div {
341 h_flex()
342 .w_full()
343 .items_center()
344 .gap(px(SECTION_GAP))
345 .child(
346 v_flex()
347 .flex_1()
348 .min_w_0()
349 .child(
350 div()
351 .text_size(px(15.))
352 .font_weight(FontWeight::SEMIBOLD)
353 .child(title),
354 )
355 .when(!detail.is_empty(), |column| {
356 column.child(
357 div()
358 .truncate()
359 .text_size(px(12.))
360 .text_color(theme::text_muted())
361 .child(detail),
362 )
363 }),
364 )
365 .child(
366 div()
367 .id("kvt-dialog-close")
368 .size(px(CLOSE_SIZE))
369 .flex_none()
370 .flex()
371 .items_center()
372 .justify_center()
373 .rounded_full()
374 .cursor_pointer()
375 .hover(|button| button.bg(theme::popup_hover()))
376 .on_click(move |_, _, cx| close(cx))
377 .child(symbol("close", 16., theme::text_muted())),
378 )
379}
380
381pub(super) fn label(text: String) -> Div {
382 div()
383 .text_size(px(12.))
384 .font_weight(FontWeight::SEMIBOLD)
385 .text_color(theme::text_muted())
386 .child(text)
387}
388
389pub(super) fn muted(text: String) -> Div {
390 div()
391 .w_full()
392 .py(px(8.))
393 .text_size(px(13.))
394 .text_color(theme::text_muted())
395 .child(text)
396}
397
398pub(super) fn field() -> Div {
399 h_flex()
400 .w_full()
401 .h(px(FIELD_HEIGHT))
402 .flex_none()
403 .px(px(10.))
404 .items_center()
405 .rounded(px(6.))
406 .bg(theme::popup_hover())
407}
408
409pub(super) fn chip(id: SharedString, label: String, selected: bool) -> Stateful<Div> {
410 h_flex()
411 .id(id)
412 .h(px(CHIP_HEIGHT))
413 .flex_none()
414 .px(px(12.))
415 .items_center()
416 .rounded_full()
417 .text_size(px(13.))
418 .cursor_pointer()
419 .map(|chip| {
420 if selected {
421 chip.bg(theme::accent())
422 .text_color(theme::on_accent())
423 .font_weight(FontWeight::SEMIBOLD)
424 } else {
425 chip.bg(theme::popup_hover())
426 .text_color(theme::text())
427 .hover(|chip| chip.bg(theme::row_hover()))
428 }
429 })
430 .child(label)
431}
432
433pub(super) fn not_linked() -> Div {
434 v_flex()
435 .w_full()
436 .gap(px(8.))
437 .child(muted(tr("kvt.card.sign_in")))
438 .child(
439 primary_button("kvt-tasks-connect", tr("kvt.settings.connect"))
440 .self_start()
441 .on_click(|_, _, cx| connect(cx)),
442 )
443}