Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
170 changes: 170 additions & 0 deletions crates/core/src/contact.rs
Original file line number Diff line number Diff line change
@@ -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<Self> {
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<String>,
}

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<Self> {
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));
}
}
}
17 changes: 17 additions & 0 deletions crates/core/src/index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -191,6 +192,9 @@ pub struct Index {
pub(crate) schemas: HashMap<String, PropertySchema>,
/// What couldn't be read of each property entity's meta-properties.
pub(crate) meta_flags: HashMap<BlockId, Vec<Flag>>,
/// 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<BlockId, Effective>,
/// For each inverse label and entity, the entities whose property
/// refers to it, and whether directly (as written).
Expand Down Expand Up @@ -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
Expand All @@ -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`.
Expand Down
1 change: 1 addition & 0 deletions crates/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

mod asset;
mod check;
pub mod contact;
mod devices;
mod effective;
mod entity;
Expand Down
16 changes: 16 additions & 0 deletions crates/core/src/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ use quiddity_syntax::{
};

use crate::Flag;
use crate::contact::ContactMapping;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ValueType {
Expand Down Expand Up @@ -94,6 +95,8 @@ pub struct PropertySchema {
pub inverse: Option<String>,
/// The relation holds both ways.
pub symmetric: bool,
/// `##contact`: the field of a contact the property's values fill.
pub contact: Option<ContactMapping>,
}

impl Default for PropertySchema {
Expand All @@ -117,6 +120,7 @@ impl PropertySchema {
inherits: false,
inverse: None,
symmetric: false,
contact: None,
}
}

Expand Down Expand Up @@ -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(),
Expand Down Expand Up @@ -229,6 +243,7 @@ enum Meta {
Inherits,
Inverse,
Symmetric,
Contact,
}

const META: &[(&str, Meta)] = &[
Expand All @@ -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.
Expand Down
67 changes: 67 additions & 0 deletions crates/core/tests/meta.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(())
}
}
2 changes: 2 additions & 0 deletions docs/Built-in properties.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 17 additions & 0 deletions docs/Contacts.md
Original file line number Diff line number Diff line change
@@ -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.
1 change: 1 addition & 0 deletions docs/User guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Loading
Loading