contacts.rs
⎇
Raw
1//! The contacts section's main area: a searchable list of the visible
2//! address books and the details of one contact.
3
4use std::collections::HashSet;
5
6use leptos::prelude::*;
7use wasm_bindgen_futures::spawn_local;
8
9use crate::api::{
10 self, PimCollectionInfo, PimCollectionKind, PimContact, PimContactDetail, PimObjectDetail,
11};
12use crate::components::icon::icon_svg;
13use crate::i18n::{self, k};
14use crate::icons::IconName;
15use crate::router::{self, Location};
16use crate::util::intl;
17use crate::views::calendar::linkified;
18use crate::views::pim::{browser_tz, display_name, safe_color};
19
20/// The open contact, as the URL names it: `{collection}/{name}`.
21fn parse_open(s: &str) -> Option<(i64, String)> {
22 let (id, name) = s.split_once('/')?;
23 Some((id.parse().ok()?, name.to_string()))
24}
25
26/// Up to two initials for a contact without photo.
27fn initials(name: &str) -> String {
28 // Words that start with a digit or bracket, like "(4th", give no letter.
29 name.split_whitespace()
30 .filter_map(|w| w.chars().next().filter(|c| c.is_alphabetic()))
31 .take(2)
32 .flat_map(char::to_uppercase)
33 .collect()
34}
35
36/// A vCard date: `1980-03-15`, `19800315`, or without year `--03-15` and
37/// `--0315`. `None` when it is none of these.
38pub fn vcard_date(s: &str) -> Option<(Option<i32>, u32, u32)> {
39 let s = s.split('T').next()?.replace('-', "");
40 // Byte slicing below needs ASCII; the value comes from any client.
41 if !s.bytes().all(|b| b.is_ascii_digit()) {
42 return None;
43 }
44 let (year, md) = match s.len() {
45 8 => (Some(s[..4].parse().ok()?), &s[4..]),
46 4 => (None, &s[..]),
47 _ => return None,
48 };
49 let (m, d) = (md[..2].parse().ok()?, md[2..].parse().ok()?);
50 // No year: February 29 is allowed.
51 let leap = year.is_none_or(|y| y % 4 == 0 && (y % 100 != 0 || y % 400 == 0));
52 let days = match m {
53 2 if leap => 29,
54 2 => 28,
55 4 | 6 | 9 | 11 => 30,
56 _ => 31,
57 };
58 ((1..=12).contains(&m) && (1..=days).contains(&d)).then_some((year, m, d))
59}
60
61fn fmt_vcard_date(s: &str) -> String {
62 let Some((year, m, d)) = vcard_date(s) else {
63 return s.to_string();
64 };
65 // `Date.UTC` maps years below 100 to 19xx, so set the year separately. A
66 // leap year, so February 29 exists when the year is unknown.
67 let date = js_sys::Date::new(&wasm_bindgen::JsValue::from_f64(0.0));
68 date.set_utc_full_year_with_month_date(year.unwrap_or(2000) as u32, m as i32 - 1, d as i32);
69 match year {
70 Some(_) => intl(
71 &date,
72 &[
73 ("timeZone", "UTC"),
74 ("day", "numeric"),
75 ("month", "long"),
76 ("year", "numeric"),
77 ],
78 ),
79 None => intl(
80 &date,
81 &[("timeZone", "UTC"), ("day", "numeric"), ("month", "long")],
82 ),
83 }
84}
85
86/// vCard TYPE values in the UI language. Unknown ones stay as written.
87fn type_label(t: &str) -> String {
88 let key = match t.to_ascii_lowercase().as_str() {
89 "work" => k::CT_TYPE_WORK,
90 "home" => k::CT_TYPE_HOME,
91 "cell" | "mobile" => k::CT_TYPE_CELL,
92 "fax" => k::CT_TYPE_FAX,
93 "other" => k::CT_TYPE_OTHER,
94 _ => return t.to_string(),
95 };
96 i18n::t(key).to_string()
97}
98
99/// Initials, covered by the photo when there is one. A photo that fails to
100/// load hides itself and leaves the initials.
101fn avatar(name: &str, photo: Option<String>, class: &'static str) -> impl IntoView + use<> {
102 view! {
103 <span class=format!("ct-avatar ct-initials {class}") aria-hidden="true">
104 {initials(name)}
105 {photo.map(|src| view! {
106 <img
107 class="ct-photo"
108 src=src
109 alt=""
110 loading="lazy"
111 on:error=|ev| {
112 let _ = event_target::<web_sys::HtmlElement>(&ev)
113 .style()
114 .set_property("display", "none");
115 }
116 />
117 })}
118 </span>
119 }
120}
121
122#[component]
123pub fn ContactsMain(
124 collections: ReadSignal<Option<Vec<PimCollectionInfo>>>,
125 hidden: RwSignal<HashSet<i64>>,
126 loc: ReadSignal<Location>,
127) -> impl IntoView {
128 let query = Memo::new(move |_| loc.with(|l| l.search.clone()));
129 let opened = Memo::new(move |_| loc.with(|l| l.open.as_deref().and_then(parse_open)));
130 let input = RwSignal::new(query.get_untracked());
131 let timer = StoredValue::new_local(None::<gloo_timers::callback::Timeout>);
132 let typed = move |v: String| {
133 input.set(v.clone());
134 // One request per pause in typing, and no history entry per key.
135 timer.set_value(Some(gloo_timers::callback::Timeout::new(300, move || {
136 let mut l = loc.get_untracked();
137 l.search = v.trim().to_string();
138 router::replace(&l);
139 })));
140 };
141
142 // Back and Forward change the query from outside the box.
143 Effect::new(move |_| {
144 let q = query.get();
145 if input.get_untracked().trim() != q {
146 input.set(q);
147 }
148 });
149
150 let contacts = RwSignal::new(Option::<Result<Vec<PimContact>, String>>::None);
151 let seq = StoredValue::new(0u32);
152 Effect::new(move |_| {
153 let q = query.get();
154 let ids = collections.with(|c| {
155 hidden.with(|h| {
156 c.as_ref().map(|c| {
157 c.iter()
158 .filter(|c| c.kind == PimCollectionKind::Addressbook && !h.contains(&c.id))
159 .map(|c| c.id)
160 .collect::<Vec<_>>()
161 })
162 })
163 });
164 let Some(ids) = ids else { return };
165 let n = seq.get_value() + 1;
166 seq.set_value(n);
167 spawn_local(async move {
168 let r = api::pim_contacts(&q, &ids).await;
169 if seq.try_get_value() != Some(n) {
170 return;
171 }
172 // A hidden book's contact stays open when it comes from a link.
173 if let (Ok(list), Some((id, name))) = (&r, opened.get_untracked())
174 && !hidden.with_untracked(|h| h.contains(&id))
175 && !list.iter().any(|c| c.collection_id == id && c.name == name)
176 {
177 router::close_open();
178 }
179 let _ = contacts.try_set(Some(r.map_err(|e| e.to_string())));
180 });
181 });
182
183 let detail = RwSignal::new(Option::<Result<PimContactDetail, String>>::None);
184 Effect::new(move |_| {
185 let Some((id, name)) = opened.get() else {
186 detail.set(None);
187 return;
188 };
189 detail.set(None);
190 spawn_local(async move {
191 let r = match api::pim_object(id, &name, None, &browser_tz()).await {
192 Ok(PimObjectDetail::Contact(c)) => Ok(c),
193 Ok(PimObjectDetail::Event(_)) => Err(i18n::t(k::PIM_NOT_CONTACT).to_string()),
194 Err(e) => Err(e.to_string()),
195 };
196 if opened.try_get_untracked() == Some(Some((id, name))) {
197 let _ = detail.try_set(Some(r));
198 }
199 });
200 });
201
202 let list = move || {
203 match contacts.get() {
204 None => view! { <p class="muted cal-pad">{i18n::t(k::LOADING)}</p> }.into_any(),
205 Some(Err(e)) => view! { <div class="card error-card">{e}</div> }.into_any(),
206 Some(Ok(all)) => {
207 let rows: Vec<_> = hidden.with(|h| {
208 all.into_iter()
209 .filter(|c| !h.contains(&c.collection_id))
210 .collect()
211 });
212 if rows.is_empty() {
213 let msg = match query.get().is_empty() {
214 true => k::PIM_NO_CONTACTS,
215 false => k::PIM_NO_MATCH,
216 };
217 return view! {
218 <div class="empty-state">
219 {icon_svg(IconName::Contacts, "empty-glyph")}
220 <p class="muted">{i18n::t(msg)}</p>
221 </div>
222 }
223 .into_any();
224 }
225 let colors: std::collections::HashMap<i64, String> = collections.with(|c| {
226 c.iter()
227 .flatten()
228 .map(|c| (c.id, safe_color(c.color.as_deref())))
229 .collect()
230 });
231 rows.into_iter()
232 .map(|c| {
233 let book = colors.get(&c.collection_id).cloned();
234 let key = (c.collection_id, c.name.clone());
235 // Per row, so opening a contact does not rebuild the list.
236 let selected = move || opened.with(|o| o.as_ref() == Some(&key));
237 let param = format!("{}/{}", c.collection_id, c.name);
238 let meta: Vec<String> = [c.org.clone(), c.email.clone(), c.phone.clone()]
239 .into_iter()
240 .flatten()
241 .collect();
242 view! {
243 <button
244 class="ct-row"
245 class:ct-sel=selected.clone()
246 aria-current=move || selected().then_some("true")
247 on:click=move |_| router::set_open(&param)
248 >
249 {avatar(
250 &c.full_name,
251 c.has_photo.then(|| api::pim_photo_url(c.collection_id, &c.name)),
252 "",
253 )}
254 <span class="ct-row-main">
255 <span class="ct-name">
256 <span class="ct-name-text">{c.full_name.clone()}</span>
257 {c.is_group.then(|| view! { <span class="badge">{i18n::t(k::PIM_GROUP)}</span> })}
258 </span>
259 {(!meta.is_empty()).then(|| view! { <span class="ct-meta">{meta.join(" · ")}</span> })}
260 </span>
261 {book.map(|b| view! {
262 <span class="ct-book" style=format!("--swatch: {b}") aria-hidden="true"></span>
263 })}
264 </button>
265 }
266 })
267 .collect::<Vec<_>>()
268 .into_any()
269 }
270 }
271 };
272
273 let book = move |id: i64| {
274 collections.with(|c| {
275 c.iter()
276 .flatten()
277 .find(|c| c.id == id)
278 .map(|c| (display_name(c), safe_color(c.color.as_deref())))
279 })
280 };
281 let pane = move || match (opened.get(), detail.get()) {
282 (None, _) => view! {
283 <div class="empty-state ct-placeholder">
284 {icon_svg(IconName::Contacts, "empty-glyph")}
285 <p class="muted">{i18n::t(k::PIM_PICK_CONTACT)}</p>
286 </div>
287 }
288 .into_any(),
289 (Some(_), None) => view! { <p class="muted cal-pad">{i18n::t(k::LOADING)}</p> }.into_any(),
290 (Some(_), Some(Err(e))) => view! { <div class="card error-card">{e}</div> }.into_any(),
291 (Some(_), Some(Ok(c))) => {
292 let sub: Vec<String> = [c.title.clone(), c.org.clone()]
293 .into_iter()
294 .flatten()
295 .collect();
296 let head_photo = avatar(&c.full_name, c.photo_url.clone(), "ct-avatar-lg");
297 let labeled = |key: &'static str,
298 items: Vec<api_types::PimLabeled>,
299 href: fn(&str) -> Option<String>| {
300 (!items.is_empty()).then(|| view! {
301 <dt>{i18n::t(key)}</dt>
302 <dd>
303 {items
304 .into_iter()
305 .map(|l| {
306 let label = l.label.as_deref().map(type_label);
307 let value = match href(&l.value) {
308 Some(h) => {
309 // mailto: and tel: open an app, not a tab.
310 let tab = h.starts_with("http").then_some("_blank");
311 view! {
312 <a href=h target=tab rel="noopener noreferrer">{l.value.clone()}</a>
313 }
314 .into_any()
315 }
316 None => view! { <span class="cal-pre">{l.value.clone()}</span> }.into_any(),
317 };
318 view! {
319 <div class="ct-value">
320 {value}
321 {label.map(|t| view! { <span class="muted ct-label">{t}</span> })}
322 </div>
323 }
324 })
325 .collect::<Vec<_>>()}
326 </dd>
327 })
328 };
329 let web = |v: &str| {
330 (v.starts_with("https://") || v.starts_with("http://")).then(|| v.to_string())
331 };
332 let collection = book(c.collection_id);
333 view! {
334 <button class="btn btn-sm ct-back" on:click=move |_| router::close_open()>
335 {icon_svg(IconName::ChevronRight, "ic-btn flip")}
336 {i18n::t(k::PIM_BACK)}
337 </button>
338 <div class="ct-head">
339 {head_photo}
340 <div class="ct-head-text">
341 <h2 class="ct-title">{c.full_name.clone()}</h2>
342 {(!sub.is_empty()).then(|| view! { <p class="muted">{sub.join(" · ")}</p> })}
343 </div>
344 </div>
345 <dl class="cal-facts">
346 {labeled(k::PIM_EMAIL, c.emails.clone(), |v| {
347 let addr = String::from(js_sys::encode_uri_component(v)).replace("%40", "@");
348 Some(format!("mailto:{addr}"))
349 })}
350 {labeled(k::PIM_PHONE, c.phones.clone(), |v| {
351 Some(format!("tel:{}", v.chars().filter(|c| !c.is_whitespace()).collect::<String>()))
352 })}
353 {labeled(k::PIM_POSTAL, c.addresses.clone(), |_| None)}
354 {labeled(k::PIM_WEBSITE, c.urls.clone(), web)}
355 {c.birthday.clone().map(|b| view! {
356 <dt>{i18n::t(k::PIM_BIRTHDAY)}</dt>
357 <dd>{fmt_vcard_date(&b)}</dd>
358 })}
359 {c.anniversary.clone().map(|b| view! {
360 <dt>{i18n::t(k::PIM_ANNIVERSARY)}</dt>
361 <dd>{fmt_vcard_date(&b)}</dd>
362 })}
363 {(!c.members.is_empty()).then(|| view! {
364 <dt>{i18n::t(k::PIM_MEMBERS)}</dt>
365 <dd>{c.members.join(", ")}</dd>
366 })}
367 {collection.map(|(n, color)| view! {
368 <dt>{i18n::t(k::PIM_ADDRESS_BOOK)}</dt>
369 <dd><span class="cal-dot" style=format!("--c: {color}")></span>" "{n}</dd>
370 })}
371 </dl>
372 {c.note.clone().filter(|n| !n.trim().is_empty()).map(|n| view! {
373 <h3 class="pim-section-title">{i18n::t(k::PIM_NOTE)}</h3>
374 <div class="cal-desc cal-pre">{linkified(&n)}
375 </div>
376 })}
377 }
378 .into_any()
379 }
380 };
381
382 view! {
383 <div class="ct" class:ct-has-open=move || opened.get().is_some()>
384 <div class="ct-list">
385 <div class="ct-search">
386 {icon_svg(IconName::Search, "ct-search-icon")}
387 <input
388 type="search"
389 placeholder=i18n::tr(k::PIM_SEARCH_CONTACTS)
390 aria-label=i18n::tr(k::PIM_SEARCH_CONTACTS)
391 prop:value=move || input.get()
392 on:input=move |ev| typed(event_target_value(&ev))
393 />
394 </div>
395 <div class="ct-rows">{list}</div>
396 </div>
397 <div class="ct-detail">{pane}</div>
398 </div>
399 }
400}
401
402#[cfg(test)]
403mod tests {
404 use super::*;
405
406 #[test]
407 fn vcard_dates() {
408 assert_eq!(vcard_date("1980-03-15"), Some((Some(1980), 3, 15)));
409 assert_eq!(vcard_date("19800315"), Some((Some(1980), 3, 15)));
410 assert_eq!(vcard_date("--03-15"), Some((None, 3, 15)));
411 assert_eq!(vcard_date("--0229"), Some((None, 2, 29)));
412 assert_eq!(
413 vcard_date("1980-03-15T00:00:00Z"),
414 Some((Some(1980), 3, 15))
415 );
416 assert_eq!(vcard_date("sometime"), None);
417 assert_eq!(vcard_date("1980-13-01"), None);
418 assert_eq!(vcard_date("1980-04-31"), None);
419 assert_eq!(vcard_date("1981-02-29"), None);
420 assert_eq!(vcard_date("1900-02-29"), None);
421 assert_eq!(vcard_date("2000-02-29"), Some((Some(2000), 2, 29)));
422 // Multi-byte values must not panic on byte slicing.
423 assert_eq!(vcard_date("1980年3"), None);
424 assert_eq!(vcard_date("--03é1"), None);
425 assert_eq!(initials("anna maria berg"), "AM");
426 assert_eq!(initials("ümit"), "Ü");
427 assert_eq!(initials("Atrium (4th floor)"), "AF");
428 assert_eq!(parse_open("3/a/b.vcf"), Some((3, "a/b.vcf".to_string())));
429 }
430}
431