asbuilt-core 0.3.1

Language-agnostic architecture model, LikeC4 emitter, config and drift check for asbuilt
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
//! A rendered view inlined into a page, so the page's colors reach it.
//!
//! The SVG `dot -Tsvg` wrote is rewritten: the prolog and comments go,
//! and Graphviz's tooltips give way to each known node's own name and a
//! link to the page that documents it, and to each edge's endpoints
//! (named on the edge too, with a wide invisible twin of its line to
//! click); `width` and `height` give way to the page's layout; ids are
//! prefixed with the view's name, so several views share a page; and
//! classes name what `theme.css` colors: each node's and group box's
//! element kind (read from the `.dot` LikeC4 wrote beside it), a node's
//! secondary text, and an edge label's backing. Only a LikeC4 render is
//! inlined. Any other SVG is left for an `<img>`, where a script in it
//! cannot run, and the rewrite drops scripts, `foreignObject` and event
//! handlers besides. Pure string work over Graphviz's own output.

use std::collections::{BTreeMap, BTreeSet};

use crate::docs::escape;

/// A rendered view as `render` left it: the SVG, and the `.dot` beside it.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ViewSource {
    pub svg: String,
    pub dot: Option<String>,
}

/// What a page knows about an element a view may draw: its kind, the
/// name its node carries on hover, and a link to where it is
/// documented (`None` for an element the page itself documents).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Node {
    pub kind: String,
    pub title: String,
    pub href: Option<String>,
}

/// A view inlined for a page: the markup, the edges it draws as pairs of
/// LikeC4 ids, in drawing order, so the page can say what each stands
/// for, and for its legend the element kinds its nodes and group boxes
/// are and the (arrowhead, line) pairs its edges are drawn with.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Inlined {
    pub html: String,
    pub edges: Vec<(String, String)>,
    pub kinds: BTreeSet<String>,
    pub edge_styles: BTreeSet<(String, String)>,
}

/// The clusters an edge is drawn out of and into (`ltail`, `lhead`),
/// keyed by the Graphviz names of the nodes its statement joins. LikeC4
/// writes them for a relation to or from an expanded element: the arrow
/// then ends at the cluster, and the page must say so, not name the
/// inner node Graphviz routed it through.
fn compound_ends(dot: &str) -> BTreeMap<(String, String), (Option<String>, Option<String>)> {
    let mut ends = BTreeMap::new();
    let mut current: Option<(String, String)> = None;
    for line in dot.lines().map(str::trim) {
        if let Some((head, _)) = line.split_once('[')
            && let Some((a, b)) = head.split_once("->")
        {
            current = Some((a.trim().to_string(), b.trim().to_string()));
        }
        if let Some(key) = &current {
            for (attr, is_head) in [("ltail=", false), ("lhead=", true)] {
                if let Some(at) = line.find(attr) {
                    let value = attr_value(&line[at + attr.len()..]);
                    let entry = ends.entry(key.clone()).or_insert((None, None));
                    if is_head {
                        entry.1 = Some(value);
                    } else {
                        entry.0 = Some(value);
                    }
                }
            }
            if line.ends_with("];") {
                current = None;
            }
        }
    }
    ends
}

/// How a view's edges are drawn: each edge statement's arrowhead and line
/// style, as LikeC4 wrote them for Graphviz, with Graphviz's own defaults
/// (`normal`, solid) where one is absent. What the legend lists is what
/// the diagram shows, whatever the view's predicates kept.
fn edge_styles(dot: &str) -> BTreeSet<(String, String)> {
    let mut styles = BTreeSet::new();
    let mut current: Option<(Option<String>, Option<String>)> = None;
    for line in dot.lines().map(str::trim) {
        if line
            .split_once('[')
            .is_some_and(|(head, _)| head.contains("->"))
        {
            current = Some((None, None));
        }
        if let Some((head, style)) = &mut current {
            for (attr, slot) in [("arrowhead=", &mut *head), ("style=", &mut *style)] {
                if let Some(at) = line.find(attr) {
                    *slot = Some(attr_value(&line[at + attr.len()..]));
                }
            }
            if line.ends_with("];") {
                let (head, style) = current.take().unwrap_or_default();
                let style = style.filter(|s| !s.is_empty());
                styles.insert((
                    head.unwrap_or_else(|| "normal".into()),
                    style.unwrap_or_else(|| "solid".into()),
                ));
            }
        }
    }
    styles
}

