alizarin-core 2.0.0-alpha.118

Core data structures and algorithms for Arches heritage graph and tile processing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! Card hierarchy index for UI-oriented traversal.
//!
//! Builds a pre-computed index of the card tree from graph metadata,
//! enabling card-based traversal as an alternative to node/edge traversal.

use std::collections::HashMap;

use super::cards::{StaticCard, StaticCardsXNodesXWidgets};
use super::nodes::StaticNodegroup;
use super::translatable::StaticTranslatableString;
use super::StaticNode;

/// A reference to a widget entry within a card, with resolved metadata.
#[derive(Debug, Clone)]
pub struct CardWidgetRef {
    pub node_id: String,
    pub node_alias: String,
    pub widget_id: String,
    /// Resolved widget name (e.g. "text-widget"), or empty if unknown
    pub widget_name: String,
    pub label: StaticTranslatableString,
    pub config: serde_json::Value,
    pub sortorder: i32,
    pub visible: bool,
}

/// Pre-computed index of the card hierarchy for a graph.
///
/// Built once at graph load time. Enables card-based traversal that
/// reuses the existing pseudo_cache (no data duplication).
#[derive(Debug, Clone)]
pub struct CardIndex {
    /// card_id -> child card_ids, sorted by child card sortorder
    pub card_children: HashMap<String, Vec<String>>,
    /// Root cards (nodegroup has no parentnodegroup_id), sorted by sortorder
    pub root_card_ids: Vec<String>,
    /// nodegroup_id -> card_id
    pub card_by_nodegroup: HashMap<String, String>,
    /// card_id -> widget entries, sorted by sortorder
    pub widgets_by_card: HashMap<String, Vec<CardWidgetRef>>,
    /// node_id -> node alias
    pub alias_by_node_id: HashMap<String, String>,
    /// card_id -> StaticCard reference data (name, component_id, etc.)
    pub cards_by_id: HashMap<String, CardRef>,
}

/// Lightweight card reference for traversal output.
#[derive(Debug, Clone)]
pub struct CardRef {
    pub cardid: String,
    pub name: StaticTranslatableString,
    pub component_id: String,
    pub nodegroup_id: String,
    pub sortorder: Option<i32>,
    pub visible: bool,
    pub active: bool,
}

impl From<&StaticCard> for CardRef {
    fn from(card: &StaticCard) -> Self {
        CardRef {
            cardid: card.cardid.clone(),
            name: card.name.clone(),
            component_id: card.component_id.clone(),
            nodegroup_id: card.nodegroup_id.clone(),
            sortorder: card.sortorder,
            visible: card.visible,
            active: card.active,
        }
    }
}

impl CardIndex {
    /// Collect nodegroup IDs needed to serialize a card (and its descendants).
    ///
    /// `max_depth`: `None` = all descendants, `Some(0)` = this card only,
    /// `Some(1)` = this card + immediate children, etc.
    pub fn nodegroup_ids_for_card(&self, card_id: &str, max_depth: Option<usize>) -> Vec<String> {
        let mut result = Vec::new();
        self.collect_nodegroups(card_id, max_depth, &mut result);
        result
    }

    /// Collect nodegroup IDs for all root cards (and their descendants).
    pub fn nodegroup_ids_for_roots(&self, max_depth: Option<usize>) -> Vec<String> {
        let mut result = Vec::new();
        for card_id in &self.root_card_ids {
            self.collect_nodegroups(card_id, max_depth, &mut result);
        }
        result
    }

    fn collect_nodegroups(&self, card_id: &str, max_depth: Option<usize>, out: &mut Vec<String>) {
        if let Some(card) = self.cards_by_id.get(card_id) {
            if !out.contains(&card.nodegroup_id) {
                out.push(card.nodegroup_id.clone());
            }

            if max_depth == Some(0) {
                return;
            }

            let child_depth = max_depth.map(|d| d.saturating_sub(1));
            if let Some(children) = self.card_children.get(card_id) {
                for child_id in children {
                    self.collect_nodegroups(child_id, child_depth, out);
                }
            }
        }
    }
}

