BlueGit

ict rusty-teams

Files

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

card.rs

card.rs 16.7 KiB Download Raw
1//! Het kaartje onder een bericht met een BC- of sleutels-link.
2
3use gpui_kit::component::{h_flex, v_flex};
4use gpui_kit::prelude::FluentBuilder as _;
5use gpui_kit::*;
6use kvt_sleutels::{CardRef, MAX_CARDS_PER_MESSAGE, parse_card_link};
7
8use super::{Load, cached_card, kind_label, kind_symbol, open_card};
9use crate::render::Block;
10use crate::render::blocks::{Inline, Segment};
11use crate::theme;
12use crate::views::widgets::symbol;
13
14const CARD_WIDTH: f32 = 360.;
15const BADGE_SIZE: f32 = 32.;
16const BADGE_ICON_SIZE: f32 = 18.;
17
18/// Kaart-verwijzingen met hun linktekst, in volgorde, zonder dubbele en zonder
19/// links in een geciteerd bericht. Hooguit [`MAX_CARDS_PER_MESSAGE`].
20pub(crate) fn card_links(blocks: &[Block]) -> Vec<(CardRef, String)> {
21 let mut found: Vec<(CardRef, String)> = Vec::new();
22 collect(blocks, &mut found);
23 found
24}
25
26fn collect(blocks: &[Block], found: &mut Vec<(CardRef, String)>) {
27 for block in blocks {
28 if found.len() >= MAX_CARDS_PER_MESSAGE {
29 return;
30 }
31 match block {
32 Block::Paragraph(inline) | Block::Heading { inline, .. } => {
33 collect_inline(inline, found)
34 }
35 Block::Quote(children) | Block::Indent { children, .. } => collect(children, found),
36 Block::List { items, .. } => {
37 for item in items {
38 collect(item, found);
39 }
40 }
41 Block::Table { rows, .. } => {
42 for cell in rows.iter().flatten() {
43 collect_inline(&cell.inline, found);
44 }
45 }
46 Block::Reply { .. }
47 | Block::Code { .. }
48 | Block::CodeLine { .. }
49 | Block::Rule
50 | Block::Image { .. } => {}
51 }
52 }
53}
54
55fn collect_inline(inline: &crate::render::blocks::Inline, found: &mut Vec<(CardRef, String)>) {
56 for segment in &inline.segments {
57 if found.len() >= MAX_CARDS_PER_MESSAGE {
58 return;
59 }
60 let Some(reference) = segment.link.as_deref().and_then(parse_card_link) else {
61 continue;
62 };
63 let text = inline
64 .text
65 .get(segment.range.clone())
66 .unwrap_or_default()
67 .trim();
68 match found.iter_mut().find(|(known, _)| {
69 known.kind == reference.kind
70 && known.company == reference.company
71 && known.no == reference.no
72 }) {
73 // Eén link kan in meerdere opgemaakte stukken staan: tekst aanvullen.
74 Some((_, known_text)) if !text.is_empty() && !known_text.contains(text) => {
75 known_text.push(' ');
76 known_text.push_str(text);
77 }
78 Some(_) => {}
79 None => found.push((reference, text.to_owned())),
80 }
81 }
82}
83
84/// De berichttekst zonder de linktekst van links die als kaartje getoond worden
85/// (KVT-fork). `None` als er geen kaartje is en de tekst dus ongewijzigd blijft.
86/// Een bericht dat alleen uit die links bestond, geeft een lege lijst: dan is er
87/// alleen het kaartje. Het bericht zelf blijft ongewijzigd (Teams ziet de link).
88pub fn blocks_without_card_links(blocks: &[Block], cx: &App) -> Option<Vec<Block>> {
89 if !cx.has_global::<super::Kvt>() {
90 return None;
91 }
92 let shown: Vec<CardRef> = card_links(blocks).into_iter().map(|(r, _)| r).collect();
93 if shown.is_empty() {
94 return None;
95 }
96 Some(strip_blocks(blocks, &shown))
97}
98
99fn same_card(a: &CardRef, b: &CardRef) -> bool {
100 a.kind == b.kind && a.company == b.company && a.no == b.no
101}
102
103fn strip_blocks(blocks: &[Block], shown: &[CardRef]) -> Vec<Block> {
104 let mut out = Vec::new();
105 for block in blocks {
106 match block {
107 Block::Paragraph(inline) => {
108 let inline = strip_inline(inline, shown);
109 if !inline.is_blank() {
110 out.push(Block::Paragraph(inline));
111 }
112 }
113 Block::Heading { level, inline } => {
114 let inline = strip_inline(inline, shown);
115 if !inline.is_blank() {
116 out.push(Block::Heading {
117 level: *level,
118 inline,
119 });
120 }
121 }
122 Block::Quote(children) => {
123 let children = strip_blocks(children, shown);
124 if !children.is_empty() {
125 out.push(Block::Quote(children));
126 }
127 }
128 Block::Indent { level, children } => {
129 let children = strip_blocks(children, shown);
130 if !children.is_empty() {
131 out.push(Block::Indent {
132 level: *level,
133 children,
134 });
135 }
136 }
137 Block::List {
138 ordered,
139 start,
140 items,
141 } => {
142 let items: Vec<Vec<Block>> = items
143 .iter()
144 .map(|item| strip_blocks(item, shown))
145 .filter(|item| !item.is_empty())
146 .collect();
147 if !items.is_empty() {
148 out.push(Block::List {
149 ordered: *ordered,
150 start: *start,
151 items,
152 });
153 }
154 }
155 Block::Table { header, rows } => {
156 let rows = rows
157 .iter()
158 .map(|row| {
159 row.iter()
160 .map(|cell| {
161 let mut cell = cell.clone();
162 cell.inline = strip_inline(&cell.inline, shown);
163 cell
164 })
165 .collect()
166 })
167 .collect();
168 out.push(Block::Table {
169 header: *header,
170 rows,
171 });
172 }
173 other => out.push(other.clone()),
174 }
175 }
176 out
177}
178
179/// Haalt de segmenten weg die naar een getoond kaartje wijzen. Witruimte die er
180/// daardoor aan het begin, dubbel of aan het eind bij komt te staan, gaat mee.
181fn strip_inline(inline: &Inline, shown: &[CardRef]) -> Inline {
182 let is_card = |segment: &Segment| {
183 segment
184 .link
185 .as_deref()
186 .and_then(parse_card_link)
187 .is_some_and(|reference| shown.iter().any(|known| same_card(known, &reference)))
188 };
189 if !inline.segments.iter().any(is_card) {
190 return inline.clone();
191 }
192 let mut out = Inline::default();
193 let mut after_removed = true;
194 for segment in &inline.segments {
195 if is_card(segment) {
196 after_removed = true;
197 continue;
198 }
199 let mut text = &inline.text[segment.range.clone()];
200 let plain = segment.emoji.is_none() && !segment.style.code;
201 let ends_with_space = out.text.is_empty() || out.text.ends_with(char::is_whitespace);
202 if plain && after_removed && ends_with_space {
203 text = text.trim_start();
204 }
205 after_removed = false;
206 if text.is_empty() {
207 continue;
208 }
209 let start = out.text.len();
210 out.text.push_str(text);
211 out.segments.push(Segment {
212 range: start..out.text.len(),
213 style: segment.style,
214 link: segment.link.clone(),
215 emoji: segment.emoji.clone(),
216 });
217 }
218 let trimmed = out.text.trim_end().len();
219 out.text.truncate(trimmed);
220 out.segments.retain_mut(|segment| {
221 segment.range.end = segment.range.end.min(trimmed);
222 segment.range.start < segment.range.end
223 });
224 out
225}
226
227/// Omschrijving uit de linktekst: «Werkorder WO2699001 - Onderhoud» → «Onderhoud».
228/// Een kale URL als tekst geeft niets.
229pub(crate) fn title_from_anchor(reference: &CardRef, text: &str) -> String {
230 let text = text.trim();
231 if text.contains("://") {
232 return String::new();
233 }
234 let prefix = format!("{} {}", reference.kind.label_nl(), reference.no);
235 match text.strip_prefix(&prefix) {
236 Some(rest) => rest.trim_start_matches([' ', '-', '–']).trim().to_owned(),
237 None if text == reference.no => String::new(),
238 None => text.to_owned(),
239 }
240}
241
242pub fn message_cards(blocks: &[Block], id: &str, cx: &App) -> Vec<AnyElement> {
243 if !cx.has_global::<super::Kvt>() {
244 return Vec::new();
245 }
246 card_links(blocks)
247 .into_iter()
248 .enumerate()
249 .map(|(index, (reference, text))| {
250 card_chip(reference, text, format!("{id}-kvt-{index}"), cx)
251 })
252 .collect()
253}
254
255fn card_chip(reference: CardRef, text: String, id: String, cx: &App) -> AnyElement {
256 let (title, subtitle) = match cached_card(&reference, cx) {
257 Some(Load::Loaded(card)) => (card.title.clone(), card.subtitle.clone()),
258 _ => (title_from_anchor(&reference, &text), String::new()),
259 };
260 let heading = format!("{} {}", kind_label(reference.kind), reference.no);
261 let detail = if subtitle.is_empty() {
262 reference.company.clone()
263 } else {
264 format!("{subtitle} · {}", reference.company)
265 };
266 let kind = reference.kind;
267 h_flex()
268 .id(ElementId::Name(id.into()))
269 .w_full()
270 .max_w(px(CARD_WIDTH))
271 .gap(px(10.))
272 .p(px(8.))
273 .items_center()
274 .rounded(px(10.))
275 .bg(theme::surface())
276 .cursor_pointer()
277 .hover(|card| card.bg(theme::row_hover()))
278 .child(
279 div()
280 .size(px(BADGE_SIZE))
281 .flex_none()
282 .flex()
283 .items_center()
284 .justify_center()
285 .rounded(px(8.))
286 .bg(theme::accent())
287 .child(symbol(
288 kind_symbol(kind),
289 BADGE_ICON_SIZE,
290 theme::on_accent(),
291 )),
292 )
293 .child(
294 v_flex()
295 .flex_1()
296 .min_w_0()
297 .gap(px(1.))
298 .child(
299 div()
300 .truncate()
301 .text_size(px(11.))
302 .font_weight(FontWeight::SEMIBOLD)
303 .text_color(theme::text_muted())
304 .child(heading),
305 )
306 .when(!title.is_empty(), |column| {
307 column.child(
308 div()
309 .truncate()
310 .text_size(px(13.))
311 .font_weight(FontWeight::SEMIBOLD)
312 .text_color(theme::text_strong())
313 .child(title),
314 )
315 })
316 .child(
317 div()
318 .truncate()
319 .text_size(px(11.))
320 .text_color(theme::text_muted())
321 .child(detail),
322 ),
323 )
324 .child(symbol("open_in_new", 14., theme::text_muted()))
325 .on_click(move |_, _, cx| {
326 cx.stop_propagation();
327 open_card(reference.clone(), text.clone(), cx);
328 })
329 .into_any_element()
330}
331
332#[cfg(test)]
333mod tests {
334 use super::{card_links, title_from_anchor};
335 use crate::render::Block;
336 use crate::render::blocks::Inline;
337 use kvt_sleutels::CardKind;
338 use kvt_sleutels::links::bc_url;
339
340 fn linked(text: &str, url: &str) -> Inline {
341 let mut inline = Inline::plain(text);
342 inline.segments[0].link = Some(url.to_owned());
343 inline
344 }
345
346 #[test]
347 fn finds_card_links_but_not_in_quotes_of_replies() {
348 let wo = bc_url(CardKind::Werkorder, "Testbedrijf", "WO2699001", None);
349 let ct = bc_url(CardKind::Contract, "Testbedrijf", "CT2699001", None);
350 let blocks = vec![
351 Block::Reply {
352 message_id: None,
353 children: vec![Block::Paragraph(linked("oud", &ct))],
354 },
355 Block::Paragraph(linked("Werkorder WO2699001 - Onderhoud", &wo)),
356 Block::List {
357 ordered: false,
358 start: 1,
359 items: vec![vec![Block::Paragraph(linked("nog eens", &wo))]],
360 },
361 Block::Paragraph(linked("site", "https://example.com/")),
362 ];
363 let found = card_links(&blocks);
364 assert_eq!(found.len(), 1);
365 assert_eq!(found[0].0.no, "WO2699001");
366 assert_eq!(found[0].1, "Werkorder WO2699001 - Onderhoud nog eens");
367 }
368
369 #[test]
370 fn title_comes_from_readable_anchor_text() {
371 let reference = kvt_sleutels::parse_card_link(&bc_url(
372 CardKind::Project,
373 "Testbedrijf",
374 "PRJ2699001",
375 None,
376 ))
377 .unwrap();
378 assert_eq!(
379 title_from_anchor(&reference, "Project PRJ2699001 - Nieuwbouw"),
380 "Nieuwbouw"
381 );
382 assert_eq!(title_from_anchor(&reference, "Project PRJ2699001"), "");
383 assert_eq!(title_from_anchor(&reference, "PRJ2699001"), "");
384 assert_eq!(
385 title_from_anchor(&reference, "https://kvtmd365.kvt.nl/x"),
386 ""
387 );
388 assert_eq!(title_from_anchor(&reference, "dit project"), "dit project");
389 }
390}
391
392#[cfg(test)]
393mod strip_tests {
394 use super::{Block, CardRef, card_links, strip_blocks};
395 use crate::render::blocks::{Inline, Segment};
396 use crate::render::blocks::StyleFlags;
397
398 const WO: &str = "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=Koninklijke%20van%20Twist&page=11333028&filter=%27No.%27%20IS%20%27WO2699001%27";
399 const COM: &str = "https://kvtmd365.kvt.nl/KVTMDLive_AAD/?company=Koninklijke%20van%20Twist&page=11332880&filter=%27No.%27%20IS%20%27COM2699001%27";
400
401 fn inline(parts: &[(&str, Option<&str>)]) -> Inline {
402 let mut out = Inline::default();
403 for (text, link) in parts {
404 let start = out.text.len();
405 out.text.push_str(text);
406 out.segments.push(Segment {
407 range: start..out.text.len(),
408 style: StyleFlags::default(),
409 link: link.map(str::to_owned),
410 emoji: None,
411 });
412 }
413 out
414 }
415
416 fn refs(blocks: &[Block]) -> Vec<CardRef> {
417 card_links(blocks).into_iter().map(|(r, _)| r).collect()
418 }
419
420 #[test]
421 fn a_message_with_only_the_link_shows_no_text() {
422 let blocks = vec![Block::Paragraph(inline(&[(
423 "Werkorder WO2699001 - Onderhoud",
424 Some(WO),
425 )]))];
426 assert!(strip_blocks(&blocks, &refs(&blocks)).is_empty());
427 }
428
429 #[test]
430 fn several_links_with_only_spaces_between_them_show_no_text() {
431 let blocks = vec![Block::Paragraph(inline(&[
432 ("Werkorder WO2699001", Some(WO)),
433 (" ", None),
434 ("Component COM2699001", Some(COM)),
435 ]))];
436 assert!(strip_blocks(&blocks, &refs(&blocks)).is_empty());
437 }
438
439 #[test]
440 fn other_text_stays_and_only_the_link_text_goes() {
441 let blocks = vec![Block::Paragraph(inline(&[
442 ("Kun je ", None),
443 ("Werkorder WO2699001", Some(WO)),
444 (" vóór vrijdag bekijken?", None),
445 ]))];
446 let stripped = strip_blocks(&blocks, &refs(&blocks));
447 let [Block::Paragraph(text)] = stripped.as_slice() else {
448 panic!("one paragraph expected");
449 };
450 assert_eq!(text.text, "Kun je vóór vrijdag bekijken?");
451 assert!(text.segments.iter().all(|segment| segment.link.is_none()));
452 }
453
454 #[test]
455 fn a_link_at_the_start_leaves_no_leading_space() {
456 let blocks = vec![Block::Paragraph(inline(&[
457 ("Werkorder WO2699001", Some(WO)),
458 (" is klaar", None),
459 ]))];
460 let stripped = strip_blocks(&blocks, &refs(&blocks));
461 let [Block::Paragraph(text)] = stripped.as_slice() else {
462 panic!("one paragraph expected");
463 };
464 assert_eq!(text.text, "is klaar");
465 assert_eq!(text.segments[0].range, 0..8);
466 }
467
468 #[test]
469 fn other_links_stay_visible() {
470 let blocks = vec![Block::Paragraph(inline(&[
471 ("zie ", None),
472 ("Werkorder WO2699001", Some(WO)),
473 (" en ", None),
474 ("de wiki", Some("https://wiki.kvt.nl/x")),
475 ]))];
476 let stripped = strip_blocks(&blocks, &refs(&blocks));
477 let [Block::Paragraph(text)] = stripped.as_slice() else {
478 panic!("one paragraph expected");
479 };
480 assert_eq!(text.text, "zie en de wiki");
481 }
482
483 #[test]
484 fn links_beyond_the_card_limit_stay_in_the_text() {
485 let blocks = vec![Block::Paragraph(inline(&[(
486 "Werkorder WO2699001",
487 Some(WO),
488 )]))];
489 assert!(strip_blocks(&blocks, &[]).len() == 1);
490 }
491}