use serde::{Deserialize, Serialize};
use super::field::{CouplingId, FieldId};
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum NodeSelector {
All,
Tagged(String),
Kind(String),
NotTagged(String),
}
pub const COUPLING_VOCAB: &str = "https://mere.computer/ns/coupling#";
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, strum::EnumIter)]
pub enum CouplingResponse {
AttractToMin,
RepelFromMax,
AlignVelocity,
FlowAdvect,
DampenInside { factor: f32 },
ContainmentWall,
Open { predicate: String },
}
impl CouplingResponse {
pub fn open(predicate: impl Into<String>) -> Self {
let predicate = predicate.into();
Self::from_iri(&predicate).unwrap_or(Self::Open { predicate })
}
pub fn is_force(&self) -> bool {
!matches!(self, Self::Open { .. })
}
pub fn predicate(&self) -> Option<&str> {
match self {
Self::Open { predicate } => Some(predicate),
_ => None,
}
}
pub fn recognized_iri(&self) -> Option<&'static str> {
Some(match self {
Self::AttractToMin => "https://mere.computer/ns/coupling#attract-to-min",
Self::RepelFromMax => "https://mere.computer/ns/coupling#repel-from-max",
Self::AlignVelocity => "https://mere.computer/ns/coupling#align-velocity",
Self::FlowAdvect => "https://mere.computer/ns/coupling#flow-advect",
Self::DampenInside { .. } => "https://mere.computer/ns/coupling#dampen-inside",
Self::ContainmentWall => "https://mere.computer/ns/coupling#containment-wall",
Self::Open { .. } => return None,
})
}
pub fn from_iri(iri: &str) -> Option<Self> {
Some(match iri {
"https://mere.computer/ns/coupling#attract-to-min" => Self::AttractToMin,
"https://mere.computer/ns/coupling#repel-from-max" => Self::RepelFromMax,
"https://mere.computer/ns/coupling#align-velocity" => Self::AlignVelocity,
"https://mere.computer/ns/coupling#flow-advect" => Self::FlowAdvect,
"https://mere.computer/ns/coupling#dampen-inside" => Self::DampenInside { factor: 1.0 },
"https://mere.computer/ns/coupling#containment-wall" => Self::ContainmentWall,
_ => return None,
})
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Coupling {
pub id: CouplingId,
pub field: FieldId,
pub selector: NodeSelector,
pub response: CouplingResponse,
pub strength: f32,
}
impl Coupling {
pub fn new(
id: CouplingId,
field: FieldId,
selector: NodeSelector,
response: CouplingResponse,
strength: f32,
) -> Self {
Self {
id,
field,
selector,
response,
strength,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use uuid::Uuid;
fn uuid(n: u8) -> Uuid {
Uuid::from_bytes([n; 16])
}
#[test]
fn coupling_serde_roundtrip() {
let c = Coupling::new(
CouplingId::from_uuid(uuid(1)),
FieldId::from_uuid(uuid(2)),
NodeSelector::Kind("paper".into()),
CouplingResponse::AttractToMin,
1.0,
);
let s = serde_json::to_string(&c).unwrap();
assert_eq!(c, serde_json::from_str::<Coupling>(&s).unwrap());
}
#[test]
fn selector_and_response_variants_roundtrip() {
let selectors = [
NodeSelector::All,
NodeSelector::Tagged("important".into()),
NodeSelector::Kind("paper".into()),
NodeSelector::NotTagged("archived".into()),
];
for s in &selectors {
let j = serde_json::to_string(s).unwrap();
assert_eq!(*s, serde_json::from_str::<NodeSelector>(&j).unwrap());
}
let responses = [
CouplingResponse::AttractToMin,
CouplingResponse::RepelFromMax,
CouplingResponse::AlignVelocity,
CouplingResponse::FlowAdvect,
CouplingResponse::DampenInside { factor: 0.3 },
CouplingResponse::ContainmentWall,
];
for r in &responses {
let j = serde_json::to_string(r).unwrap();
assert_eq!(*r, serde_json::from_str::<CouplingResponse>(&j).unwrap());
}
}
#[test]
fn open_response_serde_roundtrip() {
let r = CouplingResponse::Open {
predicate: format!("{COUPLING_VOCAB}visual/highlight"),
};
assert!(!r.is_force());
assert_eq!(
r.predicate(),
Some("https://mere.computer/ns/coupling#visual/highlight")
);
let j = serde_json::to_string(&r).unwrap();
assert_eq!(r, serde_json::from_str::<CouplingResponse>(&j).unwrap());
}
#[test]
fn recognized_response_iri_round_trips() {
use strum::IntoEnumIterator;
for r in CouplingResponse::iter().filter(|r| r.is_force()) {
let iri = r.recognized_iri().expect("force core has an IRI");
let back = CouplingResponse::from_iri(iri).expect("IRI is recognized");
assert_eq!(
back.recognized_iri(),
Some(iri),
"IRI round-trips for {r:?}"
);
}
assert!(
CouplingResponse::Open {
predicate: "x".into()
}
.recognized_iri()
.is_none()
);
assert!(CouplingResponse::from_iri("https://example.org/unknown").is_none());
}
#[test]
fn open_canonicalizes_recognized_iri() {
assert_eq!(
CouplingResponse::open("https://mere.computer/ns/coupling#attract-to-min"),
CouplingResponse::AttractToMin
);
assert!(matches!(
CouplingResponse::open(format!("{COUPLING_VOCAB}trigger/fire")),
CouplingResponse::Open { .. }
));
}
}