BlueGit

ict rusty-teams

Files

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

picker.rs

picker.rs 20.0 KiB Download Raw
1//! Picker in het plusmenu van het opstelvak: project, werkorder of contract zoeken
2//! en als gewone link met leesbare tekst invoegen.
3
4use std::time::Duration;
5
6use gpui_kit::component::fluent::{
7 MENU_ICON_LABEL_GAP, MENU_ICON_SLOT, MENU_ITEM_HEIGHT, MENU_ITEM_PADDING_X,
8};
9use gpui_kit::component::input::{Input, InputEvent, InputState};
10use gpui_kit::component::scroll::ScrollableElement as _;
11use gpui_kit::component::{h_flex, v_flex};
12use gpui_kit::prelude::FluentBuilder as _;
13use gpui_kit::*;
14use kvt_sleutels::links::{anchor_text, bc_url};
15use kvt_sleutels::{CardKind, ClientError, SearchResult, parse_card_link};
16
17use super::{
18 DEFAULT_COMPANY, Link, connect, error_text, forget_token, is_demo, kind_label, kind_symbol,
19 link, read, token_and_client, trusted_link, update,
20};
21use crate::i18n::tr;
22use crate::runtime;
23use crate::theme::{self, ElevatedSurface as _};
24use crate::views::composer::Composer;
25use crate::views::widgets::symbol;
26
27pub const KVT_PICKER_TAG: &str = "kvt-picker";
28pub const KVT_PLUS_ITEM_TAG: &str = "composer-plus/kvt-link";
29const SEARCH_DEBOUNCE: Duration = Duration::from_millis(300);
30const MIN_QUERY: usize = 2;
31const BACKDROP_OPACITY: f32 = 0.55;
32const PANEL_WIDTH: f32 = 480.;
33const PANEL_MARGIN: f32 = 32.;
34const PANEL_RADIUS: f32 = 10.;
35const PANEL_PADDING: f32 = 16.;
36const SECTION_GAP: f32 = 12.;
37const CLOSE_SIZE: f32 = 28.;
38const FIELD_HEIGHT: f32 = 36.;
39const CHIP_HEIGHT: f32 = 28.;
40const ROW_HEIGHT: f32 = 44.;
41const MAX_ROWS: usize = 10;
42const ITEM_ICON_SIZE: f32 = 20.;
43
44#[derive(Clone, PartialEq, Eq)]
45enum Status {
46 TypeMore,
47 Searching,
48 Done,
49 Failed(ClientError),
50}
51
52pub struct Picker {
53 composer: WeakEntity<Composer>,
54 kind: CardKind,
55 company: Option<String>,
56 search: Entity<InputState>,
57 results: Vec<SearchResult>,
58 status: Status,
59 highlighted: usize,
60 generation: u64,
61 task: Option<Task<()>>,
62 _subscription: Subscription,
63}
64
65/// Regel in het plusmenu; `None` als de KVT-koppeling niet geladen is.
66pub fn plus_item(
67 on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
68 cx: &App,
69) -> Option<Stateful<Div>> {
70 if !super::installed(cx) {
71 return None;
72 }
73 Some(
74 h_flex()
75 .id(KVT_PLUS_ITEM_TAG)
76 .debug_selector(|| KVT_PLUS_ITEM_TAG.into())
77 .w_full()
78 .h(MENU_ITEM_HEIGHT)
79 .flex_none()
80 .px(MENU_ITEM_PADDING_X)
81 .gap(MENU_ICON_LABEL_GAP)
82 .items_center()
83 .rounded(px(6.))
84 .cursor_pointer()
85 .hover(|row| row.bg(theme::popup_hover()))
86 .child(
87 div()
88 .size(MENU_ICON_SLOT)
89 .flex_none()
90 .flex()
91 .items_center()
92 .justify_center()
93 .child(symbol("link", ITEM_ICON_SIZE, theme::text_soft())),
94 )
95 .child(
96 div()
97 .text_size(px(13.))
98 .text_color(theme::text())
99 .child(tr("kvt.picker.menu")),
100 )
101 .on_click(on_click),
102 )
103}
104
105pub fn open_picker(composer: WeakEntity<Composer>, window: &mut Window, cx: &mut App) {
106 if !super::installed(cx) {
107 return;
108 }
109 let picker = cx.new(|cx| Picker::new(composer, window, cx));
110 update(cx, |kvt| kvt.picker = Some(picker));
111 ensure_companies(cx);
112}
113
114fn close_picker(cx: &mut App) {
115 update(cx, |kvt| kvt.picker = None);
116}
117
118/// Bedrijvenlijst eenmalig ophalen (alleen nodig voor de keuze in de picker).
119fn ensure_companies(cx: &mut App) {
120 let known = read(cx, |kvt| !kvt.companies.is_empty()).unwrap_or(true);
121 if known || is_demo(cx) {
122 return;
123 }
124 let Some((token, client)) = token_and_client(cx) else {
125 return;
126 };
127 let loading = runtime::spawn(async move { client.companies(&token).await });
128 cx.spawn(async move |cx| {
129 if let Ok(Ok(companies)) = loading.await {
130 cx.update(|cx| update(cx, |kvt| kvt.companies = companies));
131 }
132 })
133 .detach();
134}
135
136fn companies(cx: &App) -> Vec<String> {
137 read(cx, |kvt| kvt.companies.clone()).unwrap_or_default()
138}
139
140/// Het gekozen bedrijf, anders het eerste uit Mímir, anders KVT.
141fn effective_company(chosen: Option<&str>, known: &[String]) -> String {
142 chosen
143 .map(str::to_owned)
144 .or_else(|| {
145 known
146 .iter()
147 .find(|name| name.as_str() == DEFAULT_COMPANY)
148 .cloned()
149 })
150 .or_else(|| known.first().cloned())
151 .unwrap_or_else(|| DEFAULT_COMPANY.to_owned())
152}
153
154/// Link en tekst voor een zoekresultaat. Alleen een BC-link uit Mímir als die
155/// echt naar de webclient wijst; anders zelf opbouwen.
156fn link_for(result: &SearchResult, fallback: CardKind) -> (String, String) {
157 let kind = CardKind::from_api_name(&result.kind).unwrap_or(fallback);
158 let url = if trusted_link(&result.bc_url) && parse_card_link(&result.bc_url).is_some() {
159 result.bc_url.clone()
160 } else {
161 bc_url(kind, &result.company, &result.no, None)
162 };
163 (url, anchor_text(kind, &result.no, Some(&result.title)))
164}
165
166impl Picker {
167 fn new(composer: WeakEntity<Composer>, window: &mut Window, cx: &mut Context<Self>) -> Self {
168 let search = cx.new(|cx| InputState::new(window, cx).placeholder(tr("kvt.picker.search")));
169 let subscription = cx.subscribe_in(&search, window, Self::on_search_event);
170 search.update(cx, |input, cx| input.focus(window, cx));
171 Picker {
172 composer,
173 kind: CardKind::Werkorder,
174 company: None,
175 search,
176 results: Vec::new(),
177 status: Status::TypeMore,
178 highlighted: 0,
179 generation: 0,
180 task: None,
181 _subscription: subscription,
182 }
183 }
184
185 fn on_search_event(
186 &mut self,
187 _: &Entity<InputState>,
188 event: &InputEvent,
189 window: &mut Window,
190 cx: &mut Context<Self>,
191 ) {
192 match event {
193 InputEvent::Change => self.run_search(cx),
194 InputEvent::PressEnter { .. } => self.choose(self.highlighted, window, cx),
195 _ => {}
196 }
197 }
198
199 fn run_search(&mut self, cx: &mut Context<Self>) {
200 self.generation += 1;
201 self.task = None;
202 self.highlighted = 0;
203 let query = self.search.read(cx).value().trim().to_owned();
204 if query.chars().count() < MIN_QUERY {
205 self.results.clear();
206 self.status = Status::TypeMore;
207 cx.notify();
208 return;
209 }
210 let kind = self.kind;
211 let company = effective_company(self.company.as_deref(), &companies(cx));
212 if is_demo(cx) {
213 self.results = super::demo::search(kind, &company, &query);
214 self.status = Status::Done;
215 cx.notify();
216 return;
217 }
218 let Some((token, client)) = token_and_client(cx) else {
219 cx.notify();
220 return;
221 };
222 self.status = Status::Searching;
223 let generation = self.generation;
224 self.task = Some(cx.spawn(async move |this, cx| {
225 cx.background_executor().timer(SEARCH_DEBOUNCE).await;
226 let searching =
227 runtime::spawn(async move { client.search(&token, kind, &company, &query).await });
228 let result = searching.await.unwrap_or(Err(ClientError::Unavailable));
229 this.update(cx, |this, cx| {
230 if this.generation != generation {
231 return;
232 }
233 match result {
234 Ok(results) => {
235 this.results = results.into_iter().take(MAX_ROWS).collect();
236 this.status = Status::Done;
237 }
238 Err(error) => {
239 if error == ClientError::Unauthorized {
240 forget_token(cx);
241 }
242 this.results.clear();
243 this.status = Status::Failed(error);
244 }
245 }
246 cx.notify();
247 })
248 .ok();
249 }));
250 cx.notify();
251 }
252
253 fn set_kind(&mut self, kind: CardKind, cx: &mut Context<Self>) {
254 if self.kind != kind {
255 self.kind = kind;
256 self.run_search(cx);
257 }
258 }
259
260 fn set_company(&mut self, company: String, cx: &mut Context<Self>) {
261 self.company = Some(company);
262 self.run_search(cx);
263 }
264
265 fn choose(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
266 let Some(result) = self.results.get(index) else {
267 return;
268 };
269 let (url, text) = link_for(result, self.kind);
270 let composer = self.composer.clone();
271 close_picker(cx);
272 composer
273 .update(cx, |composer, cx| {
274 composer.insert_kvt_link(&text, &url, window, cx)
275 })
276 .ok();
277 }
278
279 fn on_key_down(&mut self, event: &KeyDownEvent, _: &mut Window, cx: &mut Context<Self>) {
280 let count = self.results.len();
281 match event.keystroke.key.as_str() {
282 "escape" => close_picker(cx),
283 "down" if count > 0 => {
284 self.highlighted = (self.highlighted + 1).min(count - 1);
285 cx.notify();
286 }
287 "up" if count > 0 => {
288 self.highlighted = self.highlighted.saturating_sub(1);
289 cx.notify();
290 }
291 _ => {}
292 }
293 }
294
295 fn header(&self) -> Div {
296 h_flex()
297 .w_full()
298 .items_center()
299 .gap(px(SECTION_GAP))
300 .child(
301 div()
302 .flex_1()
303 .min_w_0()
304 .text_size(px(15.))
305 .font_weight(FontWeight::SEMIBOLD)
306 .child(tr("kvt.picker.title")),
307 )
308 .child(
309 div()
310 .id("kvt-picker-close")
311 .size(px(CLOSE_SIZE))
312 .flex_none()
313 .flex()
314 .items_center()
315 .justify_center()
316 .rounded_full()
317 .cursor_pointer()
318 .hover(|button| button.bg(theme::popup_hover()))
319 .on_click(|_, _, cx| close_picker(cx))
320 .child(symbol("close", 16., theme::text_muted())),
321 )
322 }
323
324 fn chip(id: SharedString, label: String, selected: bool) -> Stateful<Div> {
325 h_flex()
326 .id(id)
327 .h(px(CHIP_HEIGHT))
328 .flex_none()
329 .px(px(12.))
330 .gap(px(6.))
331 .items_center()
332 .rounded_full()
333 .text_size(px(13.))
334 .cursor_pointer()
335 .map(|chip| {
336 if selected {
337 chip.bg(theme::accent())
338 .text_color(theme::on_accent())
339 .font_weight(FontWeight::SEMIBOLD)
340 } else {
341 chip.bg(theme::popup_hover())
342 .text_color(theme::text())
343 .hover(|chip| chip.bg(theme::row_hover()))
344 }
345 })
346 .child(label)
347 }
348
349 fn kind_chips(&self, cx: &mut Context<Self>) -> Div {
350 h_flex()
351 .w_full()
352 .flex_wrap()
353 .gap(px(6.))
354 .children(CardKind::ALL.into_iter().map(|kind| {
355 Self::chip(
356 format!("kvt-picker-kind-{}", kind.api_name()).into(),
357 kind_label(kind),
358 kind == self.kind,
359 )
360 .on_click(cx.listener(move |this, _, _, cx| this.set_kind(kind, cx)))
361 }))
362 }
363
364 fn company_chips(&self, cx: &mut Context<Self>) -> Option<Div> {
365 let known = companies(cx);
366 if known.len() < 2 {
367 return None;
368 }
369 let selected = effective_company(self.company.as_deref(), &known);
370 Some(
371 h_flex()
372 .w_full()
373 .flex_wrap()
374 .gap(px(6.))
375 .children(known.into_iter().enumerate().map(|(index, company)| {
376 let chosen = company == selected;
377 let label = company.clone();
378 Self::chip(format!("kvt-picker-company-{index}").into(), label, chosen)
379 .on_click(
380 cx.listener(move |this, _, _, cx| {
381 this.set_company(company.clone(), cx)
382 }),
383 )
384 })),
385 )
386 }
387
388 fn field(&self) -> Div {
389 h_flex()
390 .w_full()
391 .h(px(FIELD_HEIGHT))
392 .flex_none()
393 .px(px(10.))
394 .gap(px(8.))
395 .items_center()
396 .rounded(px(6.))
397 .bg(theme::popup_hover())
398 .child(symbol("search", 14., theme::text_muted()))
399 .child(
400 div()
401 .flex_1()
402 .child(Input::new(&self.search).appearance(false).bordered(false)),
403 )
404 }
405
406 fn status_line(text: String) -> Div {
407 div()
408 .w_full()
409 .py(px(8.))
410 .text_size(px(13.))
411 .text_color(theme::text_muted())
412 .child(text)
413 }
414
415 fn list(&self, cx: &mut Context<Self>) -> AnyElement {
416 if !matches!(link(cx), Link::Linked(_)) {
417 return v_flex()
418 .w_full()
419 .gap(px(8.))
420 .child(Self::status_line(tr(
421 if matches!(link(cx), Link::Connecting) {
422 "kvt.settings.connecting"
423 } else {
424 "kvt.card.sign_in"
425 },
426 )))
427 .child(
428 Self::chip(
429 "kvt-picker-connect".into(),
430 tr("kvt.settings.connect"),
431 true,
432 )
433 .on_click(|_, _, cx| connect(cx)),
434 )
435 .into_any_element();
436 }
437 match &self.status {
438 Status::TypeMore => Self::status_line(tr("kvt.picker.type_more")).into_any_element(),
439 Status::Searching => Self::status_line(tr("kvt.card.loading")).into_any_element(),
440 Status::Failed(error) => Self::status_line(error_text(error)).into_any_element(),
441 Status::Done if self.results.is_empty() => {
442 Self::status_line(tr("kvt.picker.empty")).into_any_element()
443 }
444 Status::Done => {
445 let rows: Vec<AnyElement> = self
446 .results
447 .iter()
448 .enumerate()
449 .map(|(index, result)| self.row(index, result, cx))
450 .collect();
451 v_flex()
452 .id("kvt-picker-results")
453 .w_full()
454 .max_h(px(ROW_HEIGHT * 6.))
455 .overflow_y_scrollbar()
456 .children(rows)
457 .into_any_element()
458 }
459 }
460 }
461
462 fn row(&self, index: usize, result: &SearchResult, cx: &mut Context<Self>) -> AnyElement {
463 let kind = CardKind::from_api_name(&result.kind).unwrap_or(self.kind);
464 let subtitle = if result.subtitle.is_empty() {
465 result.no.clone()
466 } else {
467 format!("{} · {}", result.no, result.subtitle)
468 };
469 h_flex()
470 .id(ElementId::Name(format!("kvt-picker-result-{index}").into()))
471 .w_full()
472 .h(px(ROW_HEIGHT))
473 .flex_none()
474 .px(px(8.))
475 .gap(px(10.))
476 .items_center()
477 .rounded(px(6.))
478 .cursor_pointer()
479 .when(index == self.highlighted, |row| {
480 row.bg(theme::popup_hover())
481 })
482 .hover(|row| row.bg(theme::popup_hover()))
483 .child(symbol(kind_symbol(kind), 18., theme::accent_text()))
484 .child(
485 v_flex()
486 .flex_1()
487 .min_w_0()
488 .child(
489 div()
490 .truncate()
491 .text_size(px(13.))
492 .text_color(theme::text())
493 .child(if result.title.is_empty() {
494 result.no.clone()
495 } else {
496 result.title.clone()
497 }),
498 )
499 .child(
500 div()
501 .truncate()
502 .text_size(px(12.))
503 .text_color(theme::text_muted())
504 .child(subtitle),
505 ),
506 )
507 .on_click(cx.listener(move |this, _, window, cx| this.choose(index, window, cx)))
508 .into_any_element()
509 }
510}
511
512impl Render for Picker {
513 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
514 div()
515 .id("kvt-picker-layer")
516 .absolute()
517 .top_0()
518 .left_0()
519 .size_full()
520 .flex()
521 .items_center()
522 .justify_center()
523 .child(
524 div()
525 .id("kvt-picker-backdrop")
526 .absolute()
527 .top_0()
528 .left_0()
529 .size_full()
530 .bg(black().opacity(BACKDROP_OPACITY))
531 .occlude()
532 .on_click(|_, _, cx| close_picker(cx)),
533 )
534 .child(
535 v_flex()
536 .debug_selector(|| KVT_PICKER_TAG.into())
537 .w(px(PANEL_WIDTH))
538 .max_w(relative(1.))
539 .max_h(relative(1.))
540 .m(px(PANEL_MARGIN))
541 .p(px(PANEL_PADDING))
542 .gap(px(SECTION_GAP))
543 .rounded(px(PANEL_RADIUS))
544 .dialog_surface()
545 .text_color(theme::text())
546 .occlude()
547 .on_key_down(cx.listener(Self::on_key_down))
548 .child(self.header())
549 .child(self.kind_chips(cx))
550 .children(self.company_chips(cx))
551 .child(self.field())
552 .child(self.list(cx)),
553 )
554 }
555}
556
557#[cfg(test)]
558mod tests {
559 use kvt_sleutels::links::bc_url;
560 use kvt_sleutels::{CardKind, SearchResult};
561
562 use super::{DEFAULT_COMPANY, effective_company, link_for};
563
564 #[test]
565 fn company_defaults_to_kvt_then_first_known() {
566 let known = vec!["KVT Germany".to_owned(), DEFAULT_COMPANY.to_owned()];
567 assert_eq!(effective_company(None, &known), DEFAULT_COMPANY);
568 assert_eq!(
569 effective_company(Some("KVT Germany"), &known),
570 "KVT Germany"
571 );
572 assert_eq!(
573 effective_company(None, &["Ander bedrijf".to_owned()]),
574 "Ander bedrijf"
575 );
576 assert_eq!(effective_company(None, &[]), DEFAULT_COMPANY);
577 }
578
579 #[test]
580 fn inserted_link_is_readable_and_never_points_elsewhere() {
581 let mut result = SearchResult {
582 kind: "werkorder".to_owned(),
583 company: "Testbedrijf".to_owned(),
584 no: "WO2699001".to_owned(),
585 title: "Onderhoud 500 uur".to_owned(),
586 subtitle: String::new(),
587 bc_url: "https://example.com/phish".to_owned(),
588 };
589 let (url, text) = link_for(&result, CardKind::Project);
590 assert_eq!(text, "Werkorder WO2699001 - Onderhoud 500 uur");
591 assert_eq!(
592 url,
593 bc_url(CardKind::Werkorder, "Testbedrijf", "WO2699001", None)
594 );
595 result.bc_url = bc_url(
596 CardKind::Werkorder,
597 "Testbedrijf",
598 "WO2699001",
599 Some("KVTGermanyLive_AAD"),
600 );
601 assert_eq!(link_for(&result, CardKind::Project).0, result.bc_url);
602 }
603}