//! Contacts: the address book. Everyone the person keeps, with or without //! a Pinnacle device: names, phone numbers, e-mail, address, birthday, //! organisation and a note, to find, read, change and remove. The book //! is the p2p service's (`pinnacle_ui::p2p::BOOK`), so Messages, Calls //! and Settings show the names given here. //! //! Import and export are vCards in the app's own folder: Export writes //! every contact to `contacts.vcf`, Import reads every `.vcf` file there, //! a phone's or a mail program's export as well; a contact imported again //! replaces the one it was, by its UID or its device's key. Built from a //! view (`pinnacle_view`). #![no_std] #![no_main] extern crate alloc; use alloc::format; use alloc::rc::Rc; use alloc::string::String; use alloc::vec::Vec; use pinnacle_rt::fs; use pinnacle_ui::p2p::{Client, Entry, contacts}; use pinnacle_ui::{App, Event, theme}; use pinnacle_view::{IntoView, Screen, Signal, View, el, signal}; /// The app's own folder, wherever the system keeps it. const FOLDER: &str = "app:"; /// What Export writes. const EXPORT: &str = "contacts.vcf"; /// How it says where its named controls are (`Screen::announce`), for /// `cargo xtask` to tap them. const ANNOUNCE: &str = "contacts: control "; #[derive(Clone, PartialEq)] enum Page { List, /// One contact, by id. Show(String), /// The editor, on [`Draft`]. Edit, } /// The contact being edited, a signal a field: typing changes only its own, /// so the page is not built again under the finger. #[derive(Clone)] struct Draft { /// What is kept as it was: id, UID, key and card. base: Signal, name: Signal, phones: Signal>>, emails: Signal>>, address: Signal, birthday: Signal, organisation: Signal, note: Signal, } impl Draft { fn new() -> Draft { Draft { base: signal(Entry::default()), name: signal(String::new()), phones: signal(Vec::new()), emails: signal(Vec::new()), address: signal(String::new()), birthday: signal(String::new()), organisation: signal(String::new()), note: signal(String::new()), } } /// Fills it from `e`, each list with an empty field to add one in. fn load(&self, e: &Entry) { let list = |values: &[String]| { let mut fields: Vec> = values.iter().map(|v| signal(v.clone())).collect(); fields.push(signal(String::new())); fields }; self.base.set(e.clone()); self.name.set(e.name.clone()); self.phones.set(list(&e.phones)); self.emails.set(list(&e.emails)); self.address.set(e.address.clone()); self.birthday.set(e.birthday.clone()); self.organisation.set(e.organisation.clone()); self.note.set(e.note.clone()); } fn entry(&self) -> Entry { let list = |fields: &Signal>>| { fields.with(|f| { f.iter() .map(|s| String::from(s.get_untracked().trim())) .filter(|v| !v.is_empty()) .collect() }) }; let text = |s: &Signal| String::from(s.get_untracked().trim()); Entry { name: text(&self.name), phones: list(&self.phones), emails: list(&self.emails), address: text(&self.address), birthday: text(&self.birthday), organisation: text(&self.organisation), note: String::from(self.note.get_untracked().trim_end()), ..self.base.get_untracked() } } } /// Everything the pages and their buttons share. #[derive(Clone)] struct Model { client: Option>, entries: Signal>, page: Signal, query: Signal, draft: Draft, /// What the last action did, shown under the header. status: Signal, /// Remove was pressed once: the next press removes. confirm: Signal, } impl Model { fn reload(&self) { if let Some(c) = &self.client { self.entries.set(c.book(&mut Vec::new())); } } fn find(&self, id: &str) -> Option { self.entries.with(|all| all.iter().find(|e| e.id == id).cloned()) } /// Shows what an action did under the header, and logs it. fn say(&self, text: String) { pinnacle_rt::println!("contacts: {text}"); self.status.set(text); } fn open(&self, page: Page) { self.confirm.set(false); self.status.set(String::new()); self.page.set(page); } fn edit(&self, e: &Entry) { self.draft.load(e); self.open(Page::Edit); } fn save(&self) { let Some(c) = &self.client else { return; }; let entry = self.draft.entry(); if entry.is_empty() { self.say("Give it a name, or a number".into()); return; } match c.put_entry(&entry, &mut Vec::new()) { Some(id) => { pinnacle_rt::println!("contacts: kept {}", entry.title()); self.reload(); self.open(Page::Show(id)); } None => self.say("It could not be kept: is the note very long?".into()), } } fn remove(&self, id: &str) { if !self.confirm.get_untracked() { self.confirm.set(true); return; } if let Some(c) = &self.client { c.remove_entry(id); pinnacle_rt::println!("contacts: removed"); } self.reload(); self.open(Page::List); } fn export(&self) { let all = self.entries.get_untracked(); let text = contacts::to_vcards(&all); let done = fs::write(&format!("{FOLDER}/{EXPORT}"), text.as_bytes()); self.say(match (done, all.len()) { (false, _) => "The export could not be written".into(), (true, 1) => format!("1 contact exported to {EXPORT}"), (true, n) => format!("{n} contacts exported to {EXPORT}"), }); } fn import(&self) { let Some(c) = &self.client else { return; }; let files: Vec = fs::list(FOLDER) .unwrap_or_default() .into_iter() .filter(|n| n.to_ascii_lowercase().ends_with(".vcf")) .collect(); let found: Vec = files .iter() .filter_map(|f| fs::read(&format!("{FOLDER}/{f}"))) .flat_map(|bytes| contacts::parse(&String::from_utf8_lossy(&bytes))) .collect(); if found.is_empty() { self.say(if files.is_empty() { "Put a .vcf file in this app's folder to import it".into() } else { format!("No contacts in {}", files.join(", ")) }); return; } let kept = c.import(&found, &mut Vec::new()); self.reload(); self.say(match kept { 1 => format!("1 contact imported from {}", files.join(", ")), n => format!("{n} contacts imported from {}", files.join(", ")), }); } } /// A button: `variant` `primary`, `ghost`, `danger` or none. fn button( label: impl IntoView, variant: &'static str, name: &'static str, onclick: impl Fn() + 'static, ) -> View { el("button") .class("m-button") .attr("type", "button") .attr("data-variant", (!variant.is_empty()).then_some(variant)) .attr("data-name", name) .on("click", move |_| onclick()) .child(label) .into_view() } /// A round badge with a name's first letter, in the name's colour. fn avatar(name: &str, size: u32) -> View { let initial: String = name .chars() .next() .map(|c| c.to_uppercase().collect()) .unwrap_or_default(); let color = theme::color_for(name).0 & 0xff_ffff; el("span") .attr( "style", format!( "width: {size}px; height: {size}px; border-radius: {r}px; flex: none; \ background: #{color:06x}; color: #ffffff; font-size: {f}px; \ display: flex; align-items: center; justify-content: center", r = size / 2, f = size / 2, ), ) .child(initial) .into_view() } const PAGE_STYLE: &str = "max-width: 640px; margin: 0 auto; padding: 24px 16px 48px; \ display: flex; flex-direction: column; align-items: stretch; gap: 12px"; const BAR_STYLE: &str = "display: flex; align-items: center; gap: 8px; flex-wrap: wrap"; fn header(title: impl IntoView, buttons: Vec) -> View { el("div") .attr("style", BAR_STYLE) .child( el("h1") .attr("style", "font-size: 28px; margin: 0; flex: 1; min-width: 0") .child(title), ) .children(buttons) .into_view() } fn status(m: &Model) -> View { let s = m.status.clone(); (move || { let text = s.get(); (!text.is_empty()).then(|| { el("p") .attr("style", "color: var(--m-text-muted); margin: 0") .attr("role", "status") .child(text) }) }) .into_view() } fn list_page(m: &Model) -> View { let (query, entries) = (m.query.clone(), m.entries.clone()); let rows = { let m = m.clone(); move || { let q = query.get().to_lowercase(); let all = entries.get(); let shown: Vec<&Entry> = all .iter() .filter(|e| { q.is_empty() || e.title().to_lowercase().contains(&q) || e.phones.iter().any(|p| p.contains(q.as_str())) || e.emails.iter().any(|x| x.to_lowercase().contains(&q)) }) .collect(); if shown.is_empty() { let text = if all.is_empty() { "No contacts yet" } else { "No one by that name" }; return el("p") .attr( "style", "color: var(--m-text-muted); text-align: center; margin: 32px 0", ) .child(text) .into_view(); } el("div") .class("m-list") .attr("role", "list") .children(shown.into_iter().map(|e| { let (m, id) = (m.clone(), e.id.clone()); let sub = e.phones.first().or(e.emails.first()).cloned().unwrap_or_default(); el("div") .class("m-list-item") .attr("role", "button") .attr("tabindex", "0") .attr("data-name", format!("contact {}", e.title())) .on("click", move |_| m.open(Page::Show(id.clone()))) .child(avatar(e.title(), 40)) .child( el("span") .class("m-list-item__body") .child(el("span").class("m-list-item__title").child(e.title())) .child( (!sub.is_empty()) .then(|| el("span").class("m-list-item__sub").child(sub)), ), ) .child(e.key.is_some().then(|| { el("span") .class("m-list-item__end") .attr("title", "Has a Pinnacle device") .child("P2P") })) .into_view() })) .into_view() } }; let q = m.query.clone(); let said = m.status.clone(); let (a, b, c) = (m.clone(), m.clone(), m.clone()); el("main") .attr("style", PAGE_STYLE) .child(header( "Contacts", alloc::vec![button("New", "primary", "new", move || a.edit(&Entry::default()))], )) .child( el("div").class("m-input").child( el("input") .class("m-input__native") .attr("type", "search") .attr("placeholder", "Search") .attr("data-name", "search") .prop("value", { let q = q.clone(); move || q.get_untracked() }) .on("input", move |e| { // What the last action said is old news now. said.set(String::new()); q.set(e.value.clone().unwrap_or_default()); }), ), ) .child(status(m)) .child(rows) .child( el("div") .attr( "style", "display: flex; gap: 8px; justify-content: center; margin-top: 8px", ) .child(button("Import", "", "import", move || b.import())) .child(button("Export", "", "export", move || c.export())), ) .into_view() } /// One labelled value of a contact's card. fn detail(label: &'static str, value: &str) -> Option { (!value.trim().is_empty()).then(|| { el("div") .class("m-list-item") .attr("role", "listitem") .child( el("span") .class("m-list-item__body") .child(el("span").class("m-list-item__sub").child(label)) .child( el("span") .class("m-list-item__title") .attr("style", "white-space: pre-wrap") .child(String::from(value.trim())), ), ) .into_view() }) } fn show_page(m: &Model, e: Entry) -> View { let mut rows: Vec = Vec::new(); rows.extend(e.phones.iter().filter_map(|p| detail("Phone", p))); rows.extend(e.emails.iter().filter_map(|x| detail("E-mail", x))); rows.extend(detail("Address", &e.address)); rows.extend(detail("Birthday", &e.birthday)); rows.extend(detail("Organisation", &e.organisation)); rows.extend(detail("Note", &e.note)); if let Some(key) = &e.key { let print = contacts::hex(&key[..8]); rows.extend(detail("Pinnacle device", &print)); } let (back, edit, remove) = (m.clone(), m.clone(), m.clone()); let confirm = m.confirm.clone(); let id = e.id.clone(); let entry = e.clone(); el("main") .attr("style", PAGE_STYLE) .child( el("div") .attr("style", BAR_STYLE) .child(button("Back", "ghost", "back", move || back.open(Page::List))), ) .child( el("div") .attr( "style", "display: flex; flex-direction: column; align-items: center; gap: 12px", ) .child(avatar(e.title(), 96)) .child( el("h1") .attr("style", "font-size: 28px; margin: 0; text-align: center") .child(String::from(e.title())), ), ) .child(status(m)) .child( el("section") .class("m-section") .child(el("div").class("m-list").attr("role", "list").children(rows)), ) .child( el("div") .attr("style", "display: flex; gap: 8px; justify-content: center") .child(button("Edit", "primary", "edit", move || edit.edit(&entry))) .child(button( move || { if confirm.get() { "Remove for good" } else { "Remove" } }, "danger", "remove", move || remove.remove(&id), )), ) .into_view() } /// A labelled text field on `value`. fn field(label: &'static str, value: &Signal, kind: &'static str) -> View { let (shown, set) = (value.clone(), value.clone()); el("label") .class("m-field") .child(el("span").class("m-field__label").child(label)) .child( el("div").class("m-input").child( el("input") .class("m-input__native") .attr("type", kind) .attr("data-name", format!("field {label}")) .prop("value", move || shown.get_untracked()) .on("input", move |e| set.set(e.value.clone().unwrap_or_default())), ), ) .into_view() } /// Fields for a list of values (phones, e-mail): one each, and an empty /// one to add another in. The list is built again only when a field is /// added ("Another number or address"), never while one is typed in. fn fields(label: &'static str, list: &Signal>>, kind: &'static str) -> View { let list = list.clone(); (move || { el("div") .attr("style", "display: flex; flex-direction: column; gap: 12px") .children(list.get().into_iter().enumerate().map(|(i, value)| { let (shown, set) = (value.clone(), value); el("label") .class("m-field") .child(el("span").class("m-field__label").child(label)) .child( el("div").class("m-input").child( el("input") .class("m-input__native") .attr("type", kind) .attr("data-name", format!("field {label} {}", i + 1)) .prop("value", move || shown.get_untracked()) .on("input", move |e| set.set(e.value.clone().unwrap_or_default())), ), ) .into_view() })) .into_view() }) .into_view() } fn edit_page(m: &Model) -> View { let d = &m.draft; let (cancel, save) = (m.clone(), m.clone()); let base = d.base.get_untracked(); let title = if base.id.is_empty() { "New contact" } else { "Edit contact" }; let more = { let (phones, emails) = (d.phones.clone(), d.emails.clone()); move || { for list in [&phones, &emails] { let filled = list.with(|l| l.last().is_none_or(|s| !s.get_untracked().trim().is_empty())); if filled { list.update(|l| l.push(signal(String::new()))); } } } }; let note = (d.note.clone(), d.note.clone()); el("main") .attr("style", PAGE_STYLE) .child(header( title, alloc::vec![ button("Cancel", "ghost", "cancel", move || { let id = cancel.draft.base.get_untracked().id; cancel.open(if id.is_empty() { Page::List } else { Page::Show(id) }); }), button("Save", "primary", "save", move || save.save()), ], )) .child(status(m)) .child(field("Name", &d.name, "text")) .child(fields("Phone", &d.phones, "tel")) .child(fields("E-mail", &d.emails, "email")) .child(button("Another number or address", "ghost", "more", more)) .child(field("Address", &d.address, "text")) .child(field("Birthday", &d.birthday, "text")) .child(field("Organisation", &d.organisation, "text")) .child( el("label") .class("m-field") .child(el("span").class("m-field__label").child("Note")) .child( el("div").class("m-input").child( el("textarea") .class("m-input__native") .attr("rows", "4") .attr("data-name", "field Note") .prop("value", move || note.0.get_untracked()) .on("input", move |e| note.1.set(e.value.clone().unwrap_or_default())), ), ), ) .into_view() } fn root(m: Model) -> View { let page = m.page.clone(); (move || match page.get() { Page::List => list_page(&m), Page::Show(id) => match m.find(&id) { Some(e) => show_page(&m, e), None => list_page(&m), }, Page::Edit => edit_page(&m), }) .into_view() } #[unsafe(no_mangle)] fn main(_argument: u64) -> u64 { let mut app = App::new("Contacts"); let mut screen = Screen::new(app.width, app.height); let model = Model { client: Client::connect(2000).map(Rc::new), entries: signal(Vec::new()), page: signal(Page::List), query: signal(String::new()), draft: Draft::new(), status: signal(String::new()), confirm: signal(false), }; model.reload(); if model.client.is_none() { model .status .set("The address book is not there: the p2p service did not answer".into()); } screen.mount(root(model.clone())); screen.draw(&mut app.canvas(), true); app.present_all(); screen.announce(ANNOUNCE); loop { match app.next_event(None) { Event::Shown(true) => { // Another app may have added someone meanwhile. if model.page.get_untracked() == Page::List { model.reload(); } screen.draw(&mut app.canvas(), true); app.present_all(); screen.announce(ANNOUNCE); } Event::Resized => { screen.resize(app.width, app.height); screen.draw(&mut app.canvas(), true); app.present_all(); screen.announce(ANNOUNCE); } Event::Input(input) => { screen.input(&input); if let Some(area) = screen.draw(&mut app.canvas(), false) { app.present(area); // A page opened, or a drag scrolled this one: where // the controls are now. screen.announce(ANNOUNCE); } } Event::Closed => return 0, _ => {} } } }