1use super::{Coupling, CouplingId, Field, FieldId, FieldLifecycle, Graph, NodeKey, NodeSelector};
17
18impl Graph {
19 pub(crate) fn add_field(&mut self, field: Field) {
23 self.fields.insert(field.id.as_uuid(), field);
24 }
25
26 pub(crate) fn retire_field(&mut self, id: FieldId) -> bool {
29 self.set_field_lifecycle(id, FieldLifecycle::Retired)
30 }
31
32 pub(crate) fn activate_field(&mut self, id: FieldId) -> bool {
37 self.set_field_lifecycle(id, FieldLifecycle::Active)
38 }
39
40 pub(crate) fn remove_field(&mut self, id: FieldId) -> bool {
44 self.fields.remove(&id.as_uuid()).is_some()
45 }
46
47 fn set_field_lifecycle(&mut self, id: FieldId, lifecycle: FieldLifecycle) -> bool {
48 match self.fields.get_mut(&id.as_uuid()) {
49 Some(field) => {
50 field.lifecycle = lifecycle;
51 true
52 },
53 None => false,
54 }
55 }
56
57 pub fn field(&self, id: FieldId) -> Option<&Field> {
59 self.fields.get(&id.as_uuid())
60 }
61
62 pub fn fields(&self) -> impl Iterator<Item = &Field> {
64 self.fields.values()
65 }
66
67 pub(crate) fn add_coupling(&mut self, coupling: Coupling) {
71 self.couplings.insert(coupling.id.as_uuid(), coupling);
72 }
73
74 pub(crate) fn retract_coupling(&mut self, id: CouplingId) -> bool {
77 self.couplings.remove(&id.as_uuid()).is_some()
78 }
79
80 pub fn couplings(&self) -> impl Iterator<Item = &Coupling> {
82 self.couplings.values()
83 }
84
85 pub fn couplings_for_field(&self, field: FieldId) -> impl Iterator<Item = &Coupling> + '_ {
87 self.couplings.values().filter(move |c| c.field == field)
88 }
89
90 pub fn field_coupling_strength(&self, field: FieldId) -> Option<f32> {
94 self.couplings
95 .values()
96 .find(|c| c.field == field)
97 .map(|c| c.strength)
98 }
99
100 pub(crate) fn set_field_coupling_strength(&mut self, field: FieldId, strength: f32) -> bool {
104 let mut changed = false;
105 for coupling in self.couplings.values_mut() {
106 if coupling.field == field {
107 coupling.strength = strength;
108 changed = true;
109 }
110 }
111 changed
112 }
113
114 pub fn nodes_matching<'a>(
121 &'a self,
122 selector: &'a NodeSelector,
123 ) -> impl Iterator<Item = NodeKey> + 'a {
124 self.inner.inner().node_indices().filter(move |&key| {
125 if self.inner.node(key).is_none() {
126 return false;
127 }
128 match selector {
129 NodeSelector::All => true,
130 NodeSelector::Tagged(tag) => self
131 .node_content_tags(key)
132 .is_some_and(|tags| tags.contains(tag)),
133 NodeSelector::NotTagged(tag) => !self
134 .node_content_tags(key)
135 .is_some_and(|tags| tags.contains(tag)),
136 NodeSelector::Kind(kind) => self.node_classifications(key).is_some_and(|classes| {
137 classes
138 .iter()
139 .any(|c| c.status.is_affirmative() && &c.value == kind)
140 }),
141 }
142 })
143 }
144}
145
146#[cfg(test)]
147mod tests {
148 use super::super::{CouplingResponse, FieldDefinition, ScalarField};
149 use super::*;
150 use euclid::default::Point2D;
151 use uuid::Uuid;
152
153 fn fid(n: u8) -> FieldId {
154 FieldId::from_uuid(Uuid::from_bytes([n; 16]))
155 }
156 fn cid(n: u8) -> CouplingId {
157 CouplingId::from_uuid(Uuid::from_bytes([n; 16]))
158 }
159 fn scalar_field(id: FieldId) -> Field {
160 Field::new(id, FieldDefinition::Scalar(ScalarField::Const(1.0)))
161 }
162
163 #[test]
164 fn add_field_and_query_round_trip() {
165 let mut g = Graph::new();
166 let id = fid(1);
167 g.add_field(scalar_field(id).with_name("focus"));
168 assert!(g.field(id).is_some());
169 assert_eq!(g.fields().count(), 1);
170 assert_eq!(g.field(id).unwrap().name.as_deref(), Some("focus"));
171 }
172
173 #[test]
174 fn retire_field_marks_retired_keeps_definition() {
175 let mut g = Graph::new();
176 let id = fid(2);
177 g.add_field(scalar_field(id));
178 assert!(g.field(id).unwrap().is_active());
179 assert!(g.retire_field(id));
180 assert!(!g.field(id).unwrap().is_active());
181 assert!(matches!(
183 g.field(id).unwrap().definition,
184 FieldDefinition::Scalar(_)
185 ));
186 assert!(!g.retire_field(fid(99)), "unknown field retires false");
187
188 assert!(g.activate_field(id));
190 assert!(g.field(id).unwrap().is_active());
191 assert!(!g.activate_field(fid(99)), "unknown field activates false");
192 }
193
194 #[test]
195 fn couplings_add_query_and_retract() {
196 let mut g = Graph::new();
197 let field = fid(3);
198 let c = Coupling::new(
199 cid(3),
200 field,
201 NodeSelector::All,
202 CouplingResponse::AttractToMin,
203 1.0,
204 );
205 let other = Coupling::new(
206 cid(4),
207 fid(7),
208 NodeSelector::All,
209 CouplingResponse::RepelFromMax,
210 1.0,
211 );
212 g.add_coupling(c);
213 g.add_coupling(other);
214 assert_eq!(g.couplings().count(), 2);
215 assert_eq!(g.couplings_for_field(field).count(), 1);
216 assert!(g.retract_coupling(cid(3)));
217 assert_eq!(g.couplings().count(), 1);
218 assert!(!g.retract_coupling(cid(3)), "second retract is false");
219 }
220
221 #[test]
222 fn nodes_matching_resolves_selectors() {
223 let mut g = Graph::new();
224 let a = g.add_node_with_id(
225 Uuid::from_u128(1),
226 "mere://a".into(),
227 Point2D::new(0.0, 0.0),
228 );
229 let b = g.add_node_with_id(
230 Uuid::from_u128(2),
231 "mere://b".into(),
232 Point2D::new(10.0, 0.0),
233 );
234 if let Some(node) = g.inner.node_mut(a) {
235 node.tags.insert("important".to_string());
236 }
237
238 let all: Vec<_> = g.nodes_matching(&NodeSelector::All).collect();
239 assert_eq!(all.len(), 2);
240
241 let tagged: Vec<_> = g
242 .nodes_matching(&NodeSelector::Tagged("important".into()))
243 .collect();
244 assert_eq!(tagged, vec![a]);
245
246 let not_tagged: Vec<_> = g
247 .nodes_matching(&NodeSelector::NotTagged("important".into()))
248 .collect();
249 assert_eq!(not_tagged, vec![b]);
250
251 let no_kind: Vec<_> = g
252 .nodes_matching(&NodeSelector::Kind("paper".into()))
253 .collect();
254 assert!(no_kind.is_empty());
255 }
256
257 #[test]
258 fn content_tag_selectors_and_facets_follow_shared_resource_after_navigation() {
259 use crate::graph::apply::{GraphDelta, apply_graph_delta};
260 use crate::graph::facet_projection::facet_projection_for_node;
261 use crate::graph::filter::{FacetScalar, FacetValue, facet_keys};
262
263 let mut graph = Graph::new();
264 let a = graph.add_node("https://shared.test/".into(), Point2D::zero());
265 let alias = graph.add_node("https://shared.test/".into(), Point2D::zero());
266 graph.ensure_surface_resource(a).unwrap();
267 graph.ensure_surface_resource(alias).unwrap();
268 apply_graph_delta(
269 &mut graph,
270 GraphDelta::InsertNodeTag {
271 key: a,
272 tag: "important".into(),
273 },
274 );
275 assert_eq!(
276 graph
277 .nodes_matching(&NodeSelector::Tagged("important".into()))
278 .collect::<Vec<_>>(),
279 vec![a, alias]
280 );
281 assert!(
282 graph
283 .nodes_matching(&NodeSelector::NotTagged("important".into()))
284 .next()
285 .is_none()
286 );
287 for key in [a, alias] {
288 assert!(!graph.get_node(key).unwrap().tags.contains("important"));
289 let facets = facet_projection_for_node(&graph, key).unwrap();
290 assert_eq!(
291 facets[facet_keys::UDC_CLASSES],
292 FacetValue::Collection(vec![FacetScalar::Text("important".into())])
293 );
294 }
295 apply_graph_delta(
296 &mut graph,
297 GraphDelta::NavigateNode {
298 key: a,
299 url: "https://later.test/".into(),
300 },
301 );
302 assert_eq!(
303 graph
304 .nodes_matching(&NodeSelector::Tagged("important".into()))
305 .collect::<Vec<_>>(),
306 vec![alias]
307 );
308 assert_eq!(
309 graph
310 .nodes_matching(&NodeSelector::NotTagged("important".into()))
311 .collect::<Vec<_>>(),
312 vec![a]
313 );
314 assert!(
315 !facet_projection_for_node(&graph, a)
316 .unwrap()
317 .contains_key(facet_keys::UDC_CLASSES)
318 );
319 assert!(
320 facet_projection_for_node(&graph, alias)
321 .unwrap()
322 .contains_key(facet_keys::UDC_CLASSES)
323 );
324 }
325
326 #[test]
327 fn kind_selection_uses_affirmative_classifications_and_retains_review_records() {
328 use crate::types::{
329 ClassificationProvenance, ClassificationScheme, ClassificationStatus,
330 NodeClassification,
331 };
332
333 for scheme in [
334 ClassificationScheme::ContentKind,
335 ClassificationScheme::Udc,
336 ClassificationScheme::Custom("rdf:type".into()),
337 ] {
338 for (status, selected) in [
339 (ClassificationStatus::Accepted, true),
340 (ClassificationStatus::Verified, true),
341 (ClassificationStatus::Imported, true),
342 (ClassificationStatus::Suggested, false),
343 (ClassificationStatus::Rejected, false),
344 ] {
345 let mut graph = Graph::new();
346 let key = graph.add_node("https://example.test/".into(), Point2D::zero());
347 let record = NodeClassification {
348 scheme: scheme.clone(),
349 value: "article".into(),
350 label: Some("Article".into()),
351 confidence: 0.8,
352 provenance: ClassificationProvenance::UserAuthored,
353 status,
354 primary: true,
355 };
356 assert!(graph.add_node_classification(key, record.clone()));
357 let actual: Vec<_> = graph
358 .nodes_matching(&NodeSelector::Kind("article".into()))
359 .collect();
360 assert_eq!(
361 actual,
362 if selected { vec![key] } else { vec![] },
363 "{record:?}"
364 );
365 assert_eq!(graph.node_classifications(key).unwrap(), vec![record]);
366 }
367 }
368 }
369}