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 rows.into_iter()
188 .map(|c| {
189 let key = (c.collection_id, c.name.clone());
190 let selected = open.as_ref() == Some(&key);
191 let param = format!("{}/{}", c.collection_id, c.name);
192 let meta: Vec<String> = [c.org.clone(), c.email.clone(), c.phone.clone()]
193 .into_iter()
194 .flatten()
195 .collect();
196 view! {
197 <button
198 class="ct-row"
199 class:ct-sel=selected
200 aria-current=selected.then_some("true")
201 on:click=move |_| router::set_open(&param)
202 >
203 {avatar(
204 &c.full_name,
205 c.has_photo.then(|| api::pim_photo_url(c.collection_id, &c.name)),
206 "",
207 )}
208 <span class="ct-row-main">
209 <span class="ct-name">
210 <span class="ct-name-text">{c.full_name.clone()}</span>
211 {c.is_group.then(|| view! { <span class="badge">{i18n::t(k::PIM_GROUP)}</span> })}
212 </span>
213 {(!meta.is_empty()).then(|| view! { <span class="ct-meta">{meta.join(" · ")}</span> })}
214 </span>
215 </button>
216 }
217 })
218 .collect::<Vec<_>>()
219 .into_any()
220 }
221 }
222 };
223
224 let book = move |id: i64| {
225 collections.with(|c| {
226 c.iter()
227 .flatten()
228 .find(|c| c.id == id)
229 .map(|c| (display_name(c), safe_color(c.color.as_deref())))
230 })
231 };
232 let pane = move || match (opened.get(), detail.get()) {
233 (None, _) => view! {
234 <div class="empty-state ct-placeholder">
235 {icon_svg(IconName::Contacts, "empty-glyph")}
236 <p class="muted">{i18n::t(k::PIM_PICK_CONTACT)}</p>
237 </div>
238 }
239 .into_any(),
240 (Some(_), None) => view! { <p class="muted cal-pad">{i18n::t(k::LOADING)}</p> }.into_any(),
241 (Some(_), Some(Err(e))) => view! { <div class="card error-card">{e}</div> }.into_any(),
242 (Some(_), Some(Ok(c))) => {
243 let sub: Vec<String> = [c.title.clone(), c.org.clone()]
244 .into_iter()
245 .flatten()
246 .collect();
247 let head_photo = avatar(&c.full_name, c.photo_url.clone(), "ct-avatar-lg");
248 let labeled = |key: &'static str,
249 items: Vec<api_types::PimLabeled>,
250 href: fn(&str) -> Option<String>| {
251 (!items.is_empty()).then(|| view! {
252 <dt>{i18n::t(key)}</dt>
253 <dd>
254 {items
255 .into_iter()
256 .map(|l| {
257 let label = l.label.as_deref().map(type_label);
258 let value = match href(&l.value) {
259 Some(h) => {
260 // mailto: and tel: open an app, not a tab.
261 let tab = h.starts_with("http").then_some("_blank");
262 view! {
263 <a href=h target=tab rel="noopener noreferrer">{l.value.clone()}</a>
264 }
265 .into_any()
266 }
267 None => view! { <span class="cal-pre">{l.value.clone()}</span> }.into_any(),
268 };
269 view! {
270 <div class="ct-value">
271 {value}
272 {label.map(|t| view! { <span class="muted ct-label">{t}</span> })}
273 </div>
274 }
275 })
276 .collect::<Vec<_>>()}
277 </dd>
278 })
279 };
280 let web = |v: &str| {
281 (v.starts_with("https://") || v.starts_with("http://")).then(|| v.to_string())
282 };
283 let collection = book(c.collection_id);
284 view! {
285 <button class="btn btn-sm ct-back" on:click=move |_| router::close_open()>
286 {icon_svg(IconName::ChevronRight, "ic-btn flip")}
287 {i18n::t(k::PIM_BACK)}
288 </button>
289 <div class="ct-head">
290 {head_photo}
291 <div class="ct-head-text">
292 <h2 class="ct-title">{c.full_name.clone()}</h2>
293 {(!sub.is_empty()).then(|| view! { <p class="muted">{sub.join(" · ")}</p> })}
294 </div>
295 </div>
296 <dl class="cal-facts">
297 {labeled(k::PIM_EMAIL, c.emails.clone(), |v| Some(format!("mailto:{v}")))}
298 {labeled(k::PIM_PHONE, c.phones.clone(), |v| {
299 Some(format!("tel:{}", v.chars().filter(|c| !c.is_whitespace()).collect::<String>()))
300 })}
301 {labeled(k::PIM_POSTAL, c.addresses.clone(), |_| None)}
302 {labeled(k::PIM_WEBSITE, c.urls.clone(), web)}
303 {c.birthday.clone().map(|b| view! {
304 <dt>{i18n::t(k::PIM_BIRTHDAY)}</dt>
305 <dd>{fmt_vcard_date(&b)}</dd>
306 })}
307 {c.anniversary.clone().map(|b| view! {
308 <dt>{i18n::t(k::PIM_ANNIVERSARY)}</dt>
309 <dd>{fmt_vcard_date(&b)}</dd>
310 })}
311 {(!c.members.is_empty()).then(|| view! {
312 <dt>{i18n::t(k::PIM_MEMBERS)}</dt>
313 <dd>{c.members.join(", ")}</dd>
314 })}
315 {collection.map(|(n, color)| view! {
316 <dt>{i18n::t(k::PIM_ADDRESS_BOOK)}</dt>
317 <dd><span class="cal-dot" style=format!("--c: {color}")></span>" "{n}</dd>
318 })}
319 </dl>
320 {c.note.clone().filter(|n| !n.trim().is_empty()).map(|n| view! {
321 <h3 class="pim-section-title">{i18n::t(k::PIM_NOTE)}</h3>
322 <div class="cal-desc cal-pre">{linkified(&n)}
323 </div>
324 })}
325 }
326 .into_any()
327 }
328 };
329
330 view! {
331 <div class="ct" class:ct-has-open=move || opened.get().is_some()>
332 <div class="ct-list">
333 <div class="ct-search">
334 {icon_svg(IconName::Search, "ct-search-icon")}
335 <input
336 type="search"
337 placeholder=i18n::tr(k::PIM_SEARCH_CONTACTS)
338 aria-label=i18n::tr(k::PIM_SEARCH_CONTACTS)
339 prop:value=move || input.get()
340 on:input=move |ev| typed(event_target_value(&ev))
341 />
342 </div>
343 <div class="ct-rows">{list}</div>
344 </div>
345 <div class="ct-detail">{pane}</div>
346 </div>
347 }
348}
349
350#[cfg(test)]
351mod tests {
352 use super::*;
353
354 #[test]
355 fn vcard_dates() {
356 assert_eq!(vcard_date("1980-03-15"), Some((Some(1980), 3, 15)));
357 assert_eq!(vcard_date("19800315"), Some((Some(1980), 3, 15)));
358 assert_eq!(vcard_date("--03-15"), Some((None, 3, 15)));
359 assert_eq!(vcard_date("--0229"), Some((None, 2, 29)));
360 assert_eq!(
361 vcard_date("1980-03-15T00:00:00Z"),
362 Some((Some(1980), 3, 15))
363 );
364 assert_eq!(vcard_date("sometime"), None);
365 assert_eq!(vcard_date("1980-13-01"), None);
366 assert_eq!(initials("anna maria berg"), "AM");
367 assert_eq!(initials("ümit"), "Ü");
368 assert_eq!(initials("Atrium (4th floor)"), "AF");
369 assert_eq!(parse_open("3/a/b.vcf"), Some((3, "a/b.vcf".to_string())));
370 }
371}
372