/// Build a CardIndex from graph components.
///
/// The `widget_name_resolver` function maps widget_id -> widget_name.
/// Pass `crate::graph_mutator::get_widget_name_by_id` for the default resolver.
pub fn build_card_index(
    cards: &[StaticCard],
    cxnxws: &[StaticCardsXNodesXWidgets],
    nodegroups: &[StaticNodegroup],
    nodes: &[StaticNode],
    widget_name_resolver: impl Fn(&str) -> Option<String>,
) -> CardIndex {
    // 1. Build alias_by_node_id
    let alias_by_node_id: HashMap<String, String> = nodes
        .iter()
        .filter_map(|n| {
            n.alias
                .as_ref()
                .filter(|a| !a.is_empty())
                .map(|a| (n.nodeid.clone(), a.clone()))
        })
        .collect();

    // 2. Build card_by_nodegroup and cards_by_id
    let mut card_by_nodegroup: HashMap<String, String> = HashMap::new();
    let mut cards_by_id: HashMap<String, CardRef> = HashMap::new();
    for card in cards {
        card_by_nodegroup.insert(card.nodegroup_id.clone(), card.cardid.clone());
        cards_by_id.insert(card.cardid.clone(), CardRef::from(card));
    }

    // 3. Build nodegroup lookup
    let ng_by_id: HashMap<&str, &StaticNodegroup> = nodegroups
        .iter()
        .map(|ng| (ng.nodegroupid.as_str(), ng))
        .collect();

    // 4. Build card_children and root_card_ids
    let mut card_children: HashMap<String, Vec<String>> = HashMap::new();
    let mut root_card_ids: Vec<String> = Vec::new();

    for card in cards {
        let ng = ng_by_id.get(card.nodegroup_id.as_str());
        let parent_ng_id = ng.and_then(|ng| ng.parentnodegroup_id.as_ref());

        match parent_ng_id {
            Some(parent_ng) => {
                if let Some(parent_card_id) = card_by_nodegroup.get(parent_ng) {
                    card_children
                        .entry(parent_card_id.clone())
                        .or_default()
                        .push(card.cardid.clone());
                } else {
                    // Parent nodegroup has no card — treat as root
                    root_card_ids.push(card.cardid.clone());
                }
            }
            None => {
                root_card_ids.push(card.cardid.clone());
            }
        }
    }

    // Sort children by sortorder
    let card_sortorder = |card_id: &str| -> i32 {
        cards_by_id
            .get(card_id)
            .and_then(|c| c.sortorder)
            .unwrap_or(0)
    };
    for children in card_children.values_mut() {
        children.sort_by_key(|id| card_sortorder(id));
    }
    root_card_ids.sort_by_key(|id| card_sortorder(id));

    // 5. Build widgets_by_card
    let mut widgets_by_card: HashMap<String, Vec<CardWidgetRef>> = HashMap::new();
    for cxnxw in cxnxws {
        let node_alias = alias_by_node_id
            .get(&cxnxw.node_id)
            .cloned()
            .unwrap_or_default();
        let widget_name = widget_name_resolver(&cxnxw.widget_id).unwrap_or_default();

        let widget_ref = CardWidgetRef {
            node_id: cxnxw.node_id.clone(),
            node_alias,
            widget_id: cxnxw.widget_id.clone(),
            widget_name,
            label: cxnxw.label.clone(),
            config: cxnxw.config.clone(),
            sortorder: cxnxw.sortorder.unwrap_or(0),
            visible: cxnxw.visible,
        };

        widgets_by_card
            .entry(cxnxw.card_id.clone())
            .or_default()
            .push(widget_ref);
    }

    // Sort widgets by sortorder within each card
    for widgets in widgets_by_card.values_mut() {
        widgets.sort_by_key(|w| w.sortorder);
    }

    CardIndex {
        card_children,
        root_card_ids,
        card_by_nodegroup,
        widgets_by_card,
        alias_by_node_id,
        cards_by_id,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::graph::translatable::StaticTranslatableString;

    fn make_node(id: &str, alias: &str, ng_id: &str) -> StaticNode {
        StaticNode {
            nodeid: id.to_string(),
            name: alias.to_string(),
            alias: Some(alias.to_string()),
            datatype: "string".to_string(),
            nodegroup_id: Some(ng_id.to_string()),
            graph_id: "test-graph".to_string(),
            is_collector: false,
            isrequired: false,
            exportable: false,
            sortorder: Some(0),
            config: Default::default(),
            parentproperty: None,
            ontologyclass: None,
            description: None,
            fieldname: None,
            hascustomalias: false,
            issearchable: false,
            istopnode: false,
            sourcebranchpublication_id: None,
            source_identifier_id: None,
            is_immutable: None,
        }
    }

    fn make_card(id: &str, name: &str, ng_id: &str, sortorder: i32) -> StaticCard {
        StaticCard {
            cardid: id.to_string(),
            name: StaticTranslatableString::from_string(name),
            nodegroup_id: ng_id.to_string(),
            component_id: "default".to_string(),
            graph_id: "test-graph".to_string(),
            active: true,
            visible: true,
            sortorder: Some(sortorder),
            config: None,
            constraints: vec![],
            cssclass: None,
            description: None,
            helpenabled: false,
            helptext: StaticTranslatableString::empty(),
            helptitle: StaticTranslatableString::empty(),
            instructions: StaticTranslatableString::empty(),
            is_editable: Some(true),
            source_identifier_id: None,
        }
    }

    fn make_ng(id: &str, parent: Option<&str>) -> StaticNodegroup {
        StaticNodegroup {
            nodegroupid: id.to_string(),
            cardinality: Some("1".to_string()),
            parentnodegroup_id: parent.map(|s| s.to_string()),
            legacygroupid: None,
            grouping_node_id: None,
        }
    }

    fn make_cxnxw(
        card_id: &str,
        node_id: &str,
        widget_id: &str,
        sortorder: i32,
    ) -> StaticCardsXNodesXWidgets {
        StaticCardsXNodesXWidgets {
            card_id: card_id.to_string(),
            node_id: node_id.to_string(),
            widget_id: widget_id.to_string(),
            id: format!("cxnxw-{}-{}", card_id, node_id),
            label: StaticTranslatableString::from_string("Label"),
            config: serde_json::Value::Object(serde_json::Map::new()),
            sortorder: Some(sortorder),
            visible: true,
            source_identifier_id: None,
        }
    }

    #[test]
    fn test_build_card_index_basic() {
        let nodes = vec![
            make_node("n1", "field_a", "ng1"),
            make_node("n2", "field_b", "ng1"),
            make_node("n3", "field_c", "ng2"),
        ];
        let nodegroups = vec![make_ng("ng1", None), make_ng("ng2", Some("ng1"))];
        let cards = vec![
            make_card("card1", "Parent Card", "ng1", 0),
            make_card("card2", "Child Card", "ng2", 0),
        ];
        let cxnxws = vec![
            make_cxnxw("card1", "n1", "widget-text", 0),
            make_cxnxw("card1", "n2", "widget-concept", 1),
            make_cxnxw("card2", "n3", "widget-date", 0),
        ];

        let index = build_card_index(&cards, &cxnxws, &nodegroups, &nodes, |wid| {
            Some(format!("resolved-{}", wid))
        });

        // Root cards
        assert_eq!(index.root_card_ids, vec!["card1"]);

        // Card children
        assert_eq!(
            index.card_children.get("card1").unwrap(),
            &vec!["card2".to_string()]
        );
        assert!(index.card_children.get("card2").is_none());

        // Widgets
        let card1_widgets = index.widgets_by_card.get("card1").unwrap();
        assert_eq!(card1_widgets.len(), 2);
        assert_eq!(card1_widgets[0].node_alias, "field_a");
        assert_eq!(card1_widgets[1].node_alias, "field_b");

        let card2_widgets = index.widgets_by_card.get("card2").unwrap();
        assert_eq!(card2_widgets.len(), 1);
        assert_eq!(card2_widgets[0].node_alias, "field_c");

        // Alias reverse lookup
        assert_eq!(index.alias_by_node_id.get("n1").unwrap(), "field_a");
    }

    #[test]
    fn test_nodegroup_ids_for_card() {
        let nodes = vec![
            make_node("n1", "a", "ng1"),
            make_node("n2", "b", "ng2"),
            make_node("n3", "c", "ng3"),
        ];
        let nodegroups = vec![
            make_ng("ng1", None),
            make_ng("ng2", Some("ng1")),
            make_ng("ng3", Some("ng2")),
        ];
        let cards = vec![
            make_card("card1", "Root", "ng1", 0),
            make_card("card2", "Child", "ng2", 0),
            make_card("card3", "Grandchild", "ng3", 0),
        ];
        let index = build_card_index(&cards, &[], &nodegroups, &nodes, |_| None);

        // Unlimited depth: all nodegroups
        let all = index.nodegroup_ids_for_card("card1", None);
        assert_eq!(all, vec!["ng1", "ng2", "ng3"]);

        // Depth 0: just this card
        let just_root = index.nodegroup_ids_for_card("card1", Some(0));
        assert_eq!(just_root, vec!["ng1"]);

        // Depth 1: root + immediate children
        let one_level = index.nodegroup_ids_for_card("card1", Some(1));
        assert_eq!(one_level, vec!["ng1", "ng2"]);

        // From middle of tree
        let from_child = index.nodegroup_ids_for_card("card2", None);
        assert_eq!(from_child, vec!["ng2", "ng3"]);

        // All roots
        let roots = index.nodegroup_ids_for_roots(Some(0));
        assert_eq!(roots, vec!["ng1"]);
    }

    #[test]
    fn test_card_index_sortorder() {
        let nodes = vec![
            make_node("n1", "a", "ng1"),
            make_node("n2", "b", "ng2"),
            make_node("n3", "c", "ng3"),
        ];
        let nodegroups = vec![
            make_ng("ng1", None),
            make_ng("ng2", None),
            make_ng("ng3", None),
        ];
        let cards = vec![
            make_card("card1", "Third", "ng1", 2),
            make_card("card2", "First", "ng2", 0),
            make_card("card3", "Second", "ng3", 1),
        ];
        let cxnxws = vec![];

        let index = build_card_index(&cards, &cxnxws, &nodegroups, &nodes, |_| None);

        // Root cards should be sorted by sortorder
        assert_eq!(index.root_card_ids, vec!["card2", "card3", "card1"]);
    }
}