Skip to main content

graphity_mermaid/
mermaid_writer.rs

1//! The Mermaid writer - Java's class `MermaidWriter`.
2
3use std::borrow::Cow;
4use std::fmt;
5use std::io;
6
7use graphity_core::{Graph, NodePartition};
8
9use crate::class_defs::ClassDefs;
10use crate::selection::{Hook, Selection, TextHook, invalid_argument, is_identifier};
11
12/// The direction of a flowchart - Java's nested enum `MermaidWriter.Direction`, a type of the crate
13/// here, as Rust has no nested types.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
15pub enum Direction {
16    /// Top to bottom, `TD`; the default.
17    #[default]
18    TopDown,
19    /// Bottom to top, `BT`.
20    BottomUp,
21    /// Left to right, `LR`.
22    LeftRight,
23    /// Right to left, `RL`.
24    RightLeft,
25}
26
27impl Direction {
28    /// Returns all directions, in declaration order - Java's `Direction.values()`.
29    pub const fn values() -> [Direction; 4] {
30        [
31            Direction::TopDown,
32            Direction::BottomUp,
33            Direction::LeftRight,
34            Direction::RightLeft,
35        ]
36    }
37
38    const fn code(self) -> &'static str {
39        match self {
40            Direction::TopDown => "TD",
41            Direction::BottomUp => "BT",
42            Direction::LeftRight => "LR",
43            Direction::RightLeft => "RL",
44        }
45    }
46}
47
48/// The shape of a node, with the brackets Mermaid draws it with - Java's nested enum
49/// `MermaidWriter.Shape`, a type of the crate here, as Rust has no nested types.
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
51pub enum Shape {
52    /// A rectangle, `[...]`.
53    Rectangle,
54    /// A rectangle with rounded corners, `(...)`.
55    Rounded,
56    /// A stadium, `([...])`.
57    Stadium,
58    /// A subroutine box, `[[...]]`.
59    Subroutine,
60    /// A cylinder, `[(...)]`.
61    Cylinder,
62    /// A circle, `((...))`.
63    Circle,
64    /// A double circle, `(((...)))`.
65    DoubleCircle,
66    /// A rhombus, `{...}`.
67    Rhombus,
68    /// A hexagon, `{{...}}`.
69    Hexagon,
70}
71
72impl Shape {
73    /// Returns all shapes, in declaration order - Java's `Shape.values()`.
74    pub const fn values() -> [Shape; 9] {
75        [
76            Shape::Rectangle,
77            Shape::Rounded,
78            Shape::Stadium,
79            Shape::Subroutine,
80            Shape::Cylinder,
81            Shape::Circle,
82            Shape::DoubleCircle,
83            Shape::Rhombus,
84            Shape::Hexagon,
85        ]
86    }
87
88    /// The opening and the closing bracket.
89    const fn brackets(self) -> (&'static str, &'static str) {
90        match self {
91            Shape::Rectangle => ("[", "]"),
92            Shape::Rounded => ("(", ")"),
93            Shape::Stadium => ("([", "])"),
94            Shape::Subroutine => ("[[", "]]"),
95            Shape::Cylinder => ("[(", ")]"),
96            Shape::Circle => ("((", "))"),
97            Shape::DoubleCircle => ("(((", ")))"),
98            Shape::Rhombus => ("{", "}"),
99            Shape::Hexagon => ("{{", "}}"),
100        }
101    }
102}
103
104/// The word that starts a direction statement; whitespace after it is encoded in labels.
105const DIRECTION_WORD: &str = "direction";
106
107/// The words Mermaid's flowchart lexer reads as keywords, never as a class name; case-sensitive.
108const KEYWORDS: [&str; 16] = [
109    "style",
110    "linkStyle",
111    "interpolate",
112    "classDef",
113    "class",
114    "href",
115    "click",
116    "call",
117    "graph",
118    "flowchart",
119    "subgraph",
120    "end",
121    "_self",
122    "_blank",
123    "_parent",
124    "_top",
125];
126
127/// A writer of Mermaid flowcharts that labels and styles a graph with the caller's data by node ID and
128/// edge index. Mermaid flowcharts render in Markdown.
129///
130/// [`MermaidWriter::of`] returns a writer for a graph, the methods that configure it return the writer
131/// again, and [`write`](Self::write) or [`write_to_string`](Self::write_to_string) write the text. The
132/// graph holds no data, so labels, shapes, classes and styles come from hooks that receive a node ID
133/// or an edge index and read the caller's arrays. Here, the packages of a small program get their
134/// names from `names`. The strongly connected components `sccs` tell which packages are in a cycle,
135/// and these are drawn in red:
136///
137/// <!-- example: writing_mermaid.rs#nodeClass -->
138/// ```
139/// # use graphity_mermaid::MermaidWriter;
140/// # let dependencies = graphity_core::Graph::of(
141/// #     &[0, 3, 4, 7, 9, 10, 13, 14, 14],
142/// #     &[1, 2, 3, 7, 3, 4, 7, 4, 5, 5, 4, 6, 7, 7],
143/// # ).unwrap();
144/// # let names: &[&str] = &["app", "cli", "ui", "service", "model", "storage", "json", "util"];
145/// # let sccs = graphity_core::components::sccs_of(&dependencies);
146/// let mermaid = MermaidWriter::of(&dependencies)
147///     .node_label(|node| Some(names[node as usize].into()))
148///     .class_def("cycle", "stroke:red")
149///     .node_class(|node| {
150///         sccs.contains_cycle(sccs.scc_of(node))
151///             .then_some("cycle".into())
152///     })
153///     .write_to_string();
154/// // model and storage, the cycle, in red:
155/// //   classDef cycle stroke:red
156/// //   class n4 cycle
157/// //   class n5 cycle
158/// # assert!(mermaid.contains("  classDef cycle stroke:red\n"));
159/// # assert!(mermaid.ends_with("  class n4 cycle\n  class n5 cycle\n"));
160/// ```
161///
162/// Nodes are named by their node IDs after an `n`, such as `n4`. The text lists the class
163/// definitions, the clusters in group order with their nodes, then the nodes in no cluster, then the
164/// edges in edge index order, the classes of the nodes and the edge styles, so the same graph and
165/// hooks always give the same text. Mermaid numbers the edges in the order they are written; the
166/// writer translates edge indices into these numbers for `linkStyle`, also when a filter leaves edges
167/// out.
168///
169/// Labels are written as quoted strings: the writer turns quotes, `#`, `%`, `&`, `:`, `<`, `>` and
170/// backticks into Mermaid entity codes and line breaks into `<br>`, so that no label reads as HTML,
171/// as a Markdown string or as a directive. For the same reason, whitespace right after the word
172/// `direction` becomes an entity code, and an empty label, which Mermaid rejects, is written as one
173/// space. Whitespace there is Java's: what `Character.isWhitespace` or `Character.isSpaceChar`
174/// accepts, and U+FEFF - not quite Rust's [`char::is_whitespace`].
175///
176/// Mermaid's renderer still changes some labels. Mermaid 11 applies Markdown emphasis and backslash
177/// escapes to every label, so `2*3*4` loses its asterisks; Mermaid 12 shows a backslash before `n` as
178/// a line break. Both read `¶ß` and `fl°`, which Mermaid uses internally for entity codes, as `;` and
179/// `&`. Both also turn `fa:fa-`*name* into an icon in a node label with a line break. With
180/// `htmlLabels` set to `false`, Mermaid shows some entity codes as written, such as `&#58;` for `:`.
181///
182/// Class names must be identifiers - an ASCII letter or underscore, then ASCII letters, digits or
183/// underscores - other than a Mermaid keyword: `style`, `linkStyle`, `interpolate`, `classDef`,
184/// `class`, `href`, `click`, `call`, `graph`, `flowchart`, `subgraph`, `end`, `_self`, `_blank`,
185/// `_parent` and `_top`. Keywords are case-sensitive, so `End` is a valid class name. Styles are
186/// written as given and must not be blank or contain a line break or a semicolon. Blank means what
187/// Java's `String.isBlank` accepts.
188///
189/// The text hooks return a [`Cow`]: a `&str` into the caller's data, which lives for the writer's
190/// lifetime `'a`, is written without a copy (`Some(names[node as usize].as_str().into())`), and a
191/// computed text is a `String` (`Some(format!("v{node}").into())`). `None` is Java's `null`.
192///
193/// Mermaid renders graphs of a few hundred nodes well; for larger ones, `DotWriter` in the crate
194/// `graphity-dot` writes DOT (the language of Graphviz). A writer keeps its configuration and can
195/// write any number of times. The graph, the partition and the data the hooks read are borrowed for
196/// its lifetime `'a`. The hooks are `Fn` closures, called from [`write`](Self::write) through `&self`.
197///
198/// Since the hooks are arbitrary closures, the writer is neither `Send` nor `Sync` - Java's instances
199/// are not safe to share between threads either.
200pub struct MermaidWriter<'a> {
201    selection: Selection<'a>,
202    direction: Direction,
203    class_defs: ClassDefs<'a>,
204    node_label: Option<TextHook<'a>>,
205    edge_label: Option<TextHook<'a>>,
206    node_shape: Option<Hook<'a, Shape>>,
207    node_class: Option<TextHook<'a>>,
208    edge_style: Option<TextHook<'a>>,
209}
210
211impl<'a> MermaidWriter<'a> {
212    /// Returns a writer for `graph`, top down, with no labels, shapes, classes, clusters or filter yet.
213    /// The graph of a [`BiAdjacentGraph`](graphity_core::BiAdjacentGraph) is accepted as well, as a
214    /// `&Graph`.
215    ///
216    /// **Time:** O(1).
217    pub fn of(graph: &'a Graph) -> Self {
218        Self {
219            selection: Selection::new(graph),
220            direction: Direction::TopDown,
221            class_defs: ClassDefs::default(),
222            node_label: None,
223            edge_label: None,
224            node_shape: None,
225            node_class: None,
226            edge_style: None,
227        }
228    }
229
230    /// Sets the direction of the flowchart; without a call, it is [`Direction::TopDown`].
231    ///
232    /// **Time:** O(1).
233    #[must_use]
234    pub fn direction(mut self, direction: Direction) -> Self {
235        self.direction = direction;
236        self
237    }
238
239    /// Sets the label of each node, by node ID; `None` shows the name of the node, such as `n4`. `label`
240    /// is called with a node ID and returns the label of the node or `None`.
241    ///
242    /// **Time:** O(1).
243    #[must_use]
244    pub fn node_label(mut self, label: impl Fn(u32) -> Option<Cow<'a, str>> + 'a) -> Self {
245        self.node_label = Some(Box::new(label));
246        self
247    }
248
249    /// Sets the label of each edge, by edge index; `None` leaves an edge unlabeled. `label` is called with
250    /// an edge index and returns the label of the edge or `None`.
251    ///
252    /// **Time:** O(1).
253    #[must_use]
254    pub fn edge_label(mut self, label: impl Fn(u32) -> Option<Cow<'a, str>> + 'a) -> Self {
255        self.edge_label = Some(Box::new(label));
256        self
257    }
258
259    /// Sets the shape of each node, by node ID; `None` draws a rectangle. `shape` is called with a node ID
260    /// and returns the shape of the node or `None`.
261    ///
262    /// **Time:** O(1).
263    #[must_use]
264    pub fn node_shape(mut self, shape: impl Fn(u32) -> Option<Shape> + 'a) -> Self {
265        self.node_shape = Some(Box::new(shape));
266        self
267    }
268
269    /// Defines a class for [`node_class`](Self::node_class) to assign, written as `classDef name style`.
270    /// `name` is an identifier other than a Mermaid keyword, and `style` is the style of the class, such
271    /// as `fill:#f96,stroke:#333`.
272    ///
273    /// **Time:** O(number of classes defined + style.len()), as the definitions are a vector of pairs,
274    /// which for the handful of classes of a chart beats hashing.
275    ///
276    /// # Panics
277    /// With an `invalid argument` message if `name` is not an identifier or is a Mermaid keyword, or
278    /// `style` is blank or contains a line break or a semicolon.
279    #[must_use]
280    #[track_caller]
281    pub fn class_def(
282        mut self,
283        name: impl Into<Cow<'a, str>>,
284        style: impl Into<Cow<'a, str>>,
285    ) -> Self {
286        let name = name.into();
287        let style = style.into();
288        check_class(&name);
289        check_style(&style);
290        self.class_defs.insert(name, style);
291        self
292    }
293
294    /// Sets the class of each node, by node ID; `None` assigns none. `class_name` is called with a node ID
295    /// and returns the name of the class of the node, an identifier other than a Mermaid keyword, or
296    /// `None`.
297    ///
298    /// **Time:** O(1).
299    #[must_use]
300    pub fn node_class(mut self, class_name: impl Fn(u32) -> Option<Cow<'a, str>> + 'a) -> Self {
301        self.node_class = Some(Box::new(class_name));
302        self
303    }
304
305    /// Sets the style of each edge, by edge index, written as a `linkStyle` statement; `None` leaves an
306    /// edge in the default style. `style` is called with an edge index and returns the style of the edge,
307    /// such as `stroke:red,stroke-width:2px`, or `None`.
308    ///
309    /// **Time:** O(1).
310    #[must_use]
311    pub fn edge_style(mut self, style: impl Fn(u32) -> Option<Cow<'a, str>> + 'a) -> Self {
312        self.edge_style = Some(Box::new(style));
313        self
314    }
315
316    /// Draws each group of `partition` as a cluster (a Mermaid `subgraph`), with a label by group ID.
317    /// `label` is called with a group ID and returns the label of its cluster or `None`.
318    ///
319    /// Nodes in no group stay outside every cluster, and a group without a node to write has no cluster. A
320    /// label of `None` shows the name of the cluster: `c` and the group ID, such as `c2`. An
321    /// [`Sccs`](graphity_core::Sccs) is accepted as well, as a `&NodePartition`.
322    ///
323    /// **Time:** O(1).
324    ///
325    /// # Panics
326    /// With an `invalid argument` message if `partition` has a different node count than the graph.
327    #[must_use]
328    #[track_caller]
329    pub fn clusters(
330        mut self,
331        partition: &'a NodePartition,
332        label: impl Fn(u32) -> Option<Cow<'a, str>> + 'a,
333    ) -> Self {
334        self.selection.set_clusters(partition, Box::new(label));
335        self
336    }
337
338    /// Restricts the text to the nodes that `include` accepts and the edges between them.
339    ///
340    /// Node IDs stay those of the graph, so the hooks keep reading the same arrays.
341    ///
342    /// **Time:** O(1).
343    #[must_use]
344    pub fn node_filter(mut self, include: impl Fn(u32) -> bool + 'a) -> Self {
345        self.selection.node_filter = Some(Box::new(include));
346        self
347    }
348
349    /// Switches to the undirected reading of the graph: edges without arrowheads.
350    ///
351    /// The edges `a -> b` and `b -> a` become one, written as the edge from the lower node ID; the edge
352    /// hooks receive its edge index.
353    ///
354    /// **Time:** O(1).
355    #[must_use]
356    pub fn undirected(mut self) -> Self {
357        self.selection.undirected = true;
358        self
359    }
360
361    /// Writes the graph to `out`, as the text of a Mermaid flowchart.
362    ///
363    /// `out` is any [`io::Write`], such as a file, standard output, a socket or a `Vec<u8>`, and receives
364    /// the text in UTF-8; Java takes an `Appendable`. It is taken by value: lend it with `&mut out` to
365    /// keep using it, and flush it yourself; this call neither flushes nor closes it. Passed by value, it
366    /// is dropped when the call returns, which closes a [`File`](std::fs::File) and flushes a
367    /// [`BufWriter`](std::io::BufWriter) without reporting an error. The writer issues many small writes,
368    /// so an unbuffered `out` such as a `File` is best wrapped in a `BufWriter`, lent with `&mut` and
369    /// flushed afterwards.
370    ///
371    /// **Time:** O(node_count + edge_count + group_count), plus the hooks, with group_count the number of
372    /// groups of the partition drawn as clusters; in the undirected reading, O(log out_degree(target))
373    /// more per edge.
374    /// **Memory:** the styles of the `linkStyle` lines while it runs, as they are written last.
375    ///
376    /// # Errors
377    /// The first error of `out` - Java's `IOException`.
378    ///
379    /// # Panics
380    /// With an `invalid argument` message if a hook returns a class name that is not an identifier or is
381    /// a Mermaid keyword, or an edge style that is blank or contains a line break or a semicolon; what was
382    /// written before stays in `out`.
383    pub fn write<W: io::Write>(&self, mut out: W) -> io::Result<()> {
384        let selection = &self.selection;
385        let n = selection.graph.node_count();
386        writeln!(out, "flowchart {}", self.direction.code())?;
387        for (name, style) in self.class_defs.iter() {
388            writeln!(out, "  classDef {name} {style}")?;
389        }
390
391        if let Some(clusters) = &selection.clusters {
392            let partition = clusters.partition;
393            for group in 0..partition.group_count() {
394                let mut opened = false;
395                for &node in partition.nodes_of(group).iter() {
396                    if !selection.is_included(node) {
397                        continue;
398                    }
399                    if !opened {
400                        write!(out, "  subgraph c{group}")?;
401                        if let Some(label) = (clusters.label)(group) {
402                            out.write_all(b"[")?;
403                            quote(&label, &mut out)?;
404                            out.write_all(b"]")?;
405                        }
406                        out.write_all(b"\n")?;
407                        opened = true;
408                    }
409                    self.write_node(node, "    ", &mut out)?;
410                }
411                if opened {
412                    out.write_all(b"  end\n")?;
413                }
414            }
415        }
416        for node in 0..n {
417            if selection.is_included(node) && selection.cluster_of(node).is_none() {
418                self.write_node(node, "  ", &mut out)?;
419            }
420        }
421
422        let link = if selection.undirected { " ---" } else { " -->" };
423        // The link styles in written order, as (link ordinal, style); written last.
424        let mut styles: Vec<(u32, Cow<'a, str>)> = Vec::new();
425        let mut ordinal = 0u32;
426        selection.for_each_written_edge(|source, target, edge_index| {
427            write!(out, "  n{source}{link}")?;
428            if let Some(label) = self.edge_label.as_ref().and_then(|label| label(edge_index)) {
429                out.write_all(b"|")?;
430                quote(&label, &mut out)?;
431                out.write_all(b"|")?;
432            }
433            writeln!(out, " n{target}")?;
434            if let Some(style) = self.edge_style.as_ref().and_then(|style| style(edge_index)) {
435                check_style(&style);
436                styles.push((ordinal, style));
437            }
438            ordinal += 1;
439            Ok::<(), io::Error>(())
440        })?;
441
442        if let Some(node_class) = &self.node_class {
443            for node in 0..n {
444                if !selection.is_included(node) {
445                    continue;
446                }
447                if let Some(class_name) = node_class(node) {
448                    // Java appends the prefix before it checks the name.
449                    write!(out, "  class n{node} ")?;
450                    out.write_all(check_class(&class_name).as_bytes())?;
451                    out.write_all(b"\n")?;
452                }
453            }
454        }
455        for (ordinal, style) in &styles {
456            writeln!(out, "  linkStyle {ordinal} {style}")?;
457        }
458        Ok(())
459    }
460
461    /// Returns the text of the Mermaid flowchart, as [`write`](Self::write) writes it.
462    ///
463    /// **Time:** as for [`write`](Self::write).
464    /// **Memory:** the text for the result, whose buffer may hold up to as much again in spare capacity;
465    /// while it runs, the `linkStyle` lines as for [`write`](Self::write).
466    ///
467    /// # Panics
468    /// As for [`write`](Self::write).
469    pub fn write_to_string(&self) -> String {
470        let mut text = Vec::new();
471        self.write(&mut text)
472            .expect("writing to a Vec<u8> does not fail");
473        String::from_utf8(text).expect("the writer writes UTF-8")
474    }
475
476    fn write_node<W: io::Write>(&self, node: u32, indent: &str, out: &mut W) -> io::Result<()> {
477        write!(out, "{indent}n{node}")?;
478        let label = self.node_label.as_ref().and_then(|label| label(node));
479        let shape = self.node_shape.as_ref().and_then(|shape| shape(node));
480        if label.is_some() || shape.is_some_and(|shape| shape != Shape::Rectangle) {
481            let (open, close) = shape.unwrap_or(Shape::Rectangle).brackets();
482            out.write_all(open.as_bytes())?;
483            match &label {
484                Some(label) => quote(label, out)?,
485                None => quote(&format!("n{node}"), out)?,
486            }
487            out.write_all(close.as_bytes())?;
488        }
489        out.write_all(b"\n")
490    }
491}
492
493impl fmt::Debug for MermaidWriter<'_> {
494    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
495        f.debug_struct("MermaidWriter")
496            .field("graph", self.selection.graph)
497            .field("direction", &self.direction)
498            .field("class_defs", &self.class_defs)
499            .field("undirected", &self.selection.undirected)
500            .finish_non_exhaustive()
501    }
502}
503
504/// Returns `name` if it is an identifier other than a Mermaid keyword, with case.
505///
506/// # Panics
507/// With an `invalid argument` message otherwise.
508#[track_caller]
509fn check_class(name: &str) -> &str {
510    if !is_identifier(name) || KEYWORDS.contains(&name) {
511        invalid_argument(format_args!("not a Mermaid class name: {name}"));
512    }
513    name
514}
515
516/// Returns `style` if it is not blank and has no line break or semicolon.
517///
518/// # Panics
519/// With an `invalid argument` message otherwise.
520#[track_caller]
521fn check_style(style: &str) -> &str {
522    if is_blank(style) || style.contains(['\n', '\r', ';']) {
523        invalid_argument(format_args!(
524            "a Mermaid style must not be blank, nor contain a line break or semicolon: {style}"
525        ));
526    }
527    style
528}
529
530/// Writes `text` as a Mermaid quoted string.
531///
532/// Mermaid applies regular expressions to the whole text before parsing, strings included: `%%`
533/// starts a directive or a comment, and on a line with `style` and `:` the last `;` is dropped,
534/// which ends an entity code. Its lexer takes any line with `direction`, whitespace and a
535/// direction code for a direction statement. So `%`, `:` and whitespace right after `direction`
536/// are written as entity codes too, and an empty text, which Mermaid rejects, as one space.
537fn quote<W: io::Write>(text: &str, out: &mut W) -> io::Result<()> {
538    if text.is_empty() {
539        return out.write_all(b"\" \"");
540    }
541    out.write_all(b"\"")?;
542    let mut plain = 0;
543    for (i, c) in text.char_indices() {
544        let replacement = match c {
545            '"' => "#quot;",
546            '#' => "#35;",
547            '%' => "#37;",
548            '&' => "#38;",
549            ':' => "#58;",
550            '`' => "#96;",
551            '<' => "#lt;",
552            '>' => "#gt;",
553            '\n' => "<br>",
554            '\r' if text[i + 1..].starts_with('\n') => "",
555            '\r' => "<br>",
556            _ if is_space(c) && text[..i].ends_with(DIRECTION_WORD) => {
557                out.write_all(&text.as_bytes()[plain..i])?;
558                write!(out, "#{};", u32::from(c))?;
559                plain = i + c.len_utf8();
560                continue;
561            }
562            _ => continue,
563        };
564        out.write_all(&text.as_bytes()[plain..i])?;
565        out.write_all(replacement.as_bytes())?;
566        plain = i + c.len_utf8();
567    }
568    out.write_all(&text.as_bytes()[plain..])?;
569    out.write_all(b"\"")
570}
571
572/// Java's `Character.isWhitespace(char)`: the space, line and paragraph separators other than the
573/// non-breaking spaces U+00A0, U+2007 and U+202F, and the controls U+0009 to U+000D and U+001C to
574/// U+001F. Unlike [`char::is_whitespace`] it excludes U+0085 and includes U+001C to U+001F.
575fn is_java_whitespace(c: char) -> bool {
576    matches!(
577        c,
578        '\u{9}'..='\u{D}'
579            | '\u{1C}'..='\u{20}'
580            | '\u{1680}'
581            | '\u{2000}'..='\u{2006}'
582            | '\u{2008}'..='\u{200A}'
583            | '\u{2028}'
584            | '\u{2029}'
585            | '\u{205F}'
586            | '\u{3000}'
587    )
588}
589
590/// Whether `c` is whitespace for the `direction` check, at least everything JavaScript's `\s`
591/// matches: Java's `Character.isWhitespace(c) || Character.isSpaceChar(c) || c == '\uFEFF'`.
592/// `isSpaceChar` adds the non-breaking spaces to `isWhitespace`.
593fn is_space(c: char) -> bool {
594    is_java_whitespace(c) || matches!(c, '\u{A0}' | '\u{2007}' | '\u{202F}' | '\u{FEFF}')
595}
596
597/// Java's `String.isBlank`: empty or only `Character.isWhitespace` characters.
598fn is_blank(text: &str) -> bool {
599    text.chars().all(is_java_whitespace)
600}
601
602#[cfg(test)]
603mod tests {
604    use super::*;
605
606    /// The characters Java 25 (Unicode 16) accepts, printed by a JDK over all code points:
607    /// `Character.isWhitespace(c) || Character.isSpaceChar(c) || c == '\uFEFF'`. No supplementary
608    /// code point is whitespace in Java; Java 17 (Unicode 13) gives the same set.
609    const JAVA_SPACE: [u32; 29] = [
610        0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x001C, 0x001D, 0x001E, 0x001F, 0x0020, 0x00A0,
611        0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009,
612        0x200A, 0x2028, 0x2029, 0x202F, 0x205F, 0x3000, 0xFEFF,
613    ];
614
615    /// The characters `String.valueOf(c).isBlank()` accepts in Java 25, printed the same way.
616    const JAVA_BLANK: [u32; 25] = [
617        0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x001C, 0x001D, 0x001E, 0x001F, 0x0020, 0x1680,
618        0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2008, 0x2009, 0x200A, 0x2028,
619        0x2029, 0x205F, 0x3000,
620    ];
621
622    fn quoted(text: &str) -> String {
623        let mut out = Vec::new();
624        quote(text, &mut out).unwrap();
625        String::from_utf8(out).unwrap()
626    }
627
628    #[test]
629    fn space_and_blank_match_java_on_every_code_point() {
630        for c in (0..=0x10FFFF).filter_map(char::from_u32) {
631            let code = u32::from(c);
632            assert_eq!(is_space(c), JAVA_SPACE.contains(&code), "U+{code:04X}");
633            assert_eq!(
634                is_blank(c.encode_utf8(&mut [0; 4])),
635                JAVA_BLANK.contains(&code)
636            );
637        }
638        assert!(is_blank(""));
639        assert!(!is_blank(" x "));
640        // Where Rust's notion of whitespace differs from Java's.
641        assert!(!is_space('\u{85}') && '\u{85}'.is_whitespace());
642        assert!(is_space('\u{1F}') && !'\u{1F}'.is_whitespace());
643        assert!(is_space('\u{FEFF}') && !'\u{FEFF}'.is_whitespace());
644    }
645
646    #[test]
647    fn quote_turns_special_characters_into_entity_codes() {
648        assert_eq!(quoted(""), "\" \"");
649        assert_eq!(quoted(" "), "\" \"");
650        assert_eq!(quoted("plain text"), "\"plain text\"");
651        assert_eq!(
652            quoted("\"#%&:`<>"),
653            "\"#quot;#35;#37;#38;#58;#96;#lt;#gt;\""
654        );
655        assert_eq!(quoted("a\nb\rc\r\nd\r"), "\"a<br>b<br>c<br>d<br>\"");
656        assert_eq!(quoted("[]{}()|;'\\"), "\"[]{}()|;'\\\"");
657        assert_eq!(quoted("é\u{1F600}\0"), "\"é\u{1F600}\0\"");
658    }
659
660    #[test]
661    fn quote_encodes_only_the_first_whitespace_right_after_direction() {
662        assert_eq!(quoted("direction LR"), "\"direction#32;LR\"");
663        assert_eq!(quoted("direction  LR"), "\"direction#32; LR\"");
664        assert_eq!(quoted("xdirection\u{A0}"), "\"xdirection#160;\"");
665        assert_eq!(quoted("direction\u{FEFF}"), "\"direction#65279;\"");
666        assert_eq!(quoted("direction\u{3000}x"), "\"direction#12288;x\"");
667        assert_eq!(quoted("direction\u{1C}"), "\"direction#28;\"");
668        // Line breaks stay line breaks; U+0085 is no whitespace in Java.
669        assert_eq!(quoted("direction\nLR"), "\"direction<br>LR\"");
670        assert_eq!(quoted("direction\r\nLR"), "\"direction<br>LR\"");
671        assert_eq!(quoted("direction\u{85}LR"), "\"direction\u{85}LR\"");
672        // Case-sensitive and whole: no code without the exact word right before.
673        assert_eq!(quoted("Direction LR"), "\"Direction LR\"");
674        assert_eq!(quoted("direct ion"), "\"direct ion\"");
675        assert_eq!(quoted("directions LR"), "\"directions LR\"");
676        assert_eq!(quoted(" direction"), "\" direction\"");
677        assert_eq!(
678            quoted("a direction\tb direction c"),
679            "\"a direction#9;b direction#32;c\""
680        );
681    }
682
683    #[test]
684    fn class_names_and_styles_are_checked() {
685        for name in ["hot", "End", "STYLE", "styled", "_topLevel", "_", "c1"] {
686            assert_eq!(check_class(name), name);
687        }
688        for name in KEYWORDS
689            .into_iter()
690            .chain(["", "1st", "a b", "a-b", "a--b"])
691        {
692            assert!(
693                std::panic::catch_unwind(|| check_class(name)).is_err(),
694                "{name}"
695            );
696        }
697        for style in ["fill:red", "x", "\u{A0}", "\u{85}", "\u{FEFF}", " a "] {
698            assert_eq!(check_style(style), style);
699        }
700        for style in ["", " ", "\t", "\u{2028}", "\u{1F}", "a;b", "a\nb", "a\rb"] {
701            assert!(
702                std::panic::catch_unwind(|| check_style(style)).is_err(),
703                "{style:?}"
704            );
705        }
706    }
707
708    #[test]
709    fn values_list_every_variant_in_declaration_order() {
710        assert_eq!(
711            Direction::values().map(Direction::code),
712            ["TD", "BT", "LR", "RL"]
713        );
714        assert_eq!(Direction::default(), Direction::TopDown);
715        assert_eq!(Shape::values()[0], Shape::Rectangle);
716        assert_eq!(Shape::values()[8], Shape::Hexagon);
717    }
718}