//! Picker in het plusmenu van het opstelvak: project, werkorder of contract zoeken //! en als gewone link met leesbare tekst invoegen. use std::time::Duration; use gpui_kit::component::fluent::{ MENU_ICON_LABEL_GAP, MENU_ICON_SLOT, MENU_ITEM_HEIGHT, MENU_ITEM_PADDING_X, }; use gpui_kit::component::input::{Input, InputEvent, InputState}; 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::links::{anchor_text, bc_url}; use kvt_sleutels::{CardKind, ClientError, SearchResult, parse_card_link}; use super::{ DEFAULT_COMPANY, Link, connect, error_text, forget_token, is_demo, kind_label, kind_symbol, link, read, token_and_client, trusted_link, update, }; use crate::i18n::tr; use crate::runtime; use crate::theme::{self, ElevatedSurface as _}; use crate::views::composer::Composer; use crate::views::widgets::symbol; pub const KVT_PICKER_TAG: &str = "kvt-picker"; pub const KVT_PLUS_ITEM_TAG: &str = "composer-plus/kvt-link"; const SEARCH_DEBOUNCE: Duration = Duration::from_millis(300); const MIN_QUERY: usize = 2; const BACKDROP_OPACITY: f32 = 0.55; const PANEL_WIDTH: f32 = 480.; 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 FIELD_HEIGHT: f32 = 36.; const CHIP_HEIGHT: f32 = 28.; const ROW_HEIGHT: f32 = 44.; const MAX_ROWS: usize = 10; const ITEM_ICON_SIZE: f32 = 20.; #[derive(Clone, PartialEq, Eq)] enum Status { TypeMore, Searching, Done, Failed(ClientError), } pub struct Picker { composer: WeakEntity, kind: CardKind, company: Option, search: Entity, results: Vec, status: Status, highlighted: usize, generation: u64, task: Option>, _subscription: Subscription, } /// Regel in het plusmenu; `None` als de KVT-koppeling niet geladen is. pub fn plus_item( on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static, cx: &App, ) -> Option> { if !super::installed(cx) { return None; } Some( h_flex() .id(KVT_PLUS_ITEM_TAG) .debug_selector(|| KVT_PLUS_ITEM_TAG.into()) .w_full() .h(MENU_ITEM_HEIGHT) .flex_none() .px(MENU_ITEM_PADDING_X) .gap(MENU_ICON_LABEL_GAP) .items_center() .rounded(px(6.)) .cursor_pointer() .hover(|row| row.bg(theme::popup_hover())) .child( div() .size(MENU_ICON_SLOT) .flex_none() .flex() .items_center() .justify_center() .child(symbol("link", ITEM_ICON_SIZE, theme::text_soft())), ) .child( div() .text_size(px(13.)) .text_color(theme::text()) .child(tr("kvt.picker.menu")), ) .on_click(on_click), ) } pub fn open_picker(composer: WeakEntity, window: &mut Window, cx: &mut App) { if !super::installed(cx) { return; } let picker = cx.new(|cx| Picker::new(composer, window, cx)); update(cx, |kvt| kvt.picker = Some(picker)); ensure_companies(cx); } fn close_picker(cx: &mut App) { update(cx, |kvt| kvt.picker = None); } /// Bedrijvenlijst eenmalig ophalen (alleen nodig voor de keuze in de picker). fn ensure_companies(cx: &mut App) { let known = read(cx, |kvt| !kvt.companies.is_empty()).unwrap_or(true); if known || is_demo(cx) { return; } let Some((token, client)) = token_and_client(cx) else { return; }; let loading = runtime::spawn(async move { client.companies(&token).await }); cx.spawn(async move |cx| { if let Ok(Ok(companies)) = loading.await { cx.update(|cx| update(cx, |kvt| kvt.companies = companies)); } }) .detach(); } fn companies(cx: &App) -> Vec { read(cx, |kvt| kvt.companies.clone()).unwrap_or_default() } /// Het gekozen bedrijf, anders het eerste uit Mímir, anders KVT. fn effective_company(chosen: Option<&str>, known: &[String]) -> String { chosen .map(str::to_owned) .or_else(|| { known .iter() .find(|name| name.as_str() == DEFAULT_COMPANY) .cloned() }) .or_else(|| known.first().cloned()) .unwrap_or_else(|| DEFAULT_COMPANY.to_owned()) } /// Link en tekst voor een zoekresultaat. Alleen een BC-link uit Mímir als die /// echt naar de webclient wijst; anders zelf opbouwen. fn link_for(result: &SearchResult, fallback: CardKind) -> (String, String) { let kind = CardKind::from_api_name(&result.kind).unwrap_or(fallback); let url = if trusted_link(&result.bc_url) && parse_card_link(&result.bc_url).is_some() { result.bc_url.clone() } else { bc_url(kind, &result.company, &result.no, None) }; (url, anchor_text(kind, &result.no, Some(&result.title))) } impl Picker { fn new(composer: WeakEntity, window: &mut Window, cx: &mut Context) -> Self { let search = cx.new(|cx| InputState::new(window, cx).placeholder(tr("kvt.picker.search"))); let subscription = cx.subscribe_in(&search, window, Self::on_search_event); search.update(cx, |input, cx| input.focus(window, cx)); Picker { composer, kind: CardKind::Werkorder, company: None, search, results: Vec::new(), status: Status::TypeMore, highlighted: 0, generation: 0, task: None, _subscription: subscription, } } fn on_search_event( &mut self, _: &Entity, event: &InputEvent, window: &mut Window, cx: &mut Context, ) { match event { InputEvent::Change => self.run_search(cx), InputEvent::PressEnter { .. } => self.choose(self.highlighted, window, cx), _ => {} } } fn run_search(&mut self, cx: &mut Context) { self.generation += 1; self.task = None; self.highlighted = 0; let query = self.search.read(cx).value().trim().to_owned(); if query.chars().count() < MIN_QUERY { self.results.clear(); self.status = Status::TypeMore; cx.notify(); return; } let kind = self.kind; let company = effective_company(self.company.as_deref(), &companies(cx)); if is_demo(cx) { self.results = super::demo::search(kind, &company, &query); self.status = Status::Done; cx.notify(); return; } let Some((token, client)) = token_and_client(cx) else { cx.notify(); return; }; self.status = Status::Searching; let generation = self.generation; self.task = Some(cx.spawn(async move |this, cx| { cx.background_executor().timer(SEARCH_DEBOUNCE).await; let searching = runtime::spawn(async move { client.search(&token, kind, &company, &query).await }); let result = searching.await.unwrap_or(Err(ClientError::Unavailable)); this.update(cx, |this, cx| { if this.generation != generation { return; } match result { Ok(results) => { this.results = results.into_iter().take(MAX_ROWS).collect(); this.status = Status::Done; } Err(error) => { if error == ClientError::Unauthorized { forget_token(cx); } this.results.clear(); this.status = Status::Failed(error); } } cx.notify(); }) .ok(); })); cx.notify(); } fn set_kind(&mut self, kind: CardKind, cx: &mut Context) { if self.kind != kind { self.kind = kind; self.run_search(cx); } } fn set_company(&mut self, company: String, cx: &mut Context) { self.company = Some(company); self.run_search(cx); } fn choose(&mut self, index: usize, window: &mut Window, cx: &mut Context) { let Some(result) = self.results.get(index) else { return; }; let (url, text) = link_for(result, self.kind); let composer = self.composer.clone(); close_picker(cx); composer .update(cx, |composer, cx| { composer.insert_kvt_link(&text, &url, window, cx) }) .ok(); } fn on_key_down(&mut self, event: &KeyDownEvent, _: &mut Window, cx: &mut Context) { let count = self.results.len(); match event.keystroke.key.as_str() { "escape" => close_picker(cx), "down" if count > 0 => { self.highlighted = (self.highlighted + 1).min(count - 1); cx.notify(); } "up" if count > 0 => { self.highlighted = self.highlighted.saturating_sub(1); cx.notify(); } _ => {} } } fn header(&self) -> Div { h_flex() .w_full() .items_center() .gap(px(SECTION_GAP)) .child( div() .flex_1() .min_w_0() .text_size(px(15.)) .font_weight(FontWeight::SEMIBOLD) .child(tr("kvt.picker.title")), ) .child( div() .id("kvt-picker-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(|_, _, cx| close_picker(cx)) .child(symbol("close", 16., theme::text_muted())), ) } fn chip(id: SharedString, label: String, selected: bool) -> Stateful
{ h_flex() .id(id) .h(px(CHIP_HEIGHT)) .flex_none() .px(px(12.)) .gap(px(6.)) .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 kind_chips(&self, cx: &mut Context) -> Div { h_flex() .w_full() .flex_wrap() .gap(px(6.)) .children(CardKind::ALL.into_iter().map(|kind| { Self::chip( format!("kvt-picker-kind-{}", kind.api_name()).into(), kind_label(kind), kind == self.kind, ) .on_click(cx.listener(move |this, _, _, cx| this.set_kind(kind, cx))) })) } fn company_chips(&self, cx: &mut Context) -> Option
{ let known = companies(cx); if known.len() < 2 { return None; } let selected = effective_company(self.company.as_deref(), &known); Some( h_flex() .w_full() .flex_wrap() .gap(px(6.)) .children(known.into_iter().enumerate().map(|(index, company)| { let chosen = company == selected; let label = company.clone(); Self::chip(format!("kvt-picker-company-{index}").into(), label, chosen) .on_click( cx.listener(move |this, _, _, cx| { this.set_company(company.clone(), cx) }), ) })), ) } fn field(&self) -> Div { h_flex() .w_full() .h(px(FIELD_HEIGHT)) .flex_none() .px(px(10.)) .gap(px(8.)) .items_center() .rounded(px(6.)) .bg(theme::popup_hover()) .child(symbol("search", 14., theme::text_muted())) .child( div() .flex_1() .child(Input::new(&self.search).appearance(false).bordered(false)), ) } fn status_line(text: String) -> Div { div() .w_full() .py(px(8.)) .text_size(px(13.)) .text_color(theme::text_muted()) .child(text) } fn list(&self, cx: &mut Context) -> AnyElement { if !matches!(link(cx), Link::Linked(_)) { return v_flex() .w_full() .gap(px(8.)) .child(Self::status_line(tr( if matches!(link(cx), Link::Connecting) { "kvt.settings.connecting" } else { "kvt.card.sign_in" }, ))) .child( Self::chip( "kvt-picker-connect".into(), tr("kvt.settings.connect"), true, ) .on_click(|_, _, cx| connect(cx)), ) .into_any_element(); } match &self.status { Status::TypeMore => Self::status_line(tr("kvt.picker.type_more")).into_any_element(), Status::Searching => Self::status_line(tr("kvt.card.loading")).into_any_element(), Status::Failed(error) => Self::status_line(error_text(error)).into_any_element(), Status::Done if self.results.is_empty() => { Self::status_line(tr("kvt.picker.empty")).into_any_element() } Status::Done => { let rows: Vec = self .results .iter() .enumerate() .map(|(index, result)| self.row(index, result, cx)) .collect(); v_flex() .id("kvt-picker-results") .w_full() .max_h(px(ROW_HEIGHT * 6.)) .overflow_y_scrollbar() .children(rows) .into_any_element() } } } fn row(&self, index: usize, result: &SearchResult, cx: &mut Context) -> AnyElement { let kind = CardKind::from_api_name(&result.kind).unwrap_or(self.kind); let subtitle = if result.subtitle.is_empty() { result.no.clone() } else { format!("{} · {}", result.no, result.subtitle) }; h_flex() .id(ElementId::Name(format!("kvt-picker-result-{index}").into())) .w_full() .h(px(ROW_HEIGHT)) .flex_none() .px(px(8.)) .gap(px(10.)) .items_center() .rounded(px(6.)) .cursor_pointer() .when(index == self.highlighted, |row| { row.bg(theme::popup_hover()) }) .hover(|row| row.bg(theme::popup_hover())) .child(symbol(kind_symbol(kind), 18., theme::accent_text())) .child( v_flex() .flex_1() .min_w_0() .child( div() .truncate() .text_size(px(13.)) .text_color(theme::text()) .child(if result.title.is_empty() { result.no.clone() } else { result.title.clone() }), ) .child( div() .truncate() .text_size(px(12.)) .text_color(theme::text_muted()) .child(subtitle), ), ) .on_click(cx.listener(move |this, _, window, cx| this.choose(index, window, cx))) .into_any_element() } } impl Render for Picker { fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { div() .id("kvt-picker-layer") .absolute() .top_0() .left_0() .size_full() .flex() .items_center() .justify_center() .child( div() .id("kvt-picker-backdrop") .absolute() .top_0() .left_0() .size_full() .bg(black().opacity(BACKDROP_OPACITY)) .occlude() .on_click(|_, _, cx| close_picker(cx)), ) .child( v_flex() .debug_selector(|| KVT_PICKER_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() .on_key_down(cx.listener(Self::on_key_down)) .child(self.header()) .child(self.kind_chips(cx)) .children(self.company_chips(cx)) .child(self.field()) .child(self.list(cx)), ) } } #[cfg(test)] mod tests { use kvt_sleutels::links::bc_url; use kvt_sleutels::{CardKind, SearchResult}; use super::{DEFAULT_COMPANY, effective_company, link_for}; #[test] fn company_defaults_to_kvt_then_first_known() { let known = vec!["KVT Germany".to_owned(), DEFAULT_COMPANY.to_owned()]; assert_eq!(effective_company(None, &known), DEFAULT_COMPANY); assert_eq!( effective_company(Some("KVT Germany"), &known), "KVT Germany" ); assert_eq!( effective_company(None, &["Ander bedrijf".to_owned()]), "Ander bedrijf" ); assert_eq!(effective_company(None, &[]), DEFAULT_COMPANY); } #[test] fn inserted_link_is_readable_and_never_points_elsewhere() { let mut result = SearchResult { kind: "werkorder".to_owned(), company: "Testbedrijf".to_owned(), no: "WO2699001".to_owned(), title: "Onderhoud 500 uur".to_owned(), subtitle: String::new(), bc_url: "https://example.com/phish".to_owned(), }; let (url, text) = link_for(&result, CardKind::Project); assert_eq!(text, "Werkorder WO2699001 - Onderhoud 500 uur"); assert_eq!( url, bc_url(CardKind::Werkorder, "Testbedrijf", "WO2699001", None) ); result.bc_url = bc_url( CardKind::Werkorder, "Testbedrijf", "WO2699001", Some("KVTGermanyLive_AAD"), ); assert_eq!(link_for(&result, CardKind::Project).0, result.bc_url); } }