use super::{Coupling, CouplingId, Field, FieldId, FieldLifecycle, Graph, NodeKey, NodeSelector};
impl Graph {
pub(crate) fn add_field(&mut self, field: Field) {
self.fields.insert(field.id.as_uuid(), field);
}
pub(crate) fn retire_field(&mut self, id: FieldId) -> bool {
self.set_field_lifecycle(id, FieldLifecycle::Retired)
}
pub(crate) fn activate_field(&mut self, id: FieldId) -> bool {
self.set_field_lifecycle(id, FieldLifecycle::Active)
}
pub(crate) fn remove_field(&mut self, id: FieldId) -> bool {
self.fields.remove(&id.as_uuid()).is_some()
}
fn set_field_lifecycle(&mut self, id: FieldId, lifecycle: FieldLifecycle) -> bool {
match self.fields.get_mut(&id.as_uuid()) {
Some(field) => {
field.lifecycle = lifecycle;
true
},
None => false,
}
}
pub fn field(&self, id: FieldId) -> Option<&Field> {
self.fields.get(&id.as_uuid())
}
pub fn fields(&self) -> impl Iterator<Item = &Field> {
self.fields.values()
}
pub(crate) fn add_coupling(&mut self, coupling: Coupling) {
self.couplings.insert(coupling.id.as_uuid(), coupling);
}
pub(crate) fn retract_coupling(&mut self, id: CouplingId) -> bool {
self.couplings.remove(&id.as_uuid()).is_some()
}
pub fn couplings(&self) -> impl Iterator<Item = &Coupling> {
self.couplings.values()
}
pub fn couplings_for_field(&self, field: FieldId) -> impl Iterator<Item = &Coupling> + '_ {
self.couplings.values().filter(move |c| c.field == field)
}
pub fn field_coupling_strength(&self, field: FieldId) -> Option<f32> {
self.couplings
.values()
.find(|c| c.field == field)
.map(|c| c.strength)
}
pub(crate) fn set_field_coupling_strength(&mut self, field: FieldId, strength: f32) -> bool {
let mut changed = false;
for coupling in self.couplings.values_mut() {
if coupling.field == field {
coupling.strength = strength;
changed = true;
}
}
changed
}
pub fn nodes_matching<'a>(
&'a self,
selector: &'a NodeSelector,
) -> impl Iterator<Item = NodeKey> + 'a {
self.inner.inner().node_indices().filter(move |&key| {
if self.inner.node(key).is_none() {
return false;
}
match selector {
NodeSelector::All => true,
NodeSelector::Tagged(tag) => self
.node_content_tags(key)
.is_some_and(|tags| tags.contains(tag)),
NodeSelector::NotTagged(tag) => !self
.node_content_tags(key)
.is_some_and(|tags| tags.contains(tag)),
NodeSelector::Kind(kind) => self.node_classifications(key).is_some_and(|classes| {
classes
.iter()
.any(|c| c.status.is_affirmative() && &c.value == kind)
}),
}
})
}
}
#[cfg(test)]
mod tests {
use super::super::{CouplingResponse, FieldDefinition, ScalarField};
use super::*;
use euclid::default::Point2D;
use uuid::Uuid;
fn fid(n: u8) -> FieldId {
FieldId::from_uuid(Uuid::from_bytes([n; 16]))
}
fn cid(n: u8) -> CouplingId {
CouplingId::from_uuid(Uuid::from_bytes([n; 16]))
}
fn scalar_field(id: FieldId) -> Field {
Field::new(id, FieldDefinition::Scalar(ScalarField::Const(1.0)))
}
#[test]
fn add_field_and_query_round_trip() {
let mut g = Graph::new();
let id = fid(1);
g.add_field(scalar_field(id).with_name("focus"));
assert!(g.field(id).is_some());
assert_eq!(g.fields().count(), 1);
assert_eq!(g.field(id).unwrap().name.as_deref(), Some("focus"));
}
#[test]
fn retire_field_marks_retired_keeps_definition() {
let mut g = Graph::new();
let id = fid(2);
g.add_field(scalar_field(id));
assert!(g.field(id).unwrap().is_active());
assert!(g.retire_field(id));
assert!(!g.field(id).unwrap().is_active());
assert!(matches!(
g.field(id).unwrap().definition,
FieldDefinition::Scalar(_)
));
assert!(!g.retire_field(fid(99)), "unknown field retires false");
assert!(g.activate_field(id));
assert!(g.field(id).unwrap().is_active());
assert!(!g.activate_field(fid(99)), "unknown field activates false");
}
#[test]
fn couplings_add_query_and_retract() {
let mut g = Graph::new();
let field = fid(3);
let c = Coupling::new(
cid(3),
field,
NodeSelector::All,
CouplingResponse::AttractToMin,
1.0,
);
let other = Coupling::new(
cid(4),
fid(7),
NodeSelector::All,
CouplingResponse::RepelFromMax,
1.0,
);
g.add_coupling(c);
g.add_coupling(other);
assert_eq!(g.couplings().count(), 2);
assert_eq!(g.couplings_for_field(field).count(), 1);
assert!(g.retract_coupling(cid(3)));
assert_eq!(g.couplings().count(), 1);
assert!(!g.retract_coupling(cid(3)), "second retract is false");
}
#[test]
fn nodes_matching_resolves_selectors() {
let mut g = Graph::new();
let a = g.add_node_with_id(
Uuid::from_u128(1),
"mere://a".into(),
Point2D::new(0.0, 0.0),
);
let b = g.add_node_with_id(
Uuid::from_u128(2),
"mere://b".into(),
Point2D::new(10.0, 0.0),
);
if let Some(node) = g.inner.node_mut(a) {
node.tags.insert("important".to_string());
}
let all: Vec<_> = g.nodes_matching(&NodeSelector::All).collect();
assert_eq!(all.len(), 2);
let tagged: Vec<_> = g
.nodes_matching(&NodeSelector::Tagged("important".into()))
.collect();
assert_eq!(tagged, vec![a]);
let not_tagged: Vec<_> = g
.nodes_matching(&NodeSelector::NotTagged("important".into()))
.collect();
assert_eq!(not_tagged, vec![b]);
let no_kind: Vec<_> = g
.nodes_matching(&NodeSelector::Kind("paper".into()))
.collect();
assert!(no_kind.is_empty());
}
#[test]
fn content_tag_selectors_and_facets_follow_shared_resource_after_navigation() {
use crate::graph::apply::{GraphDelta, apply_graph_delta};
use crate::graph::facet_projection::facet_projection_for_node;
use crate::graph::filter::{FacetScalar, FacetValue, facet_keys};
let mut graph = Graph::new();
let a = graph.add_node("https://shared.test/".into(), Point2D::zero());
let alias = graph.add_node("https://shared.test/".into(), Point2D::zero());
graph.ensure_surface_resource(a).unwrap();
graph.ensure_surface_resource(alias).unwrap();
apply_graph_delta(
&mut graph,
GraphDelta::InsertNodeTag {
key: a,
tag: "important".into(),
},
);
assert_eq!(
graph
.nodes_matching(&NodeSelector::Tagged("important".into()))
.collect::<Vec<_>>(),
vec![a, alias]
);
assert!(
graph
.nodes_matching(&NodeSelector::NotTagged("important".into()))
.next()
.is_none()
);
for key in [a, alias] {
assert!(!graph.get_node(key).unwrap().tags.contains("important"));
let facets = facet_projection_for_node(&graph, key).unwrap();
assert_eq!(
facets[facet_keys::UDC_CLASSES],
FacetValue::Collection(vec![FacetScalar::Text("important".into())])
);
}
apply_graph_delta(
&mut graph,
GraphDelta::NavigateNode {
key: a,
url: "https://later.test/".into(),
},
);
assert_eq!(
graph
.nodes_matching(&NodeSelector::Tagged("important".into()))
.collect::<Vec<_>>(),
vec![alias]
);
assert_eq!(
graph
.nodes_matching(&NodeSelector::NotTagged("important".into()))
.collect::<Vec<_>>(),
vec![a]
);
assert!(
!facet_projection_for_node(&graph, a)
.unwrap()
.contains_key(facet_keys::UDC_CLASSES)
);
assert!(
facet_projection_for_node(&graph, alias)
.unwrap()
.contains_key(facet_keys::UDC_CLASSES)
);
}
#[test]
fn kind_selection_uses_affirmative_classifications_and_retains_review_records() {
use crate::types::{
ClassificationProvenance, ClassificationScheme, ClassificationStatus,
NodeClassification,
};
for scheme in [
ClassificationScheme::ContentKind,
ClassificationScheme::Udc,
ClassificationScheme::Custom("rdf:type".into()),
] {
for (status, selected) in [
(ClassificationStatus::Accepted, true),
(ClassificationStatus::Verified, true),
(ClassificationStatus::Imported, true),
(ClassificationStatus::Suggested, false),
(ClassificationStatus::Rejected, false),
] {
let mut graph = Graph::new();
let key = graph.add_node("https://example.test/".into(), Point2D::zero());
let record = NodeClassification {
scheme: scheme.clone(),
value: "article".into(),
label: Some("Article".into()),
confidence: 0.8,
provenance: ClassificationProvenance::UserAuthored,
status,
primary: true,
};
assert!(graph.add_node_classification(key, record.clone()));
let actual: Vec<_> = graph
.nodes_matching(&NodeSelector::Kind("article".into()))
.collect();
assert_eq!(
actual,
if selected { vec![key] } else { vec![] },
"{record:?}"
);
assert_eq!(graph.node_classifications(key).unwrap(), vec![record]);
}
}
}
}