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, Section};
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 if l.section != Section::Contacts {
138 return;
139 }
140 l.search = v.trim().to_string();
141 router::replace(&l);
142 })));
143 };
144
145 // Back and Forward change the query from outside the box. A pending
146 // timer would undo that.
147 Effect::new(move |_| {
148 let q = query.get();
149 if input.get_untracked().trim() != q {
150 timer.set_value(None);
151 input.set(q);
152 }
153 });
154
155 let contacts = RwSignal::new(Option::<Result<Vec<PimContact>, String>>::None);
156 let seq = StoredValue::new(0u32);
157 Effect::new(move |_| {
158 let q = query.get();
159 let ids = collections.with(|c| {
160 hidden.with(|h| {
161 c.as_ref().map(|c| {
162 c.iter()
163 .filter(|c| c.kind == PimCollectionKind::Addressbook && !h.contains(&c.id))
164 .map(|c| c.id)
165 .collect::<Vec<_>>()
166 })
167 })
168 });
169 let Some(ids) = ids else { return };
170 let n = seq.get_value() + 1;
171 seq.set_value(n);
172 spawn_local(async move {
173 let r = api::pim_contacts(&q, &ids).await;
174 if seq.try_get_value() != Some(n) {
175 return;
176 }
177 // A hidden book's contact stays open when it comes from a link.
178 if let (Ok(list), Some((id, name))) = (&r, opened.get_untracked())
179 && !hidden.with_untracked(|h| h.contains(&id))
180 && !list.iter().any(|c| c.collection_id == id && c.name == name)
181 {
182 // Not Back: that entry holds the query from before the typing.
183 router::clear_open();
184 }
185 let _ = contacts.try_set(Some(r.map_err(|e| e.to_string())));
186 });
187 });
188
189 let detail = RwSignal::new(Option::<Result<PimContactDetail, String>>::None);
190 Effect::new(move |_| {
191 let Some((id, name)) = opened.get() else {
192 detail.set(None);
193 return;
194 };
195 detail.set(None);
196 spawn_local(async move {
197 let r = match api::pim_object(id, &name, None, &browser_tz()).await {
198 Ok(PimObjectDetail::Contact(c)) => Ok(c),
199 Ok(PimObjectDetail::Event(_)) => Err(i18n::t(k::PIM_NOT_CONTACT).to_string()),
200 Err(e) => Err(e.to_string()),
201 };
202 if opened.try_get_untracked() == Some(Some((id, name))) {
203 let _ = detail.try_set(Some(r));
204 }
205 });
206 });
207
208 let list = move || {
209 match contacts.get() {
210 None => view! { <p class="muted cal-pad">{i18n::t(k::LOADING)}</p> }.into_any(),
211 Some(Err(e)) => view! { <div class="card error-card">{e}</div> }.into_any(),
212 Some(Ok(all)) => {
213 let rows: Vec<_> = hidden.with(|h| {
214 all.into_iter()
215 .filter(|c| !h.contains(&c.collection_id))
216 .collect()
217 });
218 if rows.is_empty() {
219 let msg = match query.get().is_empty() {
220 true => k::PIM_NO_CONTACTS,
221 false => k::PIM_NO_MATCH,
222 };
223 return view! {
224 <div class="empty-state">
225 {icon_svg(IconName::Contacts, "empty-glyph")}
226 <p class="muted">{i18n::t(msg)}</p>
227 </div>
228 }
229 .into_any();
230 }
231 let colors: std::collections::HashMap<i64, String> = collections.with(|c| {
232 c.iter()
233 .flatten()
234 .map(|c| (c.id, safe_color(c.color.as_deref())))
235 .collect()
236 });
237 rows.into_iter()
238 .map(|c| {
239 let book = colors.get(&c.collection_id).cloned();
240 let key = (c.collection_id, c.name.clone());
241 // Per row, so opening a contact does not rebuild the list.
242 let selected = move || opened.with(|o| o.as_ref() == Some(&key));
243 let param = format!("{}/{}", c.collection_id, c.name);
244 let meta: Vec<String> = [c.org.clone(), c.email.clone(), c.phone.clone()]
245 .into_iter()
246 .flatten()
247 .collect();
248 view! {
249 <button
250 class="ct-row"
251 class:ct-sel=selected.clone()
252 aria-current=move || selected().then_some("true")
253 on:click=move |_| router::set_open(&param)
254 >
255 {avatar(
256 &c.full_name,
257 c.has_photo.then(|| api::pim_photo_url(c.collection_id, &c.name)),
258 "",
259 )}
260 <span class="ct-row-main">
261 <span class="ct-name">
262 <span class="ct-name-text">{c.full_name.clone()}</span>
263 {c.is_group.then(|| view! { <span class="badge">{i18n::t(k::PIM_GROUP)}</span> })}
264 </span>
265 {(!meta.is_empty()).then(|| view! { <span class="ct-meta">{meta.join(" · ")}</span> })}
266 </span>
267 {book.map(|b| view! {
268 <span class="ct-book" style=format!("--swatch: {b}") aria-hidden="true"></span>
269 })}
270 </button>
271 }
272 })
273 .collect::<Vec<_>>()
274 .into_any()
275 }
276 }
277 };
278
279 let book = move |id: i64| {
280 collections.with(|c| {
281 c.iter()
282 .flatten()
283 .find(|c| c.id == id)
284 .map(|c| (display_name(c), safe_color(c.color.as_deref())))
285 })
286 };
287 let pane = move || match (opened.get(), detail.get()) {
288 (None, _) => view! {
289 <div class="empty-state ct-placeholder">
290 {icon_svg(IconName::Contacts, "empty-glyph")}
291 <p class="muted">{i18n::t(k::PIM_PICK_CONTACT)}</p>
292 </div>
293 }
294 .into_any(),
295 (Some(_), None) => view! { <p class="muted cal-pad">{i18n::t(k::LOADING)}</p> }.into_any(),
296 (Some(_), Some(Err(e))) => view! { <div class="card error-card">{e}</div> }.into_any(),
297 (Some(_), Some(Ok(c))) => {
298 let sub: Vec<String> = [c.title.clone(), c.org.clone()]
299 .into_iter()
300 .flatten()
301 .collect();
302 let head_photo = avatar(&c.full_name, c.photo_url.clone(), "ct-avatar-lg");
303 let labeled = |key: &'static str,
304 items: Vec<api_types::PimLabeled>,
305 href: fn(&str) -> Option<String>| {
306 (!items.is_empty()).then(|| view! {
307 <dt>{i18n::t(key)}</dt>
308 <dd>
309 {items
310 .into_iter()
311 .map(|l| {
312 let label = l.label.as_deref().map(type_label);
313 let value = match href(&l.value) {
314 Some(h) => {
315 // mailto: and tel: open an app, not a tab.
316 let tab = h.starts_with("http").then_some("_blank");
317 view! {
318 <a href=h target=tab rel="noopener noreferrer">{l.value.clone()}</a>
319 }
320 .into_any()
321 }
322 None => view! { <span class="cal-pre">{l.value.clone()}</span> }.into_any(),
323 };
324 view! {
325 <div class="ct-value">
326 {value}
327 {label.map(|t| view! { <span class="muted ct-label">{t}</span> })}
328 </div>
329 }
330 })
331 .collect::<Vec<_>>()}
332 </dd>
333 })
334 };
335 let web = |v: &str| {
336 (v.starts_with("https://") || v.starts_with("http://")).then(|| v.to_string())
337 };
338 let collection = book(c.collection_id);
339 view! {
340 <button class="btn btn-sm ct-back" on:click=move |_| router::close_open()>
341 {icon_svg(IconName::ChevronRight, "ic-btn flip")}
342 {i18n::t(k::PIM_BACK)}
343 </button>
344 <div class="ct-head">
345 {head_photo}
346 <div class="ct-head-text">
347 <h2 class="ct-title">{c.full_name.clone()}</h2>
348 {(!sub.is_empty()).then(|| view! { <p class="muted">{sub.join(" · ")}</p> })}
349 </div>
350 </div>
351 <dl class="cal-facts">
352 {labeled(k::PIM_EMAIL, c.emails.clone(), |v| {
353 let addr = String::from(js_sys::encode_uri_component(v)).replace("%40", "@");
354 Some(format!("mailto:{addr}"))
355 })}
356 {labeled(k::PIM_PHONE, c.phones.clone(), |v| {
357 Some(format!("tel:{}", v.chars().filter(|c| !c.is_whitespace()).collect::<String>()))
358 })}
359 {labeled(k::PIM_POSTAL, c.addresses.clone(), |_| None)}
360 {labeled(k::PIM_WEBSITE, c.urls.clone(), web)}
361 {c.birthday.clone().map(|b| view! {
362 <dt>{i18n::t(k::PIM_BIRTHDAY)}</dt>
363 <dd>{fmt_vcard_date(&b)}</dd>
364 })}
365 {c.anniversary.clone().map(|b| view! {
366 <dt>{i18n::t(k::PIM_ANNIVERSARY)}</dt>
367 <dd>{fmt_vcard_date(&b)}</dd>
368 })}
369 {(!c.members.is_empty()).then(|| view! {
370 <dt>{i18n::t(k::PIM_MEMBERS)}</dt>
371 <dd>{c.members.join(", ")}</dd>
372 })}
373 {collection.map(|(n, color)| view! {
374 <dt>{i18n::t(k::PIM_ADDRESS_BOOK)}</dt>
375 <dd><span class="cal-dot" style=format!("--c: {color}")></span>" "{n}</dd>
376 })}
377 </dl>
378 {c.note.clone().filter(|n| !n.trim().is_empty()).map(|n| view! {
379 <h3 class="pim-section-title">{i18n::t(k::PIM_NOTE)}</h3>
380 <div class="cal-desc cal-pre">{linkified(&n)}
381 </div>
382 })}
383 }
384 .into_any()
385 }
386 };
387
388 view! {
389 <div class="ct" class:ct-has-open=move || opened.get().is_some()>
390 <div class="ct-list">
391 <div class="ct-search">
392 {icon_svg(IconName::Search, "ct-search-icon")}
393 <input
394 type="search"
395 placeholder=i18n::tr(k::PIM_SEARCH_CONTACTS)
396 aria-label=i18n::tr(k::PIM_SEARCH_CONTACTS)
397 prop:value=move || input.get()
398 on:input=move |ev| typed(event_target_value(&ev))
399 />
400 </div>
401 <div class="ct-rows">{list}</div>
402 </div>
403 <div class="ct-detail">{pane}</div>
404 </div>
405 }
406}
407
408#[cfg(test)]
409mod tests {
410 use super::*;
411
412 #[test]
413 fn vcard_dates() {
414 assert_eq!(vcard_date("1980-03-15"), Some((Some(1980), 3, 15)));
415 assert_eq!(vcard_date("19800315"), Some((Some(1980), 3, 15)));
416 assert_eq!(vcard_date("--03-15"), Some((None, 3, 15)));
417 assert_eq!(vcard_date("--0229"), Some((None, 2, 29)));
418 assert_eq!(
419 vcard_date("1980-03-15T00:00:00Z"),
420 Some((Some(1980), 3, 15))
421 );
422 assert_eq!(vcard_date("sometime"), None);
423 assert_eq!(vcard_date("1980-13-01"), None);
424 assert_eq!(vcard_date("1980-04-31"), None);
425 assert_eq!(vcard_date("1981-02-29"), None);
426 assert_eq!(vcard_date("1900-02-29"), None);
427 assert_eq!(vcard_date("2000-02-29"), Some((Some(2000), 2, 29)));
428 // Multi-byte values must not panic on byte slicing.
429 assert_eq!(vcard_date("1980年3"), None);
430 assert_eq!(vcard_date("--03é1"), None);
431 assert_eq!(initials("anna maria berg"), "AM");
432 assert_eq!(initials("ümit"), "Ü");
433 assert_eq!(initials("Atrium (4th floor)"), "AF");
434 assert_eq!(parse_open("3/a/b.vcf"), Some((3, "a/b.vcf".to_string())));
435 }
436}
437