weavatrix_graph/model/
element.rs1use super::{NodeId, Provenance, SourceSpan};
2use crate::{AttributeValue, EdgeKind, NodeKind, Result};
3use serde::{Deserialize, Serialize};
4use std::collections::BTreeMap;
5
6#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
7pub struct Node {
8 pub id: NodeId,
9 pub label: String,
10 pub kind: NodeKind,
11 #[serde(skip_serializing_if = "Option::is_none")]
12 pub language: Option<String>,
13 #[serde(skip_serializing_if = "Option::is_none")]
14 pub span: Option<SourceSpan>,
15 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
16 pub attributes: BTreeMap<String, AttributeValue>,
17}
18
19impl Node {
20 pub fn new(id: impl Into<String>, label: impl Into<String>, kind: NodeKind) -> Result<Self> {
26 Ok(Self {
27 id: NodeId::new(id)?,
28 label: label.into(),
29 kind,
30 language: None,
31 span: None,
32 attributes: BTreeMap::new(),
33 })
34 }
35
36 #[must_use]
37 pub fn with_language(mut self, language: impl Into<String>) -> Self {
38 self.language = Some(language.into());
39 self
40 }
41
42 #[must_use]
43 pub fn with_span(mut self, span: SourceSpan) -> Self {
44 self.span = Some(span);
45 self
46 }
47
48 #[must_use]
49 pub fn with_attribute(
50 mut self,
51 key: impl Into<String>,
52 value: impl Into<AttributeValue>,
53 ) -> Self {
54 self.attributes.insert(key.into(), value.into());
55 self
56 }
57}
58
59#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
60pub struct Edge {
61 pub source: NodeId,
62 pub target: NodeId,
63 pub kind: EdgeKind,
64 pub provenance: Provenance,
65 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
66 pub attributes: BTreeMap<String, AttributeValue>,
67}
68
69impl Edge {
70 #[must_use]
71 pub fn new(source: NodeId, target: NodeId, kind: EdgeKind, provenance: Provenance) -> Self {
72 Self {
73 source,
74 target,
75 kind,
76 provenance,
77 attributes: BTreeMap::new(),
78 }
79 }
80
81 #[must_use]
82 pub fn with_attribute(
83 mut self,
84 key: impl Into<String>,
85 value: impl Into<AttributeValue>,
86 ) -> Self {
87 self.attributes.insert(key.into(), value.into());
88 self
89 }
90}