/// The two Graphviz names an edge's title joins, `a->b` as the SVG
/// escapes it (`a&#45;&gt;b`), any port dropped.
fn edge_ends(title: &str) -> Option<(String, String)> {
    let plain = title.replace("&#45;", "-").replace("&gt;", ">");
    let (from, to) = plain.split_once("->")?;
    let name = |s: &str| s.trim().split(':').next().unwrap_or_default().to_string();
    Some((name(from), name(to)))
}

/// Whether `dot` was written by `likec4 gen dot`, which names the view in
/// a `likec4_viewId` graph attribute.
pub fn is_likec4_dot(dot: &str) -> bool {
    dot.contains("likec4_viewId=")
}

fn is_dot_id(text: &str) -> bool {
    !text.is_empty() && text.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
}

/// An attribute value at the start of `text`: quoted, or up to the next
/// separator.
fn attr_value(text: &str) -> String {
    match text.strip_prefix('"') {
        Some(quoted) => quoted.split('"').next().unwrap_or_default().to_string(),
        None => text
            .split(|c: char| matches!(c, ',' | ']' | ';') || c.is_whitespace())
            .next()
            .unwrap_or_default()
            .to_string(),
    }
}

/// The LikeC4 id of each node and group box in a `.dot` LikeC4 wrote,
/// keyed by the Graphviz name the SVG's `<title>` carries. LikeC4 writes
/// one attribute per line, so a statement's name opens a line (`server
/// [`, `subgraph cluster_app {`) and its `likec4_id` follows; an edge
/// carries no element, and a cluster's own `graph [` line keeps its name.
pub fn likec4_ids(dot: &str) -> BTreeMap<String, String> {
    let mut ids = BTreeMap::new();
    let mut current: Option<String> = None;
    for line in dot.lines().map(str::trim) {
        if let Some(rest) = line.strip_prefix("subgraph ") {
            current = rest
                .split_whitespace()
                .next()
                .filter(|name| is_dot_id(name))
                .map(str::to_string);
        } else if let Some((head, _)) = line.split_once('[') {
            let head = head.trim();
            if head.contains("->") {
                current = None;
            } else if head != "graph" && is_dot_id(head) {
                current = Some(head.to_string());
            }
        }
        if let Some(at) = line.find("likec4_id=")
            && let Some(name) = current.take()
        {
            ids.insert(name, attr_value(&line[at + "likec4_id=".len()..]));
        }
    }
    ids
}

/// The index of the `>` that closes the tag opening `text`, outside
/// any quoted attribute value.
fn tag_end(text: &str) -> Option<usize> {
    let mut quoted = false;
    for (i, c) in text.char_indices() {
        match c {
            '"' => quoted = !quoted,
            '>' if !quoted => return Some(i),
            _ => {}
        }
    }
    None
}

#[derive(Debug)]
struct Tag {
    name: String,
    attrs: Vec<(String, String)>,
    self_closing: bool,
}

impl Tag {
    /// A start tag's name and double-quoted attributes, values kept as
    /// written; `None` for anything else.
    fn parse(inner: &str) -> Option<Tag> {
        let inner = inner.trim_end();
        let (inner, self_closing) = match inner.strip_suffix('/') {
            Some(inner) => (inner, true),
            None => (inner, false),
        };
        let name_end = inner.find(char::is_whitespace).unwrap_or(inner.len());
        let name = inner[..name_end].to_string();
        let mut attrs = Vec::new();
        let mut rest = inner[name_end..].trim_start();
        while !rest.is_empty() {
            let (key, after) = rest.split_once('=')?;
            let quoted = after.trim_start().strip_prefix('"')?;
            let (value, tail) = quoted.split_once('"')?;
            attrs.push((key.trim().to_string(), value.to_string()));
            rest = tail.trim_start();
        }
        Some(Tag {
            name,
            attrs,
            self_closing,
        })
    }

