//! Het kaartje onder een bericht met een BC- of sleutels-link. use gpui_kit::component::{h_flex, v_flex}; use gpui_kit::prelude::FluentBuilder as _; use gpui_kit::*; use kvt_sleutels::{CardRef, MAX_CARDS_PER_MESSAGE, parse_card_link}; use super::{Load, cached_card, kind_label, kind_symbol, open_card}; use crate::render::Block; use crate::render::blocks::{Inline, Segment}; use crate::theme; use crate::views::widgets::symbol; const CARD_WIDTH: f32 = 360.; const BADGE_SIZE: f32 = 32.; const BADGE_ICON_SIZE: f32 = 18.; /// Kaart-verwijzingen met hun linktekst, in volgorde, zonder dubbele en zonder /// links in een geciteerd bericht. Hooguit [`MAX_CARDS_PER_MESSAGE`]. pub(crate) fn card_links(blocks: &[Block]) -> Vec<(CardRef, String)> { let mut found: Vec<(CardRef, String)> = Vec::new(); collect(blocks, &mut found); found } fn collect(blocks: &[Block], found: &mut Vec<(CardRef, String)>) { for block in blocks { if found.len() >= MAX_CARDS_PER_MESSAGE { return; } match block { Block::Paragraph(inline) | Block::Heading { inline, .. } => { collect_inline(inline, found) } Block::Quote(children) | Block::Indent { children, .. } => collect(children, found), Block::List { items, .. } => { for item in items { collect(item, found); } } Block::Table { rows, .. } => { for cell in rows.iter().flatten() { collect_inline(&cell.inline, found); } } Block::Reply { .. } | Block::Code { .. } | Block::CodeLine { .. } | Block::Rule | Block::Image { .. } => {} } } } fn collect_inline(inline: &crate::render::blocks::Inline, found: &mut Vec<(CardRef, String)>) { for segment in &inline.segments { if found.len() >= MAX_CARDS_PER_MESSAGE { return; } let Some(reference) = segment.link.as_deref().and_then(parse_card_link) else { continue; }; let text = inline .text .get(segment.range.clone()) .unwrap_or_default() .trim(); match found.iter_mut().find(|(known, _)| { known.kind == reference.kind && known.company == reference.company && known.no == reference.no }) { // Eén link kan in meerdere opgemaakte stukken staan: tekst aanvullen. Some((_, known_text)) if !text.is_empty() && !known_text.contains(text) => { known_text.push(' '); known_text.push_str(text); } Some(_) => {} None => found.push((reference, text.to_owned())), } } } /// De berichttekst zonder de linktekst van links die als kaartje getoond worden /// (KVT-fork). `None` als er geen kaartje is en de tekst dus ongewijzigd blijft. /// Een bericht dat alleen uit die links bestond, geeft een lege lijst: dan is er /// alleen het kaartje. Het bericht zelf blijft ongewijzigd (Teams ziet de link). pub fn blocks_without_card_links(blocks: &[Block], cx: &App) -> Option> { if !cx.has_global::() { return None; } let shown: Vec = card_links(blocks).into_iter().map(|(r, _)| r).collect(); if shown.is_empty() { return None; } Some(strip_blocks(blocks, &shown)) } fn same_card(a: &CardRef, b: &CardRef) -> bool { a.kind == b.kind && a.company == b.company && a.no == b.no } fn strip_blocks(blocks: &[Block], shown: &[CardRef]) -> Vec { let mut out = Vec::new(); for block in blocks { match block { Block::Paragraph(inline) => { let inline = strip_inline(inline, shown); if !inline.is_blank() { out.push(Block::Paragraph(inline)); } } Block::Heading { level, inline } => { let inline = strip_inline(inline, shown); if !inline.is_blank() { out.push(Block::Heading { level: *level, inline, }); } } Block::Quote(children) => { let children = strip_blocks(children, shown); if !children.is_empty() { out.push(Block::Quote(children)); } } Block::Indent { level, children } => { let children = strip_blocks(children, shown); if !children.is_empty() { out.push(Block::Indent { level: *level, children, }); } } Block::List { ordered, start, items, } => { let items: Vec> = items .iter() .map(|item| strip_blocks(item, shown)) .filter(|item| !item.is_empty()) .collect(); if !items.is_empty() { out.push(Block::List { ordered: *ordered, start: *start, items, }); } } Block::Table { header, rows } => { let rows = rows .iter() .map(|row| { row.iter() .map(|cell| { let mut cell = cell.clone(); cell.inline = strip_inline(&cell.inline, shown); cell }) .collect() }) .collect(); out.push(Block::Table { header: *header, rows, }); } other => out.push(other.clone()), } } out } /// Haalt de segmenten weg die naar een getoond kaartje wijzen. Witruimte die er /// daardoor aan het begin, dubbel of aan het eind bij komt te staan, gaat mee. fn strip_inline(inline: &Inline, shown: &[CardRef]) -> Inline { let is_card = |segment: &Segment| { segment .link .as_deref() .and_then(parse_card_link) .is_some_and(|reference| shown.iter().any(|known| same_card(known, &reference))) }; if !inline.segments.iter().any(is_card) { return inline.clone(); } let mut out = Inline::default(); let mut after_removed = true; for segment in &inline.segments { if is_card(segment) { after_removed = true; continue; } let mut text = &inline.text[segment.range.clone()]; let plain = segment.emoji.is_none() && !segment.style.code; let ends_with_space = out.text.is_empty() || out.text.ends_with(char::is_whitespace); if plain && after_removed && ends_with_space { text = text.trim_start(); } after_removed = false; if text.is_empty() { continue; } let start = out.text.len(); out.text.push_str(text); out.segments.push(Segment { range: start..out.text.len(), style: segment.style, link: segment.link.clone(), emoji: segment.emoji.clone(), }); } let trimmed = out.text.trim_end().len(); out.text.truncate(trimmed); out.segments.retain_mut(|segment| { segment.range.end = segment.range.end.min(trimmed); segment.range.start < segment.range.end }); out } /// Omschrijving uit de linktekst: «Werkorder WO2699001 - Onderhoud» → «Onderhoud». /// Een kale URL als tekst geeft niets. pub(crate) fn title_from_anchor(reference: &CardRef, text: &str) -> String { let text = text.trim(); if text.contains("://") { return String::new(); } let prefix = format!("{} {}", reference.kind.label_nl(), reference.no); match text.strip_prefix(&prefix) { Some(rest) => rest.trim_start_matches([' ', '-', '–']).trim().to_owned(), None if text == reference.no => String::new(), None => text.to_owned(), } } pub fn message_cards(blocks: &[Block], id: &str, cx: &App) -> Vec { if !cx.has_global::() { return Vec::new(); } card_links(blocks) .into_iter() .enumerate() .map(|(index, (reference, text))| { card_chip(reference, text, format!("{id}-kvt-{index}"), cx) }) .collect() } fn card_chip(reference: CardRef, text: String, id: String, cx: &App) -> AnyElement { let (title, subtitle) = match cached_card(&reference, cx) { Some(Load::Loaded(card)) => (card.title.clone(), card.subtitle.clone()), _ => (title_from_anchor(&reference, &text), String::new()), }; let heading = format!("{} {}", kind_label(reference.kind), reference.no); let detail = if subtitle.is_empty() { reference.company.clone() } else { format!("{subtitle} · {}", reference.company) }; let kind = reference.kind; h_flex() .id(ElementId::Name(id.into())) .w_full() .max_w(px(CARD_WIDTH)) .gap(px(10.)) .p(px(8.)) .items_center() .rounded(px(10.)) .bg(theme::surface()) .cursor_pointer() .hover(|card| card.bg(theme::row_hover())) .child( div() .size(px(BADGE_SIZE)) .flex_none() .flex() .items_center() .justify_center() .rounded(px(8.)) .bg(theme::accent()) .child(symbol( kind_symbol(kind), BADGE_ICON_SIZE, theme::on_accent(), )), ) .child( v_flex() .flex_1() .min_w_0() .gap(px(1.)) .child( div() .truncate() .text_size(px(11.)) .font_weight(FontWeight::SEMIBOLD) .text_color(theme::text_muted()) .child(heading), ) .when(!title.is_empty(), |column| { column.child( div() .truncate() .text_size(px(13.)) .font_weight(FontWeight::SEMIBOLD) .text_color(theme::text_strong()) .child(title), ) }) .child( div() .truncate() .text_size(px(11.)) .text_color(theme::text_muted()) .child(detail), ), ) .child(symbol("open_in_new", 14., theme::text_muted())) .on_click(move |_, _, cx| { cx.stop_propagation(); open_card(reference.clone(), text.clone(), cx); }) .into_any_element() } #[cfg(test)] mod tests { use super::{card_links, title_from_anchor}; use crate::render::Block; use crate::render::blocks::Inline; use kvt_sleutels::CardKind; use kvt_sleutels::links::bc_url; fn linked(text: &str, url: &str) -> Inline { let mut inline = Inline::plain(text); inline.segments[0].link = Some(url.to_owned()); inline } #[test] fn finds_card_links_but_not_in_quotes_of_replies() { let wo = bc_url(CardKind::Werkorder, "Testbedrijf", "WO2699001", None); let ct = bc_url(CardKind::Contract, "Testbedrijf", "CT2699001", None); let blocks = vec![ Block::Reply { message_id: None, children: vec![Block::Paragraph(linked("oud", &ct))], }, Block::Paragraph(linked("Werkorder WO2699001 - Onderhoud", &wo)), Block::List { ordered: false, start: 1, items: vec![vec![Block::Paragraph(linked("nog eens", &wo))]], }, Block::Paragraph(linked("site", "https://example.com/")), ]; let found = card_links(&blocks); assert_eq!(found.len(), 1); assert_eq!(found[0].0.no, "WO2699001"); assert_eq!(found[0].1, "Werkorder WO2699001 - Onderhoud nog eens"); } #[test] fn title_comes_from_readable_anchor_text() { let reference = kvt_sleutels::parse_card_link(&bc_url( CardKind::Project, "Testbedrijf", "PRJ2699001", None, )) .unwrap(); assert_eq!( title_from_anchor(&reference, "Project PRJ2699001 - Nieuwbouw"), "Nieuwbouw" ); assert_eq!(title_from_anchor(&reference, "Project PRJ2699001"), ""); assert_eq!(title_from_anchor(&reference, "PRJ2699001"), ""); assert_eq!( title_from_anchor(&reference, "https://kvtmd365.kvt.nl/x"), "" ); assert_eq!(title_from_anchor(&reference, "dit project"), "dit project"); } } #[cfg(test)] mod strip_tests { use super::{Block, CardRef, card_links, strip_blocks}; use crate::render::blocks::{Inline, Segment}; use crate::render::blocks::StyleFlags; const WO: &str = "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=Koninklijke%20van%20Twist&page=11333028&filter=%27No.%27%20IS%20%27WO2699001%27"; const COM: &str = "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=Koninklijke%20van%20Twist&page=11332880&filter=%27No.%27%20IS%20%27COM2699001%27"; fn inline(parts: &[(&str, Option<&str>)]) -> Inline { let mut out = Inline::default(); for (text, link) in parts { let start = out.text.len(); out.text.push_str(text); out.segments.push(Segment { range: start..out.text.len(), style: StyleFlags::default(), link: link.map(str::to_owned), emoji: None, }); } out } fn refs(blocks: &[Block]) -> Vec { card_links(blocks).into_iter().map(|(r, _)| r).collect() } #[test] fn a_message_with_only_the_link_shows_no_text() { let blocks = vec![Block::Paragraph(inline(&[( "Werkorder WO2699001 - Onderhoud", Some(WO), )]))]; assert!(strip_blocks(&blocks, &refs(&blocks)).is_empty()); } #[test] fn several_links_with_only_spaces_between_them_show_no_text() { let blocks = vec![Block::Paragraph(inline(&[ ("Werkorder WO2699001", Some(WO)), (" ", None), ("Component COM2699001", Some(COM)), ]))]; assert!(strip_blocks(&blocks, &refs(&blocks)).is_empty()); } #[test] fn other_text_stays_and_only_the_link_text_goes() { let blocks = vec![Block::Paragraph(inline(&[ ("Kun je ", None), ("Werkorder WO2699001", Some(WO)), (" vóór vrijdag bekijken?", None), ]))]; let stripped = strip_blocks(&blocks, &refs(&blocks)); let [Block::Paragraph(text)] = stripped.as_slice() else { panic!("one paragraph expected"); }; assert_eq!(text.text, "Kun je vóór vrijdag bekijken?"); assert!(text.segments.iter().all(|segment| segment.link.is_none())); } #[test] fn a_link_at_the_start_leaves_no_leading_space() { let blocks = vec![Block::Paragraph(inline(&[ ("Werkorder WO2699001", Some(WO)), (" is klaar", None), ]))]; let stripped = strip_blocks(&blocks, &refs(&blocks)); let [Block::Paragraph(text)] = stripped.as_slice() else { panic!("one paragraph expected"); }; assert_eq!(text.text, "is klaar"); assert_eq!(text.segments[0].range, 0..8); } #[test] fn other_links_stay_visible() { let blocks = vec![Block::Paragraph(inline(&[ ("zie ", None), ("Werkorder WO2699001", Some(WO)), (" en ", None), ("de wiki", Some("https://wiki.kvt.nl/x")), ]))]; let stripped = strip_blocks(&blocks, &refs(&blocks)); let [Block::Paragraph(text)] = stripped.as_slice() else { panic!("one paragraph expected"); }; assert_eq!(text.text, "zie en de wiki"); } #[test] fn links_beyond_the_card_limit_stay_in_the_text() { let blocks = vec![Block::Paragraph(inline(&[( "Werkorder WO2699001", Some(WO), )]))]; assert!(strip_blocks(&blocks, &[]).len() == 1); } }