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