From 6a4b1de8b1c7d74fa528f07adf24a028f6de24bc Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 00:18:10 +0000 Subject: [PATCH] Map properties to contact fields with ##contact A phone's contacts have fields (phone numbers, emails, addresses and so on), and Quiddity's properties are free text, so something has to say which property fills which field. Following the other meta-properties, a property's entity says it: `##contact(phone:mobile)` on `mobile` makes its values mobile phone numbers. The field is one of a fixed few, and the label after the colon is free. Nothing uses the mapping yet. This reads it into the schema, lists the mapped properties on the index, and flags a line it can't read; the contacts themselves come in the commits stacked on this one. Journal: - Added `##contact(field:label)`, which says which field of a contact a property fills. [[Contacts]] [[Built-in properties]] - It is the first step towards showing entities in Android's contacts: only the mapping is read so far, and [[Contacts]] says so. - Any entity with a value for a mapped property will be a contact, with no type to say it is a person, so the mapping is all a graph has to write. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01URxBNGtnCj5RibKerde9WL --- crates/core/src/contact.rs | 170 ++++++++++++++++++++++++++++++++++++ crates/core/src/index.rs | 17 ++++ crates/core/src/lib.rs | 1 + crates/core/src/schema.rs | 16 ++++ crates/core/tests/meta.rs | 67 ++++++++++++++ docs/Built-in properties.md | 2 + docs/Contacts.md | 17 ++++ docs/User guide.md | 1 + docs/quiddity-core.md | 1 + 9 files changed, 292 insertions(+) create mode 100644 crates/core/src/contact.rs create mode 100644 docs/Contacts.md diff --git a/crates/core/src/contact.rs b/crates/core/src/contact.rs new file mode 100644 index 00000000..71dfad4d --- /dev/null +++ b/crates/core/src/contact.rs @@ -0,0 +1,170 @@ +//! What `##contact(field:label)` says: which field of a contact a property +//! fills. +//! +//! The vocabulary is the fields every phone's contacts app has, spelt as +//! Quiddity spells them. Nothing here knows about any platform's contacts: +//! that is for whatever exposes them. + +use std::fmt; + +use quiddity_syntax::normalise_name; + +/// A field of a contact. An entity's name is the contact's name, and isn't +/// one of these. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum ContactField { + Phone, + Email, + Address, + Organisation, + JobTitle, + Nickname, + Website, + Birthday, + Note, +} + +impl ContactField { + /// Every field, in the order they are listed. + pub const ALL: [Self; 9] = [ + Self::Phone, + Self::Email, + Self::Address, + Self::Organisation, + Self::JobTitle, + Self::Nickname, + Self::Website, + Self::Birthday, + Self::Note, + ]; + + /// How the field is written in `##contact(…)`. + pub const fn name(self) -> &'static str { + match self { + Self::Phone => "phone", + Self::Email => "email", + Self::Address => "address", + Self::Organisation => "organisation", + Self::JobTitle => "job-title", + Self::Nickname => "nickname", + Self::Website => "website", + Self::Birthday => "birthday", + Self::Note => "note", + } + } + + /// Reads a field's name, ignoring case and spacing. `organization` is + /// accepted for `organisation`. + pub fn parse(s: &str) -> Option { + let s = normalise_name(s); + if s == "organization" { + return Some(Self::Organisation); + } + Self::ALL.into_iter().find(|f| f.name() == s) + } +} + +impl fmt::Display for ContactField { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.name()) + } +} + +/// The field a property fills, and the label its values carry: `phone:mobile` +/// is a phone number labelled mobile. A label is any text, and phones and +/// the like have the usual few (`home`, `work`, `mobile`, `other`) while +/// anything else is shown as written. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct ContactMapping { + pub field: ContactField, + /// As written, trimmed. Compared by [`ContactMapping::same_label`]. + pub label: Option, +} + +impl ContactMapping { + /// Reads `phone`, `email:work` or `address: home`. A field with no + /// label, or an empty one, has none. + pub fn parse(s: &str) -> Option { + let (field, label) = match s.split_once(':') { + Some((field, label)) => (field, Some(label.trim())), + None => (s, None), + }; + Some(Self { + field: ContactField::parse(field)?, + label: label.filter(|l| !l.is_empty()).map(str::to_owned), + }) + } + + /// Whether two labels are the same label, ignoring case and spacing. + pub fn same_label(a: Option<&str>, b: Option<&str>) -> bool { + a.map(normalise_name) == b.map(normalise_name) + } +} + +impl fmt::Display for ContactMapping { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match &self.label { + Some(label) => write!(f, "{}:{label}", self.field), + None => write!(f, "{}", self.field), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use proptest::prelude::*; + + #[test] + fn mappings_are_read() { + let m = |field, label: Option<&str>| { + Some(ContactMapping { + field, + label: label.map(str::to_owned), + }) + }; + assert_eq!(ContactMapping::parse("phone"), m(ContactField::Phone, None)); + assert_eq!( + ContactMapping::parse(" Email : Work "), + m(ContactField::Email, Some("Work")), + ); + assert_eq!( + ContactMapping::parse("Job Title"), + None, + "the name has a hyphen, not a space" + ); + assert_eq!( + ContactMapping::parse("organization:"), + m(ContactField::Organisation, None), + "an empty label is none" + ); + assert_eq!( + ContactMapping::parse("phone:a:b"), + m(ContactField::Phone, Some("a:b")), + "a label is everything after the first colon" + ); + assert_eq!(ContactMapping::parse("fax"), None); + assert_eq!(ContactMapping::parse(""), None); + assert_eq!(ContactMapping::parse(":work"), None); + } + + #[test] + fn labels_compare_like_names() { + assert!(ContactMapping::same_label(Some("Work"), Some(" work "))); + assert!(ContactMapping::same_label(None, None)); + assert!(!ContactMapping::same_label(Some("work"), None)); + assert!(!ContactMapping::same_label(Some("work"), Some("home"))); + } + + proptest! { + /// A mapping reads back as it was written. + #[test] + fn mappings_round_trip( + field in proptest::sample::select(ContactField::ALL.to_vec()), + label in proptest::option::of("[a-z][a-z :]{0,8}[a-z]"), + ) { + let mapping = ContactMapping { field, label }; + prop_assert_eq!(ContactMapping::parse(&mapping.to_string()), Some(mapping)); + } + } +} diff --git a/crates/core/src/index.rs b/crates/core/src/index.rs index 289db975..4c01de3b 100644 --- a/crates/core/src/index.rs +++ b/crates/core/src/index.rs @@ -7,6 +7,7 @@ use quiddity_syntax::{ parse_block, parse_properties_block, ref_items, }; +use crate::contact::ContactMapping; use crate::effective::Effective; use crate::schema::{PropertySchema, ValueType}; use crate::tags; @@ -191,6 +192,9 @@ pub struct Index { pub(crate) schemas: HashMap, /// What couldn't be read of each property entity's meta-properties. pub(crate) meta_flags: HashMap>, + /// The properties that fill a contact's fields, by key as the property + /// entity is named, in key order. + contact_keys: Vec<(String, ContactMapping)>, pub(crate) effective: HashMap, /// For each inverse label and entity, the entities whose property /// refers to it, and whether directly (as written). @@ -511,6 +515,7 @@ impl Index { fn read_schemas(&mut self) { let mut schemas = HashMap::new(); let mut flags = HashMap::new(); + let mut contact_keys = Vec::new(); for (&id, info) in &self.entities { // `##tag` is for any entity, and isn't about the property. let meta: Vec<_> = info @@ -531,12 +536,24 @@ impl Index { let (schema, problems) = base.with_meta(&meta); if key == normalise_name(&info.name) { flags.insert(id, problems); + if let Some(mapping) = &schema.contact { + contact_keys.push((info.name.clone(), mapping.clone())); + } } schemas.insert(key, schema); } } + contact_keys.sort(); self.schemas = schemas; self.meta_flags = flags; + self.contact_keys = contact_keys; + } + + /// The properties that fill a contact's fields, as their entities are + /// named, in name order: what `##contact` says, for every property + /// entity that defines one. + pub fn contact_keys(&self) -> &[(String, ContactMapping)] { + &self.contact_keys } /// The schema for the property `key`. diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index a54b1d25..e083dc6e 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -12,6 +12,7 @@ mod asset; mod check; +pub mod contact; mod devices; mod effective; mod entity; diff --git a/crates/core/src/schema.rs b/crates/core/src/schema.rs index d898d1c0..db95a211 100644 --- a/crates/core/src/schema.rs +++ b/crates/core/src/schema.rs @@ -15,6 +15,7 @@ use quiddity_syntax::{ }; use crate::Flag; +use crate::contact::ContactMapping; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ValueType { @@ -94,6 +95,8 @@ pub struct PropertySchema { pub inverse: Option, /// The relation holds both ways. pub symmetric: bool, + /// `##contact`: the field of a contact the property's values fill. + pub contact: Option, } impl Default for PropertySchema { @@ -117,6 +120,7 @@ impl PropertySchema { inherits: false, inverse: None, symmetric: false, + contact: None, } } @@ -190,6 +194,16 @@ impl PropertySchema { self.inverse = Some(p.to_owned()); None } + (Meta::Contact, Some(p)) => match ContactMapping::parse(p) { + Some(mapping) => { + self.contact = Some(mapping); + None + } + None => Some( + "expected a contact field, such as phone, email:work or address:home" + .to_owned(), + ), + }, }; flags.extend(problem.map(|message| Flag::BadMeta { key: m.key.clone(), @@ -229,6 +243,7 @@ enum Meta { Inherits, Inverse, Symmetric, + Contact, } const META: &[(&str, Meta)] = &[ @@ -240,6 +255,7 @@ const META: &[(&str, Meta)] = &[ ("inherits", Meta::Inherits), ("inverse", Meta::Inverse), ("symmetric", Meta::Symmetric), + ("contact", Meta::Contact), ]; /// How `##value-type` is spelt. diff --git a/crates/core/tests/meta.rs b/crates/core/tests/meta.rs index 9be4afc5..32c306f5 100644 --- a/crates/core/tests/meta.rs +++ b/crates/core/tests/meta.rs @@ -680,3 +680,70 @@ fn a_property_entity_is_found_by_an_alias() -> Result<()> { assert!(index.defines_property(score)); Ok(()) } + +mod contact { + use super::*; + use quiddity_core::contact::{ContactField, ContactMapping}; + + fn mapping(field: ContactField, label: Option<&str>) -> ContactMapping { + ContactMapping { + field, + label: label.map(str::to_owned), + } + } + + /// A property entity's `##contact` line is its schema's mapping, and + /// the index lists the properties that have one by the name they are + /// given, so that a new value can be written under it. + #[test] + fn contact_lines_map_properties() -> Result<()> { + let graph = Graph::new(); + entity(&graph, "mobile", "type:: property\n##contact(phone:mobile)")?; + entity(&graph, "cell", "alias:: handset\n##contact(Phone)")?; + entity(&graph, "nick", "##value-type(text)")?; + let index = Index::build(&graph)?; + assert_eq!( + index.schema("mobile").contact, + Some(mapping(ContactField::Phone, Some("mobile"))) + ); + assert_eq!( + index.schema("handset").contact, + Some(mapping(ContactField::Phone, None)), + "an alias finds the schema too" + ); + assert_eq!(index.schema("nick").contact, None); + assert_eq!( + index.contact_keys(), + [ + ("cell".to_owned(), mapping(ContactField::Phone, None)), + ( + "mobile".to_owned(), + mapping(ContactField::Phone, Some("mobile")) + ), + ], + "each property once, by its own name" + ); + Ok(()) + } + + #[test] + fn unreadable_contact_lines_are_flagged() -> Result<()> { + let graph = Graph::new(); + let bad = entity(&graph, "fax", "##contact(fax)")?; + let none = entity(&graph, "tel", "##contact")?; + let index = Index::build(&graph)?; + assert_eq!(index.schema("fax").contact, None); + assert!(index.contact_keys().is_empty()); + for id in [bad, none] { + assert!( + index + .flags(id) + .iter() + .any(|f| matches!(f, Flag::BadMeta { key, .. } if key == "contact")), + "{:?}", + index.flags(id) + ); + } + Ok(()) + } +} diff --git a/docs/Built-in properties.md b/docs/Built-in properties.md index 0dbe589b..24e238fa 100644 --- a/docs/Built-in properties.md +++ b/docs/Built-in properties.md @@ -28,7 +28,9 @@ alias:: [Meta-properties, meta-property, ## properties] | `##inherits` | an entity has the other properties of the entities it refers to | | `##inverse(label)` | the name of the relation the other way round | | `##symmetric` | the relation holds both ways | + | `##contact(phone:work)` | the field of a contact that the property's values fill. [[Contacts]] | - `##values` and `##applies-to` take a query. [[Queries]] + - `##contact` takes a field, `phone`, `email`, `address`, `organisation`, `job-title`, `nickname`, `website`, `birthday` or `note`, and after a colon a label for the values: `##contact(email:work)`. It says nothing about how values are read, so a birthday also wants `##value-type(date)`. [[Contacts]] - `##cardinality` is written as UML writes multiplicity: `1`, `0..1`, `1..*`, `2..5`, or `*` for any number. It counts values, not lines: `#steps([a, b, c])` is three, and so are three `#step` lines. A list keeps its order; that is all that makes it different. - `##values`, `##transitive`, `##inherits`, `##inverse` and `##symmetric` only make sense for references, so a property with any of them is a `ref` property unless `##value-type` says otherwise. As now, a bare name in a reference is a name: with `parent` a reference, `parent:: Scotland` means `parent:: [[Scotland]]`. [[Links]] - Defaults diff --git a/docs/Contacts.md b/docs/Contacts.md new file mode 100644 index 00000000..d73ed4ae --- /dev/null +++ b/docs/Contacts.md @@ -0,0 +1,17 @@ +alias:: contact, ##contact + +- An entity that has a value for a property mapped to a contact field is a contact, and is meant to appear in the phone's own contacts. A person, a company and a plumber all qualify. **Not built yet**: only the mapping below is read. Nothing shows contacts anywhere, so these pages say what is planned, and are corrected as each part lands. +- Mapping properties to fields + - A property entity's `##contact(field)` line says which field of a contact its values fill. `##contact(field:label)` adds a label, which says what kind of one it is. [[Built-in properties]] + - ``` + mobile ← the property's entity + └─ ##contact(phone:mobile) + work email + └─ ##contact(email:work) + ``` + - The fields are `phone`, `email`, `address`, `organisation`, `job-title`, `nickname`, `website`, `birthday` and `note`. A field is not case-sensitive, and `organization` is accepted. The entity's name is the contact's name, so there is no field for it. + - A label is anything: `home`, `work`, `mobile` and `other` are what phones offer, and any other is shown as written. Labels are compared as names are, ignoring case and spacing. + - Several properties may fill one field, and one property fills one field. Each value of a property is one entry, whether written on lines of its own or as a list. [[Properties]] + - A `##contact` that can't be read is flagged where it is written, like any meta-property, and nothing is mapped. [[Built-in properties]] +- How it works + - [[quiddity-core]] reads the line into the property's schema (`PropertySchema::contact`), and `Index::contact_keys` lists the properties that have one, by the name their entity has. diff --git a/docs/User guide.md b/docs/User guide.md index 6440ba5c..8084c36c 100644 --- a/docs/User guide.md +++ b/docs/User guide.md @@ -11,6 +11,7 @@ favourite:: true - [[Properties]]: `key:: value` and `#tag`s, with [[tags]] and the built-in properties. - [[Add a file]]: drop or paste an image or any file onto a page. - [[Built-in properties]]: `##values(…)`, `##transitive`, `##inverse(…)` and the rest, to give properties types and build taxonomies, written in [[Queries]]. + - [[Contacts]]: show entities in the phone's contacts, by mapping properties to contact fields with `##contact(…)`. - [[Links]]: `[[Name]]`, with qualifiers to pick between entities with one name, and the references at the foot of each page. Names match whatever their case or [[Unicode normalisation]]. - [[Links to nowhere]]: how a link makes the entity it names. - [[Disambiguation]]: choosing between entities that share a name. diff --git a/docs/quiddity-core.md b/docs/quiddity-core.md index cf4b4299..660160c1 100644 --- a/docs/quiddity-core.md +++ b/docs/quiddity-core.md @@ -3,6 +3,7 @@ type:: crate - The [[Graph]] on [[Loro]]: blocks and entities, the index, property schemas, journals, merging [[Duplicates]], and the text format. [[Export and import]] - `crates/core`. Its `AGENTS.md` has what Loro does that the code works around: imports that wait silently for their causes, compacted snapshots ignored without a word, and blocks that come back from an undo under a new ID. [[Compaction]] [[Undo]] - The graph's settings, and `quiddity.toml`. [[Graph settings]] +- Its `contact` module is the vocabulary `##contact` maps properties onto. [[Contacts]] - The index is derived from the text and never synced: names and aliases, properties, and what each link resolves to. [[Links]] - It also reads each property's schema from its [[Built-in properties]], works out every entity's effective properties (inherited, transitive and symmetric), answers [[Queries]], and flags what doesn't fit a schema. - It reads the `##blob` line that describes a binary ([[Binaries]]): `Asset` has its hash, MIME type, size and file name, and the index lists the blocks that start with one.