    fn get(&self, key: &str) -> Option<&str> {
        self.attrs
            .iter()
            .find(|(k, _)| k == key)
            .map(|(_, v)| v.as_str())
    }

    /// Set `key` to `value`, which the caller has escaped.
    fn set(&mut self, key: &str, value: String) {
        match self.attrs.iter_mut().find(|(k, _)| k == key) {
            Some((_, v)) => *v = value,
            None => self.attrs.push((key.to_string(), value)),
        }
    }

    fn remove(&mut self, key: &str) {
        self.attrs.retain(|(k, _)| k != key);
    }

    fn add_class(&mut self, class: &str) {
        let classes = match self.get("class") {
            Some(existing) => format!("{existing} {class}"),
            None => class.to_string(),
        };
        self.set("class", classes);
    }

    /// Write the tag; returns where its `class` value ends in `out`, so
    /// a class learned later can be inserted.
    fn write(&self, out: &mut String) -> Option<usize> {
        out.push('<');
        out.push_str(&self.name);
        let mut class_end = None;
        for (key, value) in &self.attrs {
            out.push(' ');
            out.push_str(key);
            out.push_str("=\"");
            out.push_str(value);
            if key == "class" {
                class_end = Some(out.len());
            }
            out.push('"');
        }
        out.push_str(if self.self_closing { "/>" } else { ">" });
        class_end
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Role {
    Node,
    Cluster,
    Edge,
}

#[derive(Debug)]
struct Group {
    role: Option<Role>,
    /// Where the group's open tag starts in the output, so a node can be
    /// wrapped in a link once its `<title>` names the element.
    open_at: usize,
    /// Where the group's `class` value ends in the output, until its
    /// `<title>` names the element and the kind class goes in there.
    class_end: Option<usize>,
    /// The fill of a node's first text line, its title.
    title_fill: Option<String>,
    /// Whether an `<a>` was opened before the group, to close after it.
    linked: bool,
    /// Whether an edge's line has had its twin to click: the first
    /// `<path>` is the spline, any other an arrowhead.
    hit: bool,
}

/// An attribute that could run a script: an event handler, or a link to
/// a `javascript:` URL.
fn is_active(key: &str, value: &str) -> bool {
    key.to_ascii_lowercase().starts_with("on")
        || (key.ends_with("href")
            && value
                .trim_start()
                .to_ascii_lowercase()
                .starts_with("javascript:"))
}

/// `source.svg` rewritten for a page, or `None` when it is not a LikeC4
/// render (no `.dot` beside it, or one LikeC4 did not write) or not SVG
/// in the shape Graphviz writes. `nodes` maps a LikeC4 id to what the
/// page knows about its element: a node is classed by its kind, titled
/// by its name (the hover tooltip) and wrapped in a link to its page
/// when it has one; `label` is the diagram's accessible name.
pub fn inline(
    source: &ViewSource,
    view: &str,
    label: &str,
    nodes: &BTreeMap<String, Node>,
) -> Option<Inlined> {
    let dot = source.dot.as_deref().filter(|dot| is_likec4_dot(dot))?;
    let ids = likec4_ids(dot);
    let compound = compound_ends(dot);
    let mut edges: Vec<(String, String)> = Vec::new();
    let mut kinds: BTreeSet<String> = BTreeSet::new();
    let mut rest = &source.svg[source.svg.find("<svg")?..];
    let mut out = String::with_capacity(rest.len());
    let mut groups: Vec<Group> = Vec::new();
    while let Some(lt) = rest.find('<') {
        out.push_str(&rest[..lt]);
        rest = &rest[lt..];
        if let Some(comment) = rest.strip_prefix("<!--") {
            rest = &comment[comment.find("-->")? + "-->".len()..];
            continue;
        }
        let end = tag_end(rest)?;
        let inner = &rest[1..end];
        rest = &rest[end + 1..];
        if inner.starts_with('?') || inner.starts_with('!') {
            continue;
        }
        if let Some(closing) = inner.strip_prefix('/') {
            if closing.trim() == "g" {
                let group = groups.pop();
                out.push_str("</g>");
                if group.is_some_and(|g| g.linked) {
                    out.push_str("</a>");
                }
                continue;
            }
            out.push('<');
            out.push_str(inner);
            out.push('>');
            continue;
        }
        let mut tag = Tag::parse(inner)?;
        if tag.name == "title" && !tag.self_closing {
            let close = rest.find("</title>")?;
            let name = &rest[..close];
            rest = &rest[close + "</title>".len()..];
            if let Some(group) = groups.last_mut()
                && let Some(at) = group.class_end.take()
            {
                if group.role == Some(Role::Edge) {
                    // The edge says what it joins, by id, for the page's
                    // script and for the hover.
                    if let Some((a, b)) = edge_ends(name)
                        && let (tail, head) = compound
                            .get(&(a.clone(), b.clone()))
                            .cloned()
                            .unwrap_or((None, None))
                        && let (Some(from), Some(to)) = (
                            ids.get(tail.as_deref().unwrap_or(&a)),
                            ids.get(head.as_deref().unwrap_or(&b)),
                        )
                    {
                        out.insert_str(
                            at + 1,
                            &format!(" data-from=\"{}\" data-to=\"{}\"", escape(from), escape(to)),
                        );
                        out.push_str(&format!(
                            "<title>{} \u{2192} {}</title>",
                            escape(from),
                            escape(to)
                        ));
                        edges.push((from.clone(), to.clone()));
                    }
                } else if let Some(node) = ids.get(name).and_then(|id| nodes.get(id)) {
                    out.insert_str(at, &format!(" c4-k-{}", node.kind));
                    kinds.insert(node.kind.clone());
                    if group.role == Some(Role::Node) {
                        // The element names itself on hover, and its node
                        // is a link to where the page documents it.
                        out.push_str(&format!("<title>{}</title>", escape(&node.title)));
                        if let Some(href) = &node.href {
                            out.insert_str(
                                group.open_at,
                                &format!("<a href=\"{}\">", escape(href)),
                            );
                            group.linked = true;
                        }
                    }
                }
            }
            continue;
        }
        if matches!(tag.name.as_str(), "script" | "foreignObject") {
            if !tag.self_closing {
                let close = format!("</{}>", tag.name);
                rest = &rest[rest.find(&close)? + close.len()..];
            }
            continue;
        }
        tag.attrs.retain(|(key, value)| !is_active(key, value));
        if let Some((_, id)) = tag.attrs.iter_mut().find(|(key, _)| key == "id") {
            *id = format!("{}-{id}", escape(view));
        }
        let enclosing = groups.iter().rev().find_map(|g| g.role);
        match tag.name.as_str() {
            "svg" => {
                tag.remove("width");
                tag.remove("height");
                tag.set("class", "c4".to_string());
                tag.set("data-view", escape(view));
                tag.set("role", "img".to_string());
                tag.set("aria-label", escape(label));
            }
            "g" => {
                let role = match tag.get("class") {
                    Some("node") => Some(Role::Node),
                    Some("cluster") => Some(Role::Cluster),
                    Some("edge") => Some(Role::Edge),
                    _ => None,
                };
                let open_at = out.len();
                let class_end = tag.write(&mut out);
                groups.push(Group {
                    role,
                    open_at,
                    class_end: class_end.filter(|_| role.is_some()),
                    title_fill: None,
                    linked: false,
                    hit: false,
                });
                continue;
            }
            "text" if enclosing == Some(Role::Node) => {
                let fill = tag.get("fill").unwrap_or_default().to_string();
                if let Some(node) = groups.iter_mut().rev().find(|g| g.role.is_some()) {
                    match &node.title_fill {
                        None => node.title_fill = Some(fill),
                        Some(title) if *title != fill => tag.add_class("c4-muted"),
                        Some(_) => {}
                    }
                }
            }
            "polygon" if enclosing == Some(Role::Edge) && tag.get("fill-opacity").is_some() => {
                tag.add_class("c4-label-bg");
            }
            "path" if enclosing == Some(Role::Edge) => {
                // The line is thin: a wide, invisible twin takes the clicks.
                // Only the first path, the spline; an arrowhead drawn as a
                // path keeps to its size.
                tag.write(&mut out);
                if let Some(group) = groups.last_mut()
                    && !group.hit
                    && let Some(d) = tag.get("d")
                {
                    group.hit = true;
                    out.push_str(&format!("<path class=\"c4-hit\" d=\"{d}\"/>"));
                }
                continue;
            }
            _ => {}
        }
        tag.write(&mut out);
    }
    out.push_str(rest);
    Some(Inlined {
        html: out,
        edges,
        kinds,
        edge_styles: edge_styles(dot),
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    const DOT: &str = r##"digraph {
    graph [likec4_viewId=view_app,
        bgcolor=transparent
    ];
    node [color="#2563eb",
        fillcolor="#3b82f6"
    ];
    subgraph cluster_app {
        graph [color="#57130f",
            label=<<FONT POINT-SIZE="11">APP [x]</FONT>>,
            likec4_id=app
        ];
        server [color="#2563eb",
            likec4_id="app.server"];
    }
    driver_1 [likec4_id=node_driver];
    server -> driver_1 [likec4_id="1ab"];
}
"##;

    const SVG: &str = r##"<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
 "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<!-- Generated by graphviz -->
<svg width="300pt" height="200pt"
 viewBox="0.00 0.00 300.00 200.00" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g id="graph0" class="graph" transform="scale(1 1)">
<title>G</title>
<g id="clust1" class="cluster">
<title>cluster_app</title>
<polygon fill="#722f24" stroke="#57130f" points="0,0 1,1"/>
<text x="1" y="1" fill="#ffffe5" fill-opacity="0.7">APP</text>
</g>
<!-- server -->
<g id="node1" class="node">
<title>server</title>
<polygon fill="#3b82f6" stroke="#2563eb" points="0,0 1,1"/>
<path fill="none" stroke="#2563eb" d="M1,1"/>
<text x="1" y="1" fill="#eff6ff">server</text>
<text x="1" y="2" fill="#bfdbfe">Where it runs</text>
</g>
<g id="node2" class="node">
<title>driver_1</title>
<polygon fill="#3b82f6" stroke="#2563eb" points="0,0 1,1"/>
<text x="1" y="1" fill="#eff6ff">node</text>
<text x="1" y="2" fill="#eff6ff">driver</text>
</g>
<g id="node3" class="node">
<title>stranger</title>
<polygon fill="#3b82f6" stroke="#2563eb" points="0,0 1,1"/>
</g>
<g id="edge1" class="edge">
<title>server&#45;&gt;driver_1</title>
<path fill="none" stroke="#8d8d8d" d="M0,0"/>
<path fill="#8d8d8d" stroke="#8d8d8d" d="M9,9"/>
<polygon fill="#8d8d8d" stroke="#8d8d8d" points="0,0 1,1"/>
<polygon fill="#18191b" fill-opacity="0.627451" stroke="none" points="0,0 1,1"/>
<text x="1" y="1" fill="#c9c9c9">spawns</text>
<text x="1" y="2" fill="#aaaaaa">stdio</text>
</g>
</g>
</svg>
"##;

    fn node(kind: &str, title: &str, href: Option<&str>) -> Node {
        Node {
            kind: kind.into(),
            title: title.into(),
            href: href.map(String::from),
        }
    }

    /// The page's view of the fixture's elements: the crate and its
    /// module have pages, the external none.
    fn nodes() -> BTreeMap<String, Node> {
        BTreeMap::from([
            (
                "app".to_string(),
                node("container", "app", Some("containers/app.html")),
            ),
            (
                "app.server".to_string(),
                node(
                    "component",
                    "app.server",
                    Some("containers/app.html#app.server"),
                ),
            ),
            (
                "node_driver".to_string(),
                node("process", "node_driver", None),
            ),
        ])
    }

    fn source() -> ViewSource {
        ViewSource {
            svg: SVG.into(),
            dot: Some(DOT.into()),
        }
    }

    fn inlined() -> String {
        inlined_view().html
    }

    fn inlined_view() -> Inlined {
        inline(&source(), "view_app", "app", &nodes()).expect("inlined")
    }

    #[test]
    fn likec4_ids_maps_nodes_and_group_boxes_but_not_edges() {
        let ids = likec4_ids(DOT);
        let expected: BTreeMap<String, String> = [
            ("cluster_app", "app"),
            ("driver_1", "node_driver"),
            ("server", "app.server"),
        ]
        .iter()
        .map(|(n, id)| (n.to_string(), id.to_string()))
        .collect();
        assert_eq!(ids, expected);
    }

    #[test]
    fn a_view_without_a_dot_is_not_inlined() {
        let source = ViewSource {
            svg: SVG.into(),
            dot: None,
        };
        assert_eq!(inline(&source, "view_app", "app", &nodes()), None);
    }

    #[test]
    fn a_view_whose_dot_likec4_did_not_write_is_not_inlined() {
        let source = ViewSource {
            svg: SVG.into(),
            dot: Some("digraph { a -> b }".into()),
        };
        assert_eq!(inline(&source, "view_app", "app", &nodes()), None);
    }

    #[test]
    fn the_prolog_comments_and_graphviz_s_tooltips_are_dropped() {
        // Graphviz titles every group with its own name; a node's is
        // replaced by the element's, the rest go.
        let svg = inlined();
        assert!(svg.starts_with("<svg "), "{svg}");
        for gone in [
            "<?xml",
            "<!DOCTYPE",
            "<!--",
            "-->",
            "<title>G</title>",
            "<title>cluster_app</title>",
            "<title>server</title>",
            "<title>driver_1</title>",
            "&#45;&gt;",
            "graphviz",
        ] {
            assert!(!svg.contains(gone), "{gone} in {svg}");
        }
    }

    #[test]
    fn the_root_gives_way_to_the_page_and_names_the_view() {
        let svg = inline(&source(), "view_app", "a<b", &nodes()).unwrap().html;
        let root = &svg[..svg.find('>').unwrap()];
        assert_eq!(
            root,
            "<svg viewBox=\"0.00 0.00 300.00 200.00\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" class=\"c4\" data-view=\"view_app\" role=\"img\" aria-label=\"a&lt;b\""
        );
    }

    #[test]
    fn ids_carry_the_view_name() {
        let svg = inlined();
        assert!(svg.contains("<g id=\"view_app-node1\""), "{svg}");
        assert!(!svg.contains("id=\"node1\""), "{svg}");
    }

    #[test]
    fn nodes_and_group_boxes_are_classed_by_element_kind() {
        let svg = inlined();
        assert!(
            svg.contains("<g id=\"view_app-clust1\" class=\"cluster c4-k-container\">"),
            "{svg}"
        );
        assert!(
            svg.contains("<g id=\"view_app-node1\" class=\"node c4-k-component\">"),
            "{svg}"
        );
        assert!(
            svg.contains("<g id=\"view_app-node2\" class=\"node c4-k-process\">"),
            "{svg}"
        );
    }

    #[test]
    fn a_node_with_a_page_is_a_link_to_it_titled_by_its_name() {
        let out = inlined();
        assert!(
            out.contains("<a href=\"containers/app.html#app.server\"><g id=\"view_app-node"),
            "{out}"
        );
        assert!(
            out.contains("class=\"node c4-k-component\">\n<title>app.server</title>"),
            "{out}"
        );
        assert_eq!(out.matches("</g></a>").count(), 1, "{out}");
    }

    #[test]
    fn a_node_without_a_page_is_titled_but_not_linked() {
        let out = inlined();
        assert!(
            out.contains("class=\"node c4-k-process\">\n<title>node_driver</title>"),
            "{out}"
        );
    }

    #[test]
    fn only_nodes_with_a_page_are_linked() {
        let out = inlined();
        assert_eq!(out.matches("<a ").count(), 1, "{out}");
    }

    #[test]
    fn a_group_box_is_neither_linked_nor_titled() {
        let out = inlined();
        assert!(!out.contains("<title>app</title>"), "{out}");
        assert!(!out.contains("<title>cluster_app</title>"), "{out}");
    }

    #[test]
    fn an_edge_carries_its_endpoints_ids_and_names_them() {
        let out = inlined();
        assert!(
            out.contains("class=\"edge\" data-from=\"app.server\" data-to=\"node_driver\">\n<title>app.server \u{2192} node_driver</title>"),
            "{out}"
        );
    }

    #[test]
    fn an_edge_s_line_gets_an_invisible_twin_to_click() {
        let out = inlined();
        assert!(
            out.contains("d=\"M0,0\"/><path class=\"c4-hit\" d=\"M0,0\"/>"),
            "{out}"
        );
    }

    #[test]
    fn only_an_edge_s_line_gets_a_twin_to_click() {
        // Neither the node's own path nor the edge's arrowhead path does.
        let out = inlined();
        assert_eq!(out.matches("c4-hit").count(), 1, "{out}");
    }

    #[test]
    fn an_edge_drawn_into_a_cluster_is_attributed_to_the_cluster() {
        let dot = DOT.replace(
            "server -> driver_1 [likec4_id=\"1ab\"];",
            "server -> driver_1 [ltail=cluster_app,\n        likec4_id=\"1ab\"];",
        );
        let source = ViewSource {
            svg: SVG.to_string(),
            dot: Some(dot),
        };
        let out = inline(&source, "view_app", "app", &nodes()).unwrap();
        assert_eq!(out.edges, [("app".to_string(), "node_driver".to_string())]);
        assert!(
            out.html
                .contains("data-from=\"app\" data-to=\"node_driver\""),
            "{}",
            out.html
        );
    }

    #[test]
    fn compound_ends_reads_the_clusters_an_edge_statement_names() {
        let dot = "digraph {\n    a -> b [lhead=cluster_x,\n        likec4_id=\"1\"];\n    c -> d [ltail=cluster_y, lhead=cluster_z];\n    e -> f [likec4_id=\"2\"];\n}\n";
        let ends = compound_ends(dot);
        assert_eq!(
            ends.get(&("a".to_string(), "b".to_string())),
            Some(&(None, Some("cluster_x".to_string())))
        );
        assert_eq!(
            ends.get(&("c".to_string(), "d".to_string())),
            Some(&(Some("cluster_y".to_string()), Some("cluster_z".to_string())))
        );
        assert_eq!(ends.get(&("e".to_string(), "f".to_string())), None);
    }

    #[test]
    fn the_edges_a_view_draws_are_returned_in_order() {
        assert_eq!(
            inlined_view().edges,
            [("app.server".to_string(), "node_driver".to_string())]
        );
    }

    #[test]
    fn an_edge_title_is_two_names_with_ports_dropped() {
        assert_eq!(
            edge_ends("a:p&#45;&gt;b:q"),
            Some(("a".to_string(), "b".to_string()))
        );
    }

    #[test]
    fn a_title_with_no_arrow_is_not_an_edge() {
        assert_eq!(edge_ends("lonely"), None);
    }

    #[test]
    fn a_node_the_dot_does_not_name_keeps_its_plain_class() {
        let svg = inlined();
        assert!(
            svg.contains("<g id=\"view_app-node3\" class=\"node\">"),
            "{svg}"
        );
    }

    #[test]
    fn a_node_s_title_keeps_its_class_and_its_other_lines_are_muted() {
        let svg = inlined();
        assert!(
            svg.contains("<text x=\"1\" y=\"1\" fill=\"#eff6ff\">server</text>"),
            "{svg}"
        );
        assert!(
            svg.contains(
                "<text x=\"1\" y=\"2\" fill=\"#bfdbfe\" class=\"c4-muted\">Where it runs</text>"
            ),
            "{svg}"
        );
    }

    #[test]
    fn a_title_that_wraps_keeps_every_line_as_title() {
        let svg = inlined();
        assert!(
            svg.contains("<text x=\"1\" y=\"2\" fill=\"#eff6ff\">driver</text>"),
            "{svg}"
        );
    }

    #[test]
    fn an_edge_label_s_lines_are_never_muted() {
        let svg = inlined();
        assert!(
            svg.contains("<text x=\"1\" y=\"2\" fill=\"#aaaaaa\">stdio</text>"),
            "{svg}"
        );
    }

    #[test]
    fn an_edge_s_id_is_not_given_to_an_unnamed_node_before_it() {
        let ids = likec4_ids(
            "digraph {\n    graph [likec4_viewId=v];\n    helper [shape=point];\n    helper -> server [likec4_id=\"1ab\"];\n}\n",
        );
        assert_eq!(ids, BTreeMap::new());
    }

    #[test]
    fn a_greater_than_sign_inside_an_attribute_value_does_not_end_the_tag() {
        let source = ViewSource {
            svg: SVG.replace(
                "<text x=\"1\" y=\"2\" fill=\"#bfdbfe\">",
                "<text x=\"1\" y=\"2\" data-note=\"a>b\" fill=\"#bfdbfe\">",
            ),
            dot: Some(DOT.into()),
        };
        let svg = inline(&source, "view_app", "app", &nodes()).unwrap().html;
        assert!(
            svg.contains("data-note=\"a>b\" fill=\"#bfdbfe\" class=\"c4-muted\">"),
            "{svg}"
        );
    }

    #[test]
    fn a_processing_instruction_inside_the_drawing_is_dropped() {
        let source = ViewSource {
            svg: SVG.replace("<g id=\"graph0\"", "<?render x?><g id=\"graph0\""),
            dot: Some(DOT.into()),
        };
        let svg = inline(&source, "view_app", "app", &nodes()).unwrap().html;
        assert!(!svg.contains("<?render"), "{svg}");
    }

    #[test]
    fn an_edge_label_s_backing_is_classed_and_its_arrowhead_is_not() {
        let svg = inlined();
        assert!(
            svg.contains("<polygon fill=\"#18191b\" fill-opacity=\"0.627451\" stroke=\"none\" points=\"0,0 1,1\" class=\"c4-label-bg\"/>"),
            "{svg}"
        );
        assert!(
            svg.contains("<polygon fill=\"#8d8d8d\" stroke=\"#8d8d8d\" points=\"0,0 1,1\"/>"),
            "{svg}"
        );
    }

    #[test]
    fn scripts_foreign_objects_and_event_handlers_are_dropped() {
        let svg = SVG.replace(
            "<g id=\"edge1\" class=\"edge\">",
            "<script>alert(1)</script><foreignObject><div>x</div></foreignObject><a xlink:href=\"javascript:alert(1)\" onclick=\"alert(1)\" href=\"#ok\"></a><g id=\"edge1\" class=\"edge\">",
        );
        let source = ViewSource {
            svg,
            dot: Some(DOT.into()),
        };
        let out = inline(&source, "view_app", "app", &nodes()).unwrap().html;
        for gone in ["script", "alert", "foreignObject", "<div>", "onclick"] {
            assert!(!out.contains(gone), "{gone} in {out}");
        }
        assert!(out.contains("<a href=\"#ok\"></a>"), "{out}");
    }

    #[test]
    fn an_svg_that_does_not_parse_is_not_inlined() {
        let source = ViewSource {
            svg: "<svg viewBox=\"0 0 1 1><g>".into(),
            dot: Some(DOT.into()),
        };
        assert_eq!(inline(&source, "view_app", "app", &nodes()), None);
    }

    #[test]
    fn an_inlined_view_reports_the_element_kinds_it_draws() {
        assert_eq!(
            inlined_view().kinds,
            ["component", "container", "process"]
                .map(String::from)
                .into()
        );
    }

    #[test]
    fn edge_styles_reads_each_edge_s_head_and_line() {
        let dot = "digraph {\n    edge [style=\"\"];\n    a -> b [arrowhead=onormal,\n        style=solid];\n    c -> d [arrowhead=odot, style=dotted, likec4_id=\"1\"];\n}\n";
        assert_eq!(
            edge_styles(dot),
            BTreeSet::from([
                ("odot".to_string(), "dotted".to_string()),
                ("onormal".to_string(), "solid".to_string()),
            ])
        );
    }

    #[test]
    fn an_edge_without_a_head_or_line_takes_graphviz_s_defaults() {
        let dot = "digraph {\n    a -> b [likec4_id=\"1\", style=\"\"];\n}\n";
        assert_eq!(
            edge_styles(dot),
            BTreeSet::from([("normal".to_string(), "solid".to_string())])
        );
    }
}