app: cherry-pick rune's pause and sound fixes onto the checkout

Rune comes from app/vendor/rune now, a checkout of 63ad0209 on branch
ported, carrying the four commits of upstream issues 1320 (a pause while
a clip is layered holds the layer's picture and time) and 1325 (a video's
sound is read ahead of the clock and leads it). Both were written against
eb9f1104 and ported across the refactors since. The faults are the first
two and the third in docs/rune-upstream.md; the app's workarounds in
review.rs stay until the fixes arrive upstream.
This commit is contained in:
vhaudiquet committed 2026-11-22 22:16:30 +01:00
1 parent 80fef698ce
commit 5bf262b82b
3795 files changed
+663463 -28

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
[package]
name = "rune-mermaid"
version = "0.0.1"
edition.workspace = true
license.workspace = true
description = "Native Mermaid diagrams for Rune: flowcharts, sequence diagrams and state diagrams, drawn with Rune shapes and text."
[dependencies]
rune = { workspace = true }
[dev-dependencies]
rune = { workspace = true, default-features = true }
[lints]
workspace = true
+65
View File
@@ -0,0 +1,65 @@
flowchart LR
classDef done fill:#1f3d2a,stroke:#3fb950,color:#e6edf3
classDef doing fill:#3d3416,stroke:#d29922,color:#e6edf3
classDef waiting fill:#162a3d,stroke:#58a6ff,color:#e6edf3
classDef blocked fill:#21262d,stroke:#6e7681,color:#c9d1d9
subgraph PREP["Prep, done"]
t12["t12 tokens carry byte spans"]:::done
t07["t07 grammar table in groups"]:::done
end
subgraph S2["Stage 2: first pass on the new parser (the pilot)"]
t31["t31 cache sees grammar edits"]:::waiting
t35["t35 baseline = pinned release, built from source"]:::doing
t44["t44 lint_unused, the pass rewritten"]:::doing
t11["t11 old-vs-new compare hook"]:::doing
t36["t36 link the new parser into the old tool"]:::blocked
t37["t37 PILOT: the pass runs in the new build"]:::blocked
end
subgraph IR["AST track: the new parser reads the old tool's syntax trees"]
t84["t84 formatter stops using the old evaluator"]:::doing
t33["t33 AST binary format + reader"]:::blocked
t34["t34 generate both sides from the grammar table"]:::blocked
t38["t38 AST verifier, rewritten"]:::blocked
end
subgraph S3["Stage 3: formatter on the new parser"]
t39["t39 layout, spacing, names"]:::blocked
t40["t40 comments, literals, source maps"]:::blocked
t41["t41 functions and core forms"]:::blocked
t42["t42 imports and exports"]:::blocked
t43["t43 macros, attribute glue"]:::blocked
t45["t45 byte-exact match with the old one, at most 2x slower"]:::blocked
t46["t46 the tool formats itself identically"]:::blocked
t47["t47 delete the old formatter"]:::blocked
end
t31 --> t35 --> t36
t84 --> t33 --> t34
t33 --> t36
t36 --> t37
t11 --> t37
t44 --> t37
t34 --> t38
t36 --> t38
t34 --> t39
t34 --> t40
t39 --> t41
t40 --> t41
t41 --> t42
t41 --> t43
t42 --> t45
t43 --> t45
t36 --> t45
t11 --> t45
t45 --> t46 --> t47
subgraph KEY["Key"]
k1["done"]:::done
k2["building now"]:::doing
k3["built, waiting to land"]:::waiting
k4["not started"]:::blocked
end
@@ -0,0 +1,40 @@
//! Searchable label runs from a laid-out Mermaid diagram, not the syntax that produced it.
use std::rc::Rc;
use rune::{Color, TextHighlight};
use super::{Scene, scenes};
use crate::{DiagramStyle, Drawing, Hover};
/// One prepared layout. Its title and labels can be indexed once, then drawn again with
/// different text highlights without parsing the source or laying the diagram out again.
#[derive(Clone)]
pub struct DrawingModel {
scene: Rc<Scene>,
style: DiagramStyle,
}
/// Prepare the same layout as [`crate::render_drawing`], retaining it for text lookup.
pub fn prepare_drawing(src: &str, style: &DiagramStyle, hover: Hover, color: Color) -> Option<DrawingModel> {
let hover = (hover != Hover::Off).then_some((hover, color));
Some(DrawingModel { scene: scenes::built(src, style, hover, None).0?, style: *style })
}
impl DrawingModel {
/// `(element key, shown text)` in drawing order. Includes a displayed title, but not
/// node IDs, source comments or the duplicate paint used to light a label on hover.
pub fn labels(&self) -> impl Iterator<Item = (&str, &str)> {
self.scene.title.as_deref().map(|s| ("title", s)).into_iter().chain(
self.scene.label_keys.iter().zip(&self.scene.labels).map(|((key, _), l)| (key.as_str(), l.text.as_str()))
)
}
/// Whether text ranges for `other` still describe this exact layout.
pub fn same_layout(&self, other: &Self) -> bool { Rc::ptr_eq(&self.scene, &other.scene) }
/// Draw with UTF-8 byte ranges local to each label. Keys are the ones returned by
/// [`Self::labels`]. A hover copy uses the same marks as the label underneath it.
pub fn draw(&self, marks: impl Fn(&str) -> Vec<TextHighlight>) -> Drawing {
let (el, size) = self.scene.drawing(&self.style, Some(&marks));
Drawing { el, size, surface: self.style.surface, surface_border: self.style.surface_border }
}
}
+214
View File
@@ -0,0 +1,214 @@
//! What hovering a flowchart or state diagram lights up. Each node keeps its outline as a region
//! and each edge a copy of its drawing in the hover colour, its label's index and a backing for
//! it. The finished scene puts a hover group over every node that shows its edges and their
//! labels (and with [`Hover::Neighbours`] the outlines they reach), and a chain of hover groups
//! along every edge and over its label that show that edge and its label. Hover groups light by
//! their rectangles alone, so an edge's rectangles are cut back from every node's box and a node
//! under the pointer always wins.
use std::collections::HashMap;
use rune::{Color, LineCap, Shape};
use super::parts::{Kind, Part};
use super::{Canvas, Op, dist, lerp, rounded_rect};
/// What hovering a flowchart or state diagram node lights up.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Hover {
/// Nothing.
Off,
/// The edges in and out of it, with their labels.
#[default]
Edges,
/// Its edges, its outline and the outlines of the nodes they reach.
Neighbours,
}
/// How far either side of an edge's line the pointer lights it, in points.
pub(crate) const EDGE_SLOP: f32 = 8.0;
/// The most rectangles one edge's line is split into, and in a whole diagram.
const EDGE_HITS: usize = 16;
const ALL_EDGE_HITS: usize = 1200;
pub(crate) struct Trace {
pub ends: (usize, usize),
/// The edge it is, as its piece is keyed.
pub part: Option<Part>,
pub ops: Vec<Op>,
/// The line as drawn, for its hit rectangles.
pub line: Vec<[f32; 2]>,
/// Its label's index in [`Canvas::labels`] and its box, `[x0, y0, x1, y1]`.
pub label: Option<(usize, [f32; 4])>,
}
/// One hover group: what it is, keyed by the piece it lights (`hover:n:A`, `hover:e:A>B.0`, and
/// `hover:e:A>B.t` over its label) so it stays that node or edge however the layout moves, where (`[x, y, w, h]`, finished), what it
/// draws lit, and which labels it shows in the hover colour.
pub(crate) struct Spot {
pub key: String,
pub rect: [f32; 4],
pub lit: Shape,
pub labels: Vec<usize>,
}
impl Canvas {
/// Node `i` drawn as `outline`: hovering it lights up its traces.
pub(crate) fn region(&mut self, i: usize, outline: Vec<[f32; 2]>) {
if self.hover.is_none() {
return;
}
if self.regions.len() <= i {
self.regions.resize(i + 1, Vec::new());
}
self.regions[i] = outline;
}
/// The ops drawn since `start` are the edge `from` → `to`: keeps a copy with every `line`
/// colour turned to the hover colour, a little heavier, for hovering either end or the edge.
/// `label` is the label drawn with it (its index in [`Canvas::labels`] and box) and the colour
/// behind it, which its lit backing covers before tinting.
pub(crate) fn trace(&mut self, from: usize, to: usize, start: usize, line: Color, label: Option<(usize, [f32; 4], Color)>) {
let Some((_, lit)) = self.hover else { return };
let mut path = Vec::new();
let mut ops: Vec<Op> = self.ops[start..]
.iter()
.map(|op| match op {
Op::Fill(p, c) if *c == line => Op::Fill(p.clone(), lit),
Op::Stroke { points, closed, width, cap, color } if *color == line => {
if !closed {
path.extend_from_slice(points);
}
Op::Stroke { points: points.clone(), closed: *closed, width: width + 0.5, cap: *cap, color: lit }
}
op => op.clone(),
})
.collect();
if let Some((_, g, back)) = label {
let pill = rounded_rect(g[0], g[1], g[2], g[3], 4.0);
ops.push(Op::Fill(pill.clone(), back));
ops.push(Op::Fill(pill.clone(), Color { a: lit.a * 0.14, ..lit }));
ops.push(Op::Stroke { points: pill, closed: true, width: 1.0, cap: LineCap::Round, color: lit });
}
let part = self.current_part();
self.traces.push(Trace { ends: (from, to), part, ops, line: path, label: label.map(|(i, g, _)| (i, g)) });
}
/// Every hover group, edges first so a node's lit drawing lands over theirs.
pub(crate) fn hovers(&self, map: impl Fn([f32; 2]) -> [f32; 2], paint: impl Fn(Shape, &Op) -> Shape) -> Vec<Spot> {
let Some((reach, lit)) = self.hover else { return Vec::new() };
let drawn = |v: usize| self.regions.get(v).is_some_and(|r| r.len() >= 3);
let rect = |lo: [f32; 2], hi: [f32; 2]| {
let (a, z) = (map(lo), map(hi));
[a[0], a[1], z[0] - a[0], z[1] - a[1]]
};
let boxes: Vec<[f32; 4]> = (0..self.regions.len()).filter(|&v| drawn(v)).map(|v| {
let (lo, hi) = bounds(&self.regions[v]);
rect(lo, hi)
}).collect();
let outline = |v: usize| Op::Stroke { points: self.regions[v].clone(), closed: true, width: 1.0, cap: LineCap::Round, color: lit };
let mut spots = Vec::new();
let mut seen: HashMap<String, usize> = HashMap::new();
let mut key = |part: Part| {
let base = format!("hover:{}", self.part_key(&part).0);
let n = seen.entry(base.clone()).or_insert(0);
*n += 1;
if *n == 1 { base } else { format!("{base}~{}", *n - 1) }
};
let mut budget = ALL_EDGE_HITS;
for (k, t) in self.traces.iter().enumerate() {
let edge = key(t.part.clone().unwrap_or(Part::Index(Kind::Edge, k)));
let shape = t.ops.iter().fold(Shape::new(), &paint);
let labels: Vec<usize> = t.label.iter().map(|l| l.0).collect();
let line: Vec<[f32; 2]> = t.line.iter().map(|&p| map(p)).collect();
let mut hits = cut_away(line_hits(&line, EDGE_SLOP), &boxes);
hits.truncate(budget);
budget -= hits.len();
for (j, r) in hits.into_iter().enumerate() {
spots.push(Spot { key: format!("{edge}.{j}"), rect: r, lit: shape.clone(), labels: labels.clone() });
}
if let Some((_, g)) = t.label {
spots.push(Spot { key: format!("{edge}.t"), rect: rect([g[0], g[1]], [g[2], g[3]]), lit: shape.clone(), labels: labels.clone() });
}
}
for v in (0..self.regions.len()).filter(|&v| drawn(v)) {
let mine: Vec<&Trace> = self.traces.iter().filter(|t| t.ends.0 == v || t.ends.1 == v).collect();
if mine.is_empty() {
continue;
}
let mut shape = mine.iter().flat_map(|t| &t.ops).fold(Shape::new(), &paint);
if reach == Hover::Neighbours {
let mut near: Vec<usize> = mine.iter().flat_map(|t| [t.ends.0, t.ends.1]).filter(|&u| drawn(u)).collect();
near.sort_unstable();
near.dedup();
shape = near.into_iter().fold(shape, |s, u| paint(s, &outline(u)));
}
let (lo, hi) = bounds(&self.regions[v]);
let labels = mine.iter().filter_map(|t| t.label.map(|l| l.0)).collect();
spots.push(Spot { key: key(Part::Index(Kind::Node, v)), rect: rect(lo, hi), lit: shape, labels });
}
spots
}
}
fn bounds(pts: &[[f32; 2]]) -> ([f32; 2], [f32; 2]) {
pts.iter().fold(([f32::MAX; 2], [f32::MIN; 2]), |(lo, hi), p| ([lo[0].min(p[0]), lo[1].min(p[1])], [hi[0].max(p[0]), hi[1].max(p[1])]))
}
/// Rectangles (`[x, y, w, h]`) covering `line` to `slop` either side: a run along it grows while
/// its box stays thin, so straight runs take one rectangle and curves a few; at most [`EDGE_HITS`].
pub(crate) fn line_hits(line: &[[f32; 2]], slop: f32) -> Vec<[f32; 4]> {
// Points at most a few points apart, so a long diagonal splits too.
let mut pts: Vec<[f32; 2]> = Vec::new();
for w in line.windows(2) {
let n = (dist(w[0], w[1]) / 4.0).ceil().clamp(1.0, 200.0) as usize;
pts.extend((0..n).map(|i| lerp(w[0], w[1], i as f32 / n as f32)));
}
pts.extend(line.last());
pts.retain(|p| p[0].is_finite() && p[1].is_finite());
if pts.is_empty() {
return Vec::new();
}
let mut thin = slop;
loop {
let mut out = Vec::new();
let (mut lo, mut hi) = (pts[0], pts[0]);
for w in pts.windows(2) {
let p = w[1];
let (nlo, nhi) = ([lo[0].min(p[0]), lo[1].min(p[1])], [hi[0].max(p[0]), hi[1].max(p[1])]);
if (nhi[0] - nlo[0]).min(nhi[1] - nlo[1]) > thin {
out.push([lo[0] - slop, lo[1] - slop, hi[0] - lo[0] + 2.0 * slop, hi[1] - lo[1] + 2.0 * slop]);
(lo, hi) = ([w[0][0].min(p[0]), w[0][1].min(p[1])], [w[0][0].max(p[0]), w[0][1].max(p[1])]);
} else {
(lo, hi) = (nlo, nhi);
}
}
out.push([lo[0] - slop, lo[1] - slop, hi[0] - lo[0] + 2.0 * slop, hi[1] - lo[1] + 2.0 * slop]);
if out.len() <= EDGE_HITS || thin > 4096.0 {
return out;
}
thin *= 2.0;
}
}
/// `hits` with every part over one of `nodes` cut away, keeping the biggest side left of each cut
/// and dropping what gets too small to aim at.
pub(crate) fn cut_away(hits: Vec<[f32; 4]>, nodes: &[[f32; 4]]) -> Vec<[f32; 4]> {
hits.into_iter()
.filter_map(|r| {
nodes.iter().try_fold(r, |r, n| {
let (x0, y0, x1, y1) = (r[0], r[1], r[0] + r[2], r[1] + r[3]);
let (nx0, ny0, nx1, ny1) = (n[0], n[1], n[0] + n[2], n[1] + n[3]);
if nx0 >= x1 || nx1 <= x0 || ny0 >= y1 || ny1 <= y0 {
return Some(r);
}
let sides = [[x0, y0, nx0 - x0, r[3]], [nx1, y0, x1 - nx1, r[3]], [x0, y0, r[2], ny0 - y0], [x0, ny1, r[2], y1 - ny1]];
sides.into_iter().filter(|s| s[2] >= 4.0 && s[3] >= 4.0).max_by(|a, b| (a[2] * a[3]).total_cmp(&(b[2] * b[3])))
})
})
.collect()
}
#[cfg(test)]
#[path = "hover_tests.rs"]
mod tests;
@@ -0,0 +1,186 @@
use rune::{Color, Cx, El, Env, Runtime, col};
use super::*;
use crate::canvas::Scene;
use crate::{DiagramStyle, scene};
const LIT: Color = Color { r: 0.9, g: 0.2, b: 0.5, a: 1.0 };
fn lit_scene(src: &str) -> Scene {
scene(src, &DiagramStyle::neutral(false), Some((Hover::Edges, LIT))).expect("draws")
}
/// The index of the label reading `text`.
fn label(s: &Scene, text: &str) -> usize {
s.labels.iter().position(|l| l.text == text).unwrap_or_else(|| panic!("no label {text:?}"))
}
fn spots<'a>(s: &'a Scene, prefix: &'a str) -> impl Iterator<Item = &'a Spot> + 'a {
s.hovers.iter().filter(move |h| h.key.starts_with(prefix))
}
fn inside(r: [f32; 4], p: [f32; 2]) -> bool {
p[0] >= r[0] && p[0] <= r[0] + r[2] && p[1] >= r[1] && p[1] <= r[1] + r[3]
}
fn centre(s: &Scene, i: usize) -> [f32; 2] {
let l = &s.labels[i];
[l.at[0] + l.size[0] / 2.0, l.at[1] + l.size[1] / 2.0]
}
#[test]
fn a_node_lights_its_edges_labels() {
let s = lit_scene("flowchart TD\n A -->|go| B");
let go = label(&s, "go");
for node in ["hover:n:A", "hover:n:B"] {
let spot = spots(&s, node).next().unwrap_or_else(|| panic!("{node} has a hover group"));
assert_eq!(spot.labels, [go], "{node} lights the label of the edge it lights");
}
let st = lit_scene("stateDiagram-v2\n Idle --> Busy : start");
let start = label(&st, "start");
assert!(spots(&st, "hover:n:").all(|h| h.labels == [start]));
}
#[test]
fn an_edge_lights_itself_and_its_label_and_nodes_win() {
let s = lit_scene("stateDiagram-v2\n Idle --> Busy : start\n Busy --> Done");
let start = label(&s, "start");
let first: Vec<&Spot> = spots(&s, "hover:e:Idle>Busy.").collect();
assert!(first.len() >= 2, "the line and the label are both hover targets: {}", first.len());
assert!(first.iter().all(|h| h.labels == [start]), "hovering the edge lights its label");
let nodes: Vec<[f32; 4]> = spots(&s, "hover:n:").map(|h| h.rect).collect();
let overlap = |a: [f32; 4], b: [f32; 4]| a[0] < b[0] + b[2] && b[0] < a[0] + a[2] && a[1] < b[1] + b[3] && b[1] < a[1] + a[3];
for h in spots(&s, "hover:e:") {
assert!(h.rect[2] >= 4.0 && h.rect[3] >= 4.0, "{} is big enough to aim at: {:?}", h.key, h.rect);
assert!(!nodes.iter().any(|&n| overlap(n, h.rect)), "{} stays off every node so the node wins: {:?}", h.key, h.rect);
assert!(h.rect.iter().all(|v| v.is_finite()));
}
let thin = first.iter().map(|h| h.rect[2].min(h.rect[3])).fold(f32::MAX, f32::min);
assert!(thin >= 2.0 * EDGE_SLOP - 0.5, "the line's slop reaches both sides: {thin}");
let second: Vec<&Spot> = spots(&s, "hover:e:Busy>Done.").collect();
assert!(!second.is_empty() && second.iter().all(|h| h.labels.is_empty()), "an edge without a label lights no label");
}
#[test]
fn a_label_lights_itself_and_its_edge() {
let s = lit_scene("flowchart LR\n A -->|go on| B\n B --> C");
let go = label(&s, "go on");
let over: Vec<&Spot> = s.hovers.iter().filter(|h| inside(h.rect, centre(&s, go))).collect();
assert!(!over.is_empty(), "the label is a hover target");
assert!(over.iter().all(|h| h.key.starts_with("hover:e:A>B.") && h.labels == [go]), "it lights the label and its own edge only");
}
#[test]
fn an_unlit_edges_label_stays_unlit() {
let s = lit_scene("flowchart TD\n A -->|go| B\n C -->|stay| D");
let (go, stay) = (label(&s, "go"), label(&s, "stay"));
for h in spots(&s, "hover:n:A").chain(spots(&s, "hover:n:B")).chain(spots(&s, "hover:e:A>B.")) {
assert_eq!(h.labels, [go], "{} lights only its own edge's label", h.key);
assert!(!h.labels.contains(&stay));
}
assert!(!s.hovers.iter().any(|h| h.labels.contains(&go) && h.labels.contains(&stay)));
}
#[test]
fn off_draws_no_hover_groups() {
let s = scene("flowchart TD\n A -->|go| B", &DiagramStyle::neutral(false), None).unwrap();
assert!(s.hovers.is_empty());
}
#[test]
fn line_hits_cover_a_bend_and_stay_bounded() {
let hits = line_hits(&[[0.0, 0.0], [0.0, 100.0], [100.0, 100.0]], EDGE_SLOP);
assert_eq!(hits.len(), 2, "two straight runs, one rectangle each: {hits:?}");
let wiggle: Vec<[f32; 2]> = (0..400).map(|i| [i as f32 * 3.0, if i % 2 == 0 { 0.0 } else { 30.0 }]).collect();
assert!(line_hits(&wiggle, EDGE_SLOP).len() <= 16);
assert_eq!(cut_away(vec![[0.0, 0.0, 16.0, 100.0]], &[[-10.0, 80.0, 40.0, 40.0]]), [[0.0, 0.0, 16.0, 80.0]]);
assert!(cut_away(vec![[0.0, 0.0, 16.0, 16.0]], &[[-10.0, -10.0, 40.0, 40.0]]).is_empty());
}
#[test]
fn hovering_an_edge_lights_it_instantly_and_leaving_drops_it() {
fn view(_: &u32, _: &mut Cx<u32>) -> El {
let paint = DiagramStyle::neutral(false);
let s = scene("stateDiagram-v2\n Idle --> Busy : start", &paint, Some((Hover::Edges, LIT))).unwrap();
col().w_full().child(s.el(&paint, false))
}
let mut rt = Runtime::new(0u32, view, (400.0, 400.0), Env::new(false, 1.0));
rt.frame(0.0);
let find = |rt: &Runtime<u32>, key: &str| rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap_or_else(|| panic!("no {key}"));
let label_spot = find(&rt, "hover:e:Idle>Busy.t");
let key = label_spot.key.clone().unwrap();
let r = label_spot.rect;
rt.pointer_move(r[0] + r[2] / 2.0, r[1] + r[3] / 2.0);
rt.frame(1.0 / 60.0);
assert_eq!(find(&rt, &key).hover, 1.0, "on in the first frame, like a node");
assert_eq!(find(&rt, "hover:n:Idle").hover, 0.0);
rt.pointer_move(1.0, 399.0);
for _ in 0..12 {
rt.frame(1.0 / 60.0);
}
assert_eq!(find(&rt, &key).hover, 0.0, "and off as the pointer leaves");
}
#[test]
fn hover_groups_are_keyed_by_the_piece_they_light() {
let s = lit_scene("flowchart TD\n A -->|go| B\n B --> C\n");
let pieces: Vec<&str> = s.pieces.iter().map(|p| p.key.as_str()).collect();
for h in &s.hovers {
let piece = h.key.strip_prefix("hover:").unwrap_or_else(|| panic!("{} names no piece", h.key));
let piece = if piece.starts_with("e:") { piece.rsplit_once('.').map_or(piece, |p| p.0) } else { piece };
assert!(pieces.contains(&piece), "{} lights {piece}, a piece the diagram draws: {pieces:?}", h.key);
if piece.starts_with("e:") && !h.labels.is_empty() {
assert_eq!(s.label_keys[h.labels[0]].0, format!("{piece}.t0"), "{} lights its own edge's label", h.key);
}
}
assert!(s.hovers.iter().any(|h| h.key == "hover:e:A>B.t"), "the label's group is its own, apart from the line's");
}
#[test]
fn a_still_pointer_keeps_what_it_hovers_or_lets_go_as_a_streaming_diagram_moves() {
fn view(s: &String, _: &mut Cx<String>) -> El {
let paint = DiagramStyle::neutral(false);
col().w_full().children(crate::render_streaming(s, &paint, Hover::Edges, LIT))
}
// What each hovered group lights, by the labels it shows lit.
fn lit(rt: &Runtime<String>) -> Vec<Vec<String>> {
let all = rt.elements();
all.iter()
.filter(|g| g.hover > 0.0 && g.key.is_some())
.map(|g| {
let inside = format!("{}/", g.path);
let mut t: Vec<String> = all.iter().filter(|e| e.path.starts_with(&inside)).filter_map(|e| e.text.clone()).collect();
t.sort();
t
})
.collect()
}
let src = "graph TD\n X -->|in| S\n S --> W\n W -->|out| Y\n";
// The subgraph turns the placeholder node `S` into a frame around `D`: every node after it
// shifts down an index, and the frame pushes `W` and `Y` down.
let grown = format!("{src} subgraph S\n D\n end\n");
let rect = |rt: &Runtime<String>, key: &str| rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key) && !e.exiting).map(|e| e.rect);
// Over the label of an edge that stays, and over the node that goes.
for (over, before) in [("hover:e:W>Y.t", vec!["out".to_owned()]), ("hover:n:S", vec!["in".to_owned()])] {
let mut rt = Runtime::new(src.to_owned(), view, (600.0, 600.0), Env::new(false, 1.0));
rt.frame(0.0);
let at = rect(&rt, over).unwrap_or_else(|| panic!("no {over}"));
let y = rect(&rt, "n:Y").expect("Y");
rt.pointer_move(at[0] + at[2] / 2.0, at[1] + at[3] / 2.0);
rt.frame(1.0 / 60.0);
let now = lit(&rt);
assert!(!now.is_empty() && now.iter().all(|l| *l == before), "{over} lights {before:?}: {now:?}");
rt.update(|s, _| *s = grown.clone());
for _ in 0..240 {
rt.frame(1.0 / 60.0);
if !rt.elements().iter().any(|e| e.moving) {
break;
}
for l in lit(&rt) {
assert_eq!(l, before, "{over}: a still pointer keeps lighting what it was over, or lets go");
}
}
let y2 = rect(&rt, "n:Y").expect("Y");
assert!((y2[1] - y[1]).abs() > 8.0, "{over}: the diagram moved under the pointer: {y:?} → {y2:?}");
}
}
+147
View File
@@ -0,0 +1,147 @@
//! Lines, outlines and arrowheads made opaque before they are drawn.
//!
//! Rune draws a stroke as one capsule per segment, so a translucent stroke blends twice at every
//! joint: a curve gets beads, a rounded corner gets brighter than the edges beside it, and a line
//! gets brighter where it runs under its own arrowhead or meets a node's outline. Each
//! translucent ink colour is replaced with what it would show over the fills beneath it (the
//! card's surface, a subgraph's tint, a node's fill), so overlaps and joints paint the same
//! colour twice and look like one stroke. Area fills (tints, bands, slices) keep their alpha.
//!
//! The blend is in sRGB-encoded values, as apps blend by default (`App::srgb_blend`).
use rune::Color;
use super::Op;
use super::hover::Trace;
/// `ops` with their ink made opaque over `surface`: every stroke, and every fill in a stroke's
/// colour (arrowheads and other filled heads). The hover `traces` draw over `ops`; their ink is
/// flattened over the same fills.
pub(crate) fn flatten(ops: &mut [Op], traces: &mut [Trace], surface: Color) {
let mut inks: Vec<Color> = Vec::new();
for op in ops.iter().chain(traces.iter().flat_map(|t| &t.ops)) {
if let Op::Stroke { color, .. } = op
&& translucent(*color)
&& !inks.contains(color)
{
inks.push(*color);
}
}
if inks.is_empty() {
return;
}
let areas: Vec<Area> = ops
.iter()
.enumerate()
.filter_map(|(i, op)| match op {
Op::Fill(points, color) if !inks.contains(color) => Some(Area { at: i, bounds: bounds(points), points: points.clone(), color: *color }),
_ => None,
})
.collect();
let backdrop = Backdrop { areas, surface };
let n = ops.len();
for (i, op) in ops.iter_mut().enumerate() {
backdrop.flatten(op, i, &inks);
}
for op in traces.iter_mut().flat_map(|t| &mut t.ops) {
backdrop.flatten(op, n, &inks);
}
}
struct Area {
at: usize,
bounds: [f32; 4],
points: Vec<[f32; 2]>,
color: Color,
}
struct Backdrop {
areas: Vec<Area>,
surface: Color,
}
impl Backdrop {
fn flatten(&self, op: &mut Op, at: usize, inks: &[Color]) {
match op {
Op::Stroke { points, closed, color, .. } if translucent(*color) => {
let (p, own) = if *closed { (centroid(points), Some(&points[..])) } else { (midpoint(points), None) };
*color = over(*color, self.under(p, at, own));
}
Op::Fill(points, color) if inks.contains(color) => *color = over(*color, self.under(centroid(points), at, None)),
_ => {}
}
}
/// The colour at `p` from the fills drawn before op `at`, over the surface; `own` is the
/// outline being drawn, whose own fill doesn't count.
fn under(&self, p: [f32; 2], at: usize, own: Option<&[[f32; 2]]>) -> Color {
self.areas
.iter()
.take_while(|a| a.at < at)
.filter(|a| own != Some(&a.points[..]) && inside(p, a.bounds, &a.points))
.fold(self.surface, |under, a| over(a.color, under))
}
}
/// Ink that shows what's under it; clear ink stays clear.
fn translucent(c: Color) -> bool {
c.a > 0.0 && c.a < 1.0
}
/// `top` over `bottom`, blended in sRGB-encoded values.
pub(crate) fn over(top: Color, bottom: Color) -> Color {
let a = top.a + bottom.a * (1.0 - top.a);
if a <= 1e-6 {
return Color::TRANSPARENT;
}
let m = |t: f32, b: f32| dec((enc(t) * top.a + enc(b) * bottom.a * (1.0 - top.a)) / a);
Color { r: m(top.r, bottom.r), g: m(top.g, bottom.g), b: m(top.b, bottom.b), a }
}
fn enc(c: f32) -> f32 {
rune::color::srgb_encode(c.clamp(0.0, 1.0))
}
fn dec(c: f32) -> f32 {
rune::color::srgb_decode(c.clamp(0.0, 1.0))
}
fn bounds(points: &[[f32; 2]]) -> [f32; 4] {
points.iter().fold([f32::MAX, f32::MAX, f32::MIN, f32::MIN], |b, p| [b[0].min(p[0]), b[1].min(p[1]), b[2].max(p[0]), b[3].max(p[1])])
}
fn centroid(points: &[[f32; 2]]) -> [f32; 2] {
let n = points.len().max(1) as f32;
let s = points.iter().fold([0.0, 0.0], |s, p| [s[0] + p[0], s[1] + p[1]]);
[s[0] / n, s[1] / n]
}
fn midpoint(points: &[[f32; 2]]) -> [f32; 2] {
let i = points.len() / 2;
match points.len() {
0 => [0.0, 0.0],
n if n % 2 == 0 => crate::canvas::lerp(points[i - 1], points[i], 0.5),
_ => points[i],
}
}
/// Whether `p` is inside the polygon `points` (even-odd).
fn inside(p: [f32; 2], b: [f32; 4], points: &[[f32; 2]]) -> bool {
if p[0] < b[0] || p[0] > b[2] || p[1] < b[1] || p[1] > b[3] {
return false;
}
let mut odd = false;
let mut j = points.len() - 1;
for i in 0..points.len() {
let (a, c) = (points[i], points[j]);
if (a[1] > p[1]) != (c[1] > p[1]) && p[0] < (c[0] - a[0]) * (p[1] - a[1]) / (c[1] - a[1]) + a[0] {
odd = !odd;
}
j = i;
}
odd
}
#[cfg(test)]
#[path = "ink_tests.rs"]
mod tests;
@@ -0,0 +1,154 @@
use rune::{Color, LineCap};
use super::{flatten, over};
use crate::canvas::{Canvas, Op, dist, lerp};
use crate::{DiagramStyle, Hover, scene};
/// The colour Rune paints at `p` for `ops` over `surface`: every stroke segment is its own
/// capsule (or box, with butt caps) and blends on its own, as the renderer draws them.
fn painted(ops: &[Op], surface: Color, p: [f32; 2]) -> Color {
ops.iter().fold(surface, |under, op| match op {
Op::Fill(points, color) => (0..inside_count(points, p)).fold(under, |u, _| over(*color, u)),
Op::Stroke { points, closed, width, cap, color } => {
let mut segs: Vec<([f32; 2], [f32; 2])> = points.windows(2).map(|w| (w[0], w[1])).collect();
if *closed && points.len() > 2 {
segs.push((points[points.len() - 1], points[0]));
}
segs.iter().filter(|(a, b)| covers(*a, *b, *width, *cap, p)).fold(under, |u, _| over(*color, u))
}
})
}
fn inside_count(points: &[[f32; 2]], p: [f32; 2]) -> usize {
let mut odd = false;
let mut j = points.len() - 1;
for i in 0..points.len() {
let (a, c) = (points[i], points[j]);
if (a[1] > p[1]) != (c[1] > p[1]) && p[0] < (c[0] - a[0]) * (p[1] - a[1]) / (c[1] - a[1]) + a[0] {
odd = !odd;
}
j = i;
}
odd as usize
}
fn covers(a: [f32; 2], b: [f32; 2], width: f32, cap: LineCap, p: [f32; 2]) -> bool {
let len = dist(a, b).max(1e-6);
let d = [(b[0] - a[0]) / len, (b[1] - a[1]) / len];
let t = (p[0] - a[0]) * d[0] + (p[1] - a[1]) * d[1];
let n = ((p[0] - a[0]) * -d[1] + (p[1] - a[1]) * d[0]).abs();
match cap {
LineCap::Butt => (0.0..=len).contains(&t) && n <= width / 2.0,
LineCap::Round => dist(p, lerp(a, b, (t / len).clamp(0.0, 1.0))) <= width / 2.0,
}
}
fn brighter(a: Color, b: Color) -> f32 {
a.luminance() - b.luminance()
}
const FLOW: &str = "flowchart LR\n R1[Retry at once] -->|fails| R2[Back off 1 s]\n R2 -->|fails| Off[Offline]\n R1 -->|ok| On[Online]";
#[test]
fn a_line_is_no_brighter_at_its_joints_under_its_head_or_round_a_corner() {
let paint = DiagramStyle::neutral(true);
let ops = scene(FLOW, &paint, None).expect("draws").ops;
let at = |p| painted(&ops, paint.surface, p);
let mut checked = 0;
for op in &ops {
let Op::Stroke { points, closed, .. } = op else { continue };
let longest = points.windows(2).max_by(|a, b| dist(a[0], a[1]).total_cmp(&dist(b[0], b[1]))).expect("a segment");
let body = at(lerp(longest[0], longest[1], 0.5));
// Every joint, and an open line's ends, where it runs under its arrowhead.
for &p in points.iter().skip(if *closed { 0 } else { 1 }) {
let lift = brighter(at(p), body);
assert!(lift < 0.002, "brighter by {lift} at {p:?} than along the stroke ({:?} vs {:?})", at(p), body);
checked += 1;
}
}
assert!(checked > 40, "edges and rounded node corners were checked: {checked}");
}
#[test]
fn every_diagram_draws_its_ink_opaque_over_an_opaque_surface() {
let sources = [
FLOW,
"flowchart TD\n subgraph S [Box]\n A --> B\n end\n B -.-> C\n C ==> A",
"sequenceDiagram\n participant A\n participant B\n A->>B: hi\n B-->>A: back\n A-)B: async\n Note over A,B: note",
"stateDiagram-v2\n [*] --> Idle\n Idle --> Busy : go\n Busy --> [*]",
"classDiagram\n Animal <|-- Duck\n Animal *-- Leg\n Animal o-- Tail\n class Animal {\n +int age\n +eat()\n }",
"erDiagram\n CUSTOMER ||--o{ ORDER : places\n ORDER ||--|{ LINE : contains",
"journey\n title Day\n section Work\n Code: 5: Me\n Meet: 2: Me, You",
"timeline\n 2024 : one\n 2025 : two : three",
"gitGraph\n commit\n branch dev\n commit\n checkout main\n merge dev",
];
for dark in [true, false] {
let paint = DiagramStyle::neutral(dark);
assert_eq!(paint.surface.a, 1.0);
for src in sources {
let ops = scene(src, &paint, None).unwrap_or_else(|| panic!("draws {src:?}")).ops;
for op in &ops {
match op {
Op::Stroke { color, .. } => assert_eq!(color.a, 1.0, "a translucent stroke in {src:?}"),
Op::Fill(points, color) if points.len() == 3 => assert_eq!(color.a, 1.0, "a translucent arrowhead in {src:?}"),
_ => {}
}
}
}
}
}
#[test]
fn ink_takes_the_colour_of_the_fills_beneath_it() {
let surface = Color { r: 0.02, g: 0.02, b: 0.02, a: 1.0 };
let tint = Color::WHITE.alpha(0.1);
let ink = Color::WHITE.alpha(0.5);
let mut c = Canvas::default();
c.fill(vec![[0.0, 0.0], [100.0, 0.0], [100.0, 100.0], [0.0, 100.0]], tint);
c.stroke(vec![[10.0, 50.0], [90.0, 50.0]], false, 1.0, ink);
c.stroke(vec![[110.0, 50.0], [190.0, 50.0]], false, 1.0, ink);
c.fill(vec![[150.0, 40.0], [160.0, 50.0], [150.0, 60.0]], ink);
flatten(&mut c.ops, &mut [], surface);
let colors: Vec<Color> = c.ops.iter().map(|op| match op {
Op::Fill(_, c) | Op::Stroke { color: c, .. } => *c,
}).collect();
assert_eq!(colors[0], tint, "an area keeps its alpha");
assert_eq!(colors[1], over(ink, over(tint, surface)), "ink inside the tint");
assert_eq!(colors[2], over(ink, surface), "ink on the surface");
assert_eq!(colors[3], colors[2], "a head in the line's colour matches its line");
}
#[test]
fn hover_traces_light_in_opaque_ink_too() {
let paint = DiagramStyle::neutral(true);
let Some(crate::Parsed { diagram: crate::Diagram::Flowchart(f), .. }) = crate::parse(FLOW) else { panic!() };
let mut c = crate::graph::flowchart::draw_canvas(&f, &paint, Some((Hover::Edges, paint.text.alpha(0.9)))).expect("draws");
flatten(&mut c.ops, &mut c.traces, paint.surface);
let strokes = c.traces.iter().flat_map(|t| &t.ops).filter_map(|op| match op {
Op::Stroke { color, .. } => Some(color.a),
_ => None,
});
assert!(strokes.clone().count() >= 3);
assert!(strokes.into_iter().all(|a| a == 1.0));
}
#[test]
fn srgb_enc_dec_match_clamped_reference_bit_for_bit() {
let ref_enc = |c: f32| {
let c = c.clamp(0.0, 1.0);
if c <= 0.003_130_8 { c * 12.92 } else { 1.055 * c.powf(1.0 / 2.4) - 0.055 }
};
let ref_dec = |c: f32| {
let c = c.clamp(0.0, 1.0);
if c <= 0.040_45 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) }
};
for v in 0..=255u8 {
let x = v as f32 / 255.0;
assert_eq!(super::enc(x).to_bits(), ref_enc(x).to_bits(), "enc byte {v}");
assert_eq!(super::dec(x).to_bits(), ref_dec(x).to_bits(), "dec byte {v}");
}
for x in [-1.0, -0.01, -0.0, 0.0, 0.003_130_8, 0.040_45, 0.5, 1.0, 1.5] {
assert_eq!(super::enc(x).to_bits(), ref_enc(x).to_bits(), "enc {x}");
assert_eq!(super::dec(x).to_bits(), ref_dec(x).to_bits(), "dec {x}");
}
}
+526
View File
@@ -0,0 +1,526 @@
//! Vector canvas, text measurement, geometry primitives and scene assembly for [`crate::render`].
pub(crate) mod drawing;
pub(crate) mod hover;
mod ink;
pub(crate) mod parts;
pub(crate) mod scenes;
pub(crate) mod shape;
use rune::{Align, Color, El, LineCap, Shape, TextHighlight, TextStyle, Transition, canvas, col, el, text};
use crate::DiagramStyle;
use hover::{Hover, Spot, Trace};
use parts::{LabelKey, Mark, Names, Piece, pieces};
/// The card's padding on each side.
const CARD_PAD: f32 = 16.0;
type Marks<'a> = Option<&'a dyn Fn(&str) -> Vec<TextHighlight>>;
fn marked(el: El, key: &str, marks: Marks<'_>) -> El {
if let Some(paint) = marks { el.text_highlights(paint(key)) } else { el }
}
/// The widest a diagram's drawing can be for its card to fit `paint.max_width`.
pub(crate) fn room(paint: &DiagramStyle) -> f32 {
paint.max_width - 2.0 * CARD_PAD - 2.0
}
/// How much a canvas `width` points wide is drawn at to fit its card in `paint.max_width`, down
/// to `paint.min_scale`.
fn fit(width: f32, paint: &DiagramStyle) -> f32 {
if width <= room(paint) { 1.0 } else { (room(paint) / width).max(paint.min_scale.clamp(0.0, 1.0)) }
}
/// Text measured for a diagram: its size, and whether it wraps at [`WRAP`].
#[derive(Clone, Default)]
pub(crate) struct Measured {
pub text: String,
pub size: [f32; 2],
pub wrap: bool,
}
/// Labels wider than this wrap.
const WRAP: f32 = 200.0;
pub(crate) fn measure(s: &str, font: TextStyle) -> Measured {
measure_wrap(s, font, WRAP)
}
pub(crate) fn measure_wrap(s: &str, font: TextStyle, max_w: f32) -> Measured {
if s.is_empty() {
return Measured::default();
}
let (w, h) = rune::text::measure(s, &[], font, None);
if w <= max_w {
return Measured { text: s.to_owned(), size: [w, h], wrap: false };
}
let (w, h) = rune::text::measure(s, &[], font, Some(max_w));
Measured { text: s.to_owned(), size: [w, h], wrap: true }
}
/// [`measure`], wrapped to the narrowest width that takes as few lines, so the lines come out
/// even and none is a lone word.
pub(crate) fn measure_balanced(s: &str, font: TextStyle) -> Measured {
let mut m = measure(s, font);
if !m.wrap {
return m;
}
let (mut lo, mut hi) = (0.0, m.size[0]);
while hi - lo > 1.0 {
let mid = (lo + hi) / 2.0;
let (w, h) = rune::text::measure(s, &[], font, Some(mid));
if h > m.size[1] + 0.5 {
lo = mid;
} else {
(hi, m.size[0]) = (mid, w);
}
}
m
}
/// Straight-alpha `top` composited over `bottom` in linear sRGB.
pub(crate) fn over_color(top: Color, bottom: Color) -> Color {
let a = top.a + bottom.a * (1.0 - top.a);
if a <= 1e-6 {
return Color::TRANSPARENT;
}
let m = |t: f32, b: f32| (t * top.a + b * bottom.a * (1.0 - top.a)) / a;
Color { r: m(top.r, bottom.r), g: m(top.g, bottom.g), b: m(top.b, bottom.b), a }
}
/// The outline of a group (a subgraph, a block group, a participant box): the nodes' outline,
/// quieter, so a group reads as a region behind its nodes rather than another node.
pub(crate) fn group_border(paint: &crate::DiagramStyle) -> Color {
paint.node_border.alpha(paint.node_border.a * 0.7)
}
#[derive(Clone)]
pub(crate) enum Op {
Fill(Vec<[f32; 2]>, Color),
Stroke { points: Vec<[f32; 2]>, closed: bool, width: f32, cap: LineCap, color: Color },
}
pub(crate) struct Label {
pub text: String,
pub at: [f32; 2],
pub size: [f32; 2],
pub font: TextStyle,
pub color: Color,
pub wrap: bool,
pub align: Align,
}
/// Drawing in a diagram's own points; [`Canvas::finish`] moves it to the origin and scales it.
#[derive(Default)]
pub(crate) struct Canvas {
pub(crate) ops: Vec<Op>,
pub(crate) labels: Vec<Label>,
/// Per node: its outline, where hovering it lights up its traces (empty when not drawn).
pub(crate) regions: Vec<Vec<[f32; 2]>>,
/// Per edge: its ends and its drawing in the hover colour.
pub(crate) traces: Vec<Trace>,
pub(crate) hover: Option<(Hover, Color)>,
/// Where each node, edge and frame's drawing starts ([`Canvas::part`]), and their names.
pub(crate) marks: Vec<Mark>,
pub(crate) names: Names,
/// A horizontal diagram turned vertical to fit: its edges are keyed apart from the
/// horizontal ones'.
pub(crate) turned: bool,
}
impl Canvas {
pub(crate) fn fill(&mut self, points: Vec<[f32; 2]>, color: Color) {
if points.len() >= 3 {
self.ops.push(Op::Fill(points, color));
}
}
pub(crate) fn stroke(&mut self, points: Vec<[f32; 2]>, closed: bool, width: f32, color: Color) {
if points.len() >= 2 {
self.ops.push(Op::Stroke { points, closed, width, cap: LineCap::Round, color });
}
}
/// A filled outline.
pub(crate) fn shape(&mut self, points: Vec<[f32; 2]>, fill: Color, border: Color, width: f32) {
self.fill(points.clone(), fill);
self.stroke(points, true, width, border);
}
pub(crate) fn dashed(&mut self, points: &[[f32; 2]], width: f32, color: Color, on: f32, off: f32) {
let mut dash: Vec<[f32; 2]> = Vec::new();
let mut drawing = true;
let mut left = on;
// Bounded so a huge or non-finite length (where `t += step` stops advancing) can't spin.
let mut budget = 20_000usize;
for w in points.windows(2) {
let (a, b) = (w[0], w[1]);
let len = dist(a, b);
if !len.is_finite() {
continue;
}
let mut t = 0.0;
while t < len {
let Some(rest) = budget.checked_sub(1) else { return };
budget = rest;
let step = left.min(len - t);
let p0 = lerp(a, b, t / len);
let p1 = lerp(a, b, (t + step) / len);
if drawing {
if dash.is_empty() {
dash.push(p0);
}
dash.push(p1);
}
t += step;
left -= step;
if left <= 1e-3 {
if drawing && dash.len() >= 2 {
self.ops.push(Op::Stroke { points: std::mem::take(&mut dash), closed: false, width, cap: LineCap::Butt, color });
}
dash.clear();
drawing = !drawing;
left = if drawing { on } else { off };
}
}
}
if dash.len() >= 2 {
self.ops.push(Op::Stroke { points: dash, closed: false, width, cap: LineCap::Butt, color });
}
}
/// `m` centred on `center`.
pub(crate) fn label(&mut self, m: &Measured, center: [f32; 2], font: TextStyle, color: Color, align: Align) {
if m.text.is_empty() {
return;
}
let at = [center[0] - m.size[0] / 2.0, center[1] - m.size[1] / 2.0];
self.label_at(m, at, font, color, align);
}
pub(crate) fn label_at(&mut self, m: &Measured, at: [f32; 2], font: TextStyle, color: Color, align: Align) {
if !m.text.is_empty() {
self.labels.push(Label { text: m.text.clone(), at, size: m.size, font, color, wrap: m.wrap, align });
}
}
/// Draws `other` over this.
pub(crate) fn append(&mut self, other: Canvas) {
let (base, shift) = (self.ops.len(), self.labels.len());
self.marks.push((base, shift, None));
self.marks.extend(other.marks.into_iter().map(|(o, l, p)| (o + base, l + shift, p)));
self.ops.extend(other.ops);
self.labels.extend(other.labels);
self.traces.extend(other.traces.into_iter().map(|t| Trace { label: t.label.map(|(i, g)| (i + shift, g)), ..t }));
}
/// The bounding box of everything drawn: `[x0, y0, x1, y1]`.
fn bounds(&self) -> [f32; 4] {
let mut b = [f32::MAX, f32::MAX, f32::MIN, f32::MIN];
let mut add = |p: [f32; 2], r: f32| {
b = [b[0].min(p[0] - r), b[1].min(p[1] - r), b[2].max(p[0] + r), b[3].max(p[1] + r)];
};
for op in &self.ops {
match op {
Op::Fill(points, _) => points.iter().for_each(|&p| add(p, 0.0)),
Op::Stroke { points, width, .. } => points.iter().for_each(|&p| add(p, width / 2.0)),
}
}
for l in &self.labels {
add(l.at, 0.0);
add([l.at[0] + l.size[0], l.at[1] + l.size[1]], 0.0);
}
if b[0] > b[2] { [0.0; 4] } else { b }
}
pub(crate) fn width(&self) -> f32 {
let b = self.bounds();
b[2] - b[0]
}
/// What [`Self::finish`] draws: the bounds, from no further in than a streaming build's
/// last corner ([`crate::layout::steady::origin`]).
fn drawn(&self) -> [f32; 4] {
let b = self.bounds();
let [left, top] = crate::layout::steady::origin(b, self.turned);
[left, top, b[2], b[3]]
}
pub(crate) fn finish_fit(self, paint: &DiagramStyle) -> Option<Scene> {
let b = self.drawn();
let scale = fit(b[2] - b[0], paint);
self.finish(scale, paint)
}
pub(crate) fn finish(mut self, scale: f32, paint: &DiagramStyle) -> Option<Scene> {
if self.ops.is_empty() && self.labels.is_empty() {
return None;
}
ink::flatten(&mut self.ops, &mut self.traces, paint.surface);
let b = self.drawn();
// Store full-size drawing; Scene::el fits each destination before animating it.
// Labels scale without changing font metrics. Lines scale with everything else, as an
// SVG's do: a floor here would be baked into the full-size drawing, so a diagram shrunk
// far to fit would draw fat lines once something magnifies it again.
let pad = 1.0 / scale;
let map = |p: [f32; 2]| [p[0] - b[0] + pad, p[1] - b[1] + pad];
let paint = |shape: Shape, op: &Op| match op {
Op::Fill(points, color) => shape.fill(points.iter().map(|&p| map(p)).collect::<Vec<_>>(), *color),
Op::Stroke { points, closed, width, cap, color } => {
shape.stroke_with(points.iter().map(|&p| map(p)).collect::<Vec<_>>(), *closed, *width, *cap, *color)
}
};
let (pieces, label_keys) = pieces(&self, map);
let hovers = self.hovers(map, paint);
let labels = self.labels.into_iter().map(|l| Label { at: map(l.at), ..l }).collect();
let full = [b[2] - b[0] + 2.0 * pad, b[3] - b[1] + 2.0 * pad];
let size = [full[0] * scale, full[1] * scale];
let lit = self.hover.map_or(Color::TRANSPARENT, |h| h.1);
Some(Scene {
title: None,
size,
full,
scale,
pieces,
labels,
label_keys,
hovers,
lit,
#[cfg(test)]
ops: self.ops,
})
}
}
/// A laid-out diagram, drawn the same way every build.
pub(crate) struct Scene {
pub(crate) title: Option<String>,
/// The size it's drawn at: [`Self::full`] times [`Self::scale`].
pub(crate) size: [f32; 2],
/// The size its pieces, labels and hovers are laid out in, before it shrinks to fit.
pub(crate) full: [f32; 2],
/// How much it shrinks to fit the room it has.
pub(crate) scale: f32,
/// Each node, edge and frame's drawing, and the rest, in drawing order.
pub(crate) pieces: Vec<Piece>,
pub(crate) labels: Vec<Label>,
pub(crate) label_keys: Vec<LabelKey>,
/// The hover groups over edges, edge labels and nodes, and what each lights up.
pub(crate) hovers: Vec<Spot>,
/// The hover colour.
lit: Color,
/// What the pieces draw, in the diagram's own points.
#[cfg(test)]
pub(crate) ops: Vec<Op>,
}
impl Scene {
pub(crate) fn with_title(mut self, title: Option<String>) -> Self {
if let Some(t) = title.filter(|t| !t.trim().is_empty()) {
self.title = Some(t);
}
self
}
/// The diagram card. `streaming`: its source is still arriving, so each node, edge and frame
/// new since the last build comes in on its own ([`parts::Kind::enter`]); otherwise
/// everything shows the frame it mounts.
pub(crate) fn el(&self, paint: &DiagramStyle, streaming: bool) -> El {
let still = |t: Transition| if streaming { t } else { Transition::none() };
let mut card = col()
.w_full()
.items_center()
.padding(CARD_PAD)
.radius(6.0)
.fill(paint.surface)
.border(0.5, paint.surface_border)
.clip_rounded(6.0)
.animate_layout()
.transition(still(Transition::opacity()));
if self.size[0] > room(paint) + 0.5 {
// Shrunk as far as `min_scale` lets it and still too wide: its sides fade out under
// the card's padding rather than stopping at a hard edge.
card = card.clip_fade(CARD_PAD, 0.0, CARD_PAD, 0.0);
}
if let Some(title) = self.title_el(paint, streaming, None) {
card = card.gap(TITLE_GAP).child(title);
}
card.child(self.diagram_el(streaming, None))
}
/// The title and drawing without the card around them, and the size they take.
pub(crate) fn drawing(&self, paint: &DiagramStyle, marks: Marks<'_>) -> (El, [f32; 2]) {
let mut size = self.size;
let mut out = col().items_center();
if let Some(title) = self.title_el(paint, false, marks) {
let t = measure(self.title.as_deref().unwrap_or_default(), title_font(paint)).size;
size = [size[0].max(t[0] + 2.0), size[1] + t[1] + TITLE_GAP];
out = out.gap(TITLE_GAP).child(title);
}
(out.child(self.diagram_el(false, marks)), size)
}
fn title_el(&self, paint: &DiagramStyle, streaming: bool, marks: Marks<'_>) -> Option<El> {
let still = if streaming { Transition::opacity() } else { Transition::none() };
self.title.as_ref().map(|title| marked(text(title.clone()).key("title").font(title_font(paint)).color(paint.text).transition(still), "title", marks))
}
fn diagram_el(&self, streaming: bool, marks: Marks<'_>) -> El {
let [w, h] = self.full;
let still = |t: Transition| if streaming { t } else { Transition::none() };
// Fit destinations before springing them. Multiplying a springing canvas size by a
// second, shrinking scale spring makes edges overshoot and reverse between updates.
let scale = self.scale;
let mut body = el().key("fit").absolute(0.0, 0.0).size(self.size[0], self.size[1]).transition(Transition::none());
for p in &self.pieces {
// Shapes and lines draw what the labels and the figure's description say.
body = body.child(p.el(streaming, scale).a11y_hidden());
}
let label = |l: &Label, color: Color| {
// A point of slack so rounding never breaks a measured line.
let t = text(l.text.clone()).font(l.font).color(color).align(l.align).w(l.size[0] + 2.0);
if l.wrap { t.wrap() } else { t }
};
// Labels and hover groups are placed by offset, as pieces are ([`Piece::el`]).
for (l, (key, kind)) in self.labels.iter().zip(&self.label_keys) {
let (enter, delay) = kind.map_or((Transition::opacity(), 0.0), |k| k.label_enter());
let mut t = marked(label(l, l.color), key, marks).absolute(0.0, 0.0).offset((l.at[0] - 1.0) * scale, l.at[1] * scale).origin(0.0, 0.0).scale(scale).key(key.clone()).transition(still(enter));
if streaming && delay > 0.0 {
t = t.enter_delay(delay);
}
body = body.child(t);
}
// Over the labels, so a lit label's backing covers the one it lights. Unlit until
// hovered, so they never animate in and their drawing moves at once. One a streaming
// rebuild drops fades out, unseen, rather than cutting.
for s in &self.hovers {
let r = s.rect;
let mut glow = el()
.absolute(-r[0] * scale, -r[1] * scale)
.size(w, h)
.origin(0.0, 0.0)
.scale(scale)
.group_opacity(0.0, 1.0)
.instant_changes()
.transition(Transition::none())
.child(canvas(s.lit.clone()).key("lit").absolute(0.0, 0.0).size(w, h).transition(Transition::none()));
for &i in &s.labels {
if let Some(l) = self.labels.get(i) {
let t = marked(label(l, self.lit), &self.label_keys[i].0, marks);
glow = glow.child(t.absolute(l.at[0] - 1.0, l.at[1]).key(format!("t{i}")).transition(Transition::none()));
}
}
let exit = if streaming { Transition { insertion: rune::Effect::IDENTITY, ..Transition::opacity() } } else { Transition::none() };
body = body.child(el().key(s.key.clone()).absolute(0.0, 0.0).offset(r[0] * scale, r[1] * scale).size(r[2] * scale, r[3] * scale).hover_group().transition(exit).child(glow).a11y_hidden());
}
el().key("diagram").size(self.size[0], self.size[1]).transition(still(Transition::opacity())).child(body)
}
}
/// Points between a diagram's title and its drawing.
const TITLE_GAP: f32 = 12.0;
fn title_font(paint: &DiagramStyle) -> TextStyle {
TextStyle { size: paint.font.size + 1.0, line_height: paint.font.line_height + 2.0, weight: 600.0, ..paint.font }
}
pub(crate) fn dist(a: [f32; 2], b: [f32; 2]) -> f32 {
((b[0] - a[0]).powi(2) + (b[1] - a[1]).powi(2)).sqrt()
}
pub(crate) fn lerp(a: [f32; 2], b: [f32; 2], t: f32) -> [f32; 2] {
[a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]
}
pub(crate) fn unit(a: [f32; 2], b: [f32; 2]) -> [f32; 2] {
let d = dist(a, b).max(1e-6);
[(b[0] - a[0]) / d, (b[1] - a[1]) / d]
}
/// A rectangle with corners of radius `r`, as a polygon.
pub(crate) fn rounded_rect(x0: f32, y0: f32, x1: f32, y1: f32, r: f32) -> Vec<[f32; 2]> {
let r = r.min((x1 - x0) / 2.0).min((y1 - y0) / 2.0).max(0.0);
if r < 0.5 {
return vec![[x0, y0], [x1, y0], [x1, y1], [x0, y1]];
}
let steps = 6;
let mut pts = Vec::with_capacity(4 * (steps + 1));
let corners = [([x1 - r, y0 + r], -90.0f32), ([x1 - r, y1 - r], 0.0), ([x0 + r, y1 - r], 90.0), ([x0 + r, y0 + r], 180.0)];
for (c, start) in corners {
for i in 0..=steps {
let a = (start + 90.0 * i as f32 / steps as f32).to_radians();
pts.push([c[0] + r * a.cos(), c[1] + r * a.sin()]);
}
}
pts
}
/// An ellipse's arc from `a0` to `a1` degrees (clockwise on screen), as points.
pub(crate) fn arc(c: [f32; 2], rx: f32, ry: f32, a0: f32, a1: f32, steps: usize) -> Vec<[f32; 2]> {
(0..=steps)
.map(|i| {
let a = (a0 + (a1 - a0) * i as f32 / steps as f32).to_radians();
[c[0] + rx * a.cos(), c[1] + ry * a.sin()]
})
.collect()
}
pub(crate) fn ellipse(c: [f32; 2], rx: f32, ry: f32) -> Vec<[f32; 2]> {
let mut pts = arc(c, rx, ry, 0.0, 360.0, 48);
pts.pop();
pts
}
/// A filled arrowhead with its tip at `tip`, pointing along `dir` (a unit vector).
pub(crate) fn arrowhead(tip: [f32; 2], dir: [f32; 2], len: f32, width: f32) -> Vec<[f32; 2]> {
let base = [tip[0] - dir[0] * len, tip[1] - dir[1] * len];
let n = [-dir[1] * width / 2.0, dir[0] * width / 2.0];
vec![tip, [base[0] + n[0], base[1] + n[1]], [base[0] - n[0], base[1] - n[1]]]
}
/// A diamond head (for UML composition and aggregation) with its tip at `tip`, along `dir`.
pub(crate) fn diamond_head(tip: [f32; 2], dir: [f32; 2], len: f32, width: f32) -> Vec<[f32; 2]> {
let mid = [tip[0] - dir[0] * len / 2.0, tip[1] - dir[1] * len / 2.0];
let tail = [tip[0] - dir[0] * len, tip[1] - dir[1] * len];
let n = [-dir[1] * width / 2.0, dir[0] * width / 2.0];
vec![tip, [mid[0] + n[0], mid[1] + n[1]], tail, [mid[0] - n[0], mid[1] - n[1]]]
}
/// A smooth curve through `pts` (Catmull-Rom, as flattened cubics).
pub(crate) fn smooth(pts: &[[f32; 2]]) -> Vec<[f32; 2]> {
if pts.len() < 3 {
return pts.to_vec();
}
let n = pts.len();
let tangent = |i: usize| {
let (a, b) = if i == 0 {
(pts[0], pts[1])
} else if i == n - 1 {
(pts[n - 2], pts[n - 1])
} else {
(pts[i - 1], pts[i + 1])
};
let k = if i == 0 || i == n - 1 { 1.0 } else { 0.5 };
[(b[0] - a[0]) * k, (b[1] - a[1]) * k]
};
let mut out = vec![pts[0]];
for i in 0..n - 1 {
let (a, b) = (pts[i], pts[i + 1]);
let (ta, tb) = (tangent(i), tangent(i + 1));
let c1 = [a[0] + ta[0] / 3.0, a[1] + ta[1] / 3.0];
let c2 = [b[0] - tb[0] / 3.0, b[1] - tb[1] / 3.0];
let steps = ((dist(a, c1) + dist(c1, c2) + dist(c2, b)) / 4.0).ceil().clamp(2.0, 48.0) as usize;
for s in 1..=steps {
let t = s as f32 / steps as f32;
let u = 1.0 - t;
let (b0, b1, b2, b3) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t);
out.push([
b0 * a[0] + b1 * c1[0] + b2 * c2[0] + b3 * b[0],
b0 * a[1] + b1 * c1[1] + b2 * c2[1] + b3 * b[1],
]);
}
}
out
}
+232
View File
@@ -0,0 +1,232 @@
//! A diagram's drawing split into the things it shows (each node, edge and frame), so the
//! finished scene keys each by what it is: a diagram streaming in brings each new node, edge and
//! frame in on its own while the ones already there glide to their new places, and a finished
//! diagram draws the same pieces at once.
use std::collections::HashMap;
use rune::{Shape, Transition, canvas};
use super::{Canvas, Op};
use crate::layout::draw::Edge;
/// What a run of drawing is.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Kind {
/// A node, a participant, a note: fades and grows in.
Node,
/// A connector or message: draws on from its source to its target.
Edge,
/// A subgraph, a frame, a band, lifelines: fades in.
Frame,
}
impl Kind {
fn prefix(self) -> &'static str {
match self {
Kind::Node => "n:",
Kind::Edge => "e:",
Kind::Frame => "g:",
}
}
/// How a piece of this kind enters while its diagram streams in.
pub(crate) fn enter(self) -> Transition {
match self {
Kind::Node => Transition::scale(0.96),
Kind::Edge => Transition::draw(),
Kind::Frame => Transition::opacity(),
}
}
/// How a label of this kind enters: an edge's after its line is under way.
pub(crate) fn label_enter(self) -> (Transition, f32) {
match self {
Kind::Node => (Transition::scale(0.96), 0.0),
Kind::Edge => (Transition::opacity(), 0.12),
Kind::Frame => (Transition::opacity(), 0.0),
}
}
}
/// Which thing a run of drawing belongs to: the `i`th of its kind (named by [`Names`], so a
/// flowchart node keeps its key when nodes before it come and go), or one named outright.
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum Part {
Index(Kind, usize),
Key(Kind, String),
}
/// What the `i`th node, edge and frame are called (its Mermaid id). Unnamed ones go by index.
#[derive(Clone, Default)]
pub(crate) struct Names {
pub nodes: Vec<String>,
pub edges: Vec<String>,
pub frames: Vec<String>,
}
impl Names {
/// Nodes and frames named as given, edges by their ends' names (`A>B`, then `A>B~1` for a
/// second edge between the same two).
pub(crate) fn new(nodes: Vec<String>, edges: &[Edge], frames: Vec<String>) -> Names {
let id = |i: usize| nodes.get(i).cloned().unwrap_or_else(|| format!("#{i}"));
let mut seen: HashMap<(usize, usize), usize> = HashMap::new();
let edges = edges
.iter()
.map(|e| {
let n = seen.entry((e.from, e.to)).or_insert(0);
*n += 1;
let name = format!("{}>{}", id(e.from), id(e.to));
if *n == 1 { name } else { format!("{name}~{}", *n - 1) }
})
.collect();
Names { nodes, edges, frames }
}
fn key(&self, part: &Part) -> (String, Kind) {
match part {
Part::Index(k, i) => {
let list = match k {
Kind::Node => &self.nodes,
Kind::Edge => &self.edges,
Kind::Frame => &self.frames,
};
let name = list.get(*i).cloned().unwrap_or_else(|| format!("#{i}"));
(format!("{}{name}", k.prefix()), *k)
}
Part::Key(k, s) => (format!("{}{s}", k.prefix()), *k),
}
}
}
/// Where a part starts: the first op and label drawn for it (`None`: drawing that is no part).
pub(crate) type Mark = (usize, usize, Option<Part>);
impl Canvas {
/// What is drawn from here on belongs to `part`, until the next call (`None` ends it).
pub(crate) fn part(&mut self, part: Option<Part>) {
self.marks.push((self.ops.len(), self.labels.len(), part));
}
/// What `part` is keyed by, in its pieces and its hover groups alike.
pub(crate) fn part_key(&self, part: &Part) -> (String, Kind) {
let (key, kind) = self.names.key(part);
// Turned on its side, every edge takes a new route: a diagram streaming in glides its
// nodes to their new places and draws its edges on afresh, rather than bending the old
// lines into the new ones.
(if self.turned && kind == Kind::Edge { format!("{key}|v") } else { key }, kind)
}
/// The part drawn now: the one the last [`Canvas::part`] named.
pub(crate) fn current_part(&self) -> Option<Part> {
self.marks.last().and_then(|m| m.2.clone())
}
/// The runs of drawing, in order: each run's part, its ops and its labels.
pub(crate) fn runs(&self) -> Vec<(Option<&Part>, std::ops::Range<usize>, std::ops::Range<usize>)> {
let mut out = Vec::new();
let mut at = (0, 0, None);
for (o, l, p) in self.marks.iter().map(|(o, l, p)| (*o, *l, p.as_ref())).chain([(self.ops.len(), self.labels.len(), None)]) {
if o > at.0 || l > at.1 {
out.push((at.2, at.0..o, at.1..l));
}
at = (o, l, p);
}
out
}
}
/// One keyed piece of a finished scene: its own shape, placed at `at` and `size` big, in the
/// diagram's finished points.
pub(crate) struct Piece {
pub key: String,
pub kind: Option<Kind>,
pub at: [f32; 2],
pub size: [f32; 2],
pub shape: Shape,
}
/// Each label's key and kind, beside [`super::Scene::labels`].
pub(crate) type LabelKey = (String, Option<Kind>);
/// Splits `c`'s finished ops (already moved by `map`) into keyed pieces, and keys its labels by
/// the part each belongs to.
pub(crate) fn pieces(c: &Canvas, map: impl Fn([f32; 2]) -> [f32; 2]) -> (Vec<Piece>, Vec<LabelKey>) {
let mut pieces = Vec::new();
let mut label_keys = vec![(String::new(), None); c.labels.len()];
let mut seen: HashMap<String, usize> = HashMap::new();
let mut rest_labels = 0;
let mut rest_runs = 0;
for (part, ops, labels) in c.runs() {
let (key, kind) = match part {
Some(p) => {
let (key, kind) = c.part_key(p);
(key, Some(kind))
}
None => {
rest_runs += 1;
(if rest_runs == 1 { "shape".to_owned() } else { format!("shape{rest_runs}") }, None)
}
};
let n = seen.entry(key.clone()).or_insert(0);
let run_key = if *n == 0 { key } else { format!("{key}~{n}") };
*n += 1;
for (j, i) in labels.enumerate() {
label_keys[i] = match kind {
Some(k) => (format!("{run_key}.t{j}"), Some(k)),
None => {
rest_labels += 1;
(format!("t{}", rest_labels - 1), None)
}
};
}
if let Some(piece) = piece(&c.ops[ops], run_key, kind, &map) {
pieces.push(piece);
}
}
(pieces, label_keys)
}
fn piece(ops: &[Op], key: String, kind: Option<Kind>, map: &impl Fn([f32; 2]) -> [f32; 2]) -> Option<Piece> {
let mut b = [f32::MAX, f32::MAX, f32::MIN, f32::MIN];
let mut add = |p: [f32; 2], r: f32| b = [b[0].min(p[0] - r), b[1].min(p[1] - r), b[2].max(p[0] + r), b[3].max(p[1] + r)];
for op in ops {
match op {
Op::Fill(points, _) => points.iter().for_each(|&p| add(map(p), 0.0)),
// A point beyond the stroke's half width for its round caps and antialiasing.
Op::Stroke { points, width, .. } => points.iter().for_each(|&p| add(map(p), width / 2.0 + 1.0)),
}
}
if b[0] > b[2] {
return None;
}
let local = |p: [f32; 2]| {
let q = map(p);
[q[0] - b[0], q[1] - b[1]]
};
let shape = ops.iter().fold(Shape::new(), |s, op| match op {
Op::Fill(points, color) => s.fill(points.iter().map(|&p| local(p)).collect::<Vec<_>>(), *color),
Op::Stroke { points, closed, width, cap, color } => s.stroke_with(points.iter().map(|&p| local(p)).collect::<Vec<_>>(), *closed, *width, *cap, *color),
});
let size = [(b[2] - b[0]).max(1.0), (b[3] - b[1]).max(1.0)];
// Coordinates stretch with the piece, so a frame or lifeline that grows springs to its new
// size instead of jumping.
Some(Piece { key, kind, at: [b[0], b[1]], size, shape: shape.view_box(size[0], size[1]) })
}
impl Piece {
/// Placed by offset, not layout: a reply's growth row snaps the layout of what it holds,
/// but an offset still springs, so a piece glides to its new place there too.
pub(crate) fn el(&self, streaming: bool, scale: f32) -> rune::El {
let enter = match self.kind {
Some(k) if streaming => k.enter(),
None if streaming => Transition::opacity(),
_ => Transition::none(),
};
canvas(self.shape.clone()).key(self.key.clone()).absolute(0.0, 0.0).offset(self.at[0] * scale, self.at[1] * scale).size(self.size[0] * scale, self.size[1] * scale).transition(enter)
}
}
#[cfg(test)]
#[path = "parts_tests.rs"]
mod tests;
@@ -0,0 +1,118 @@
use rune::{Cx, El, Env, ElementInfo, Runtime, col};
use crate::{DiagramStyle, Hover, render_streaming, render_with_hover, scene};
fn keys(src: &str) -> Vec<String> {
let s = scene(src, &DiagramStyle::neutral(true), Some((Hover::Edges, DiagramStyle::neutral(true).text))).expect("draws");
s.pieces.iter().map(|p| p.key.clone()).chain(s.label_keys.iter().map(|k| k.0.clone())).collect()
}
fn has(keys: &[String], want: &[&str]) -> bool {
want.iter().all(|w| keys.iter().any(|k| k == w))
}
#[test]
fn flowchart_pieces_are_keyed_by_mermaid_id_across_rebuilds() {
let a = keys("graph TD\n A[Start] --> B{Ok?}\n");
assert!(has(&a, &["n:A", "n:B", "e:A>B", "n:A.t0", "n:B.t0"]), "{a:?}");
// A line arriving adds its own pieces and keeps every key it had.
let b = keys("graph TD\n A[Start] --> B{Ok?}\n B -->|yes| C[Done]\n B --> C\n");
assert!(a.iter().all(|k| b.contains(k)), "{a:?} → {b:?}");
assert!(has(&b, &["n:C", "e:B>C", "e:B>C~1", "e:B>C.t0"]), "{b:?}");
// A subgraph is a frame by its id; nodes inside it keep their ids when it arrives around them.
let c = keys("graph TD\n subgraph core [Core]\n A --> B\n end\n B --> C\n");
assert!(has(&c, &["g:core", "g:core.t0", "n:A", "n:B", "n:C", "e:A>B", "e:B>C"]), "{c:?}");
}
#[test]
fn sequence_and_state_pieces_keep_their_keys_as_lines_arrive() {
let a = keys("sequenceDiagram\n participant A\n participant B\n A->>B: hi\n");
assert!(has(&a, &["n:p0", "n:p1", "n:p0.end", "g:life0", "e:m0", "e:m0.t0"]), "{a:?}");
let b = keys("sequenceDiagram\n participant A\n participant B\n A->>B: hi\n B-->>A: hello\n Note over A,B: done\n");
assert!(a.iter().all(|k| b.contains(k)), "{a:?} → {b:?}");
assert!(has(&b, &["e:m1", "n:note2"]), "{b:?}");
let s = keys("stateDiagram-v2\n [*] --> Idle\n Idle --> Busy : go\n");
assert!(has(&s, &["n:Idle", "n:Busy", "e:Idle>Busy", "e:Idle>Busy.t0"]), "{s:?}");
}
fn find(rt: &Runtime<(String, bool)>, key: &str) -> Option<ElementInfo> {
rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key))
}
fn view(s: &(String, bool), _: &mut Cx<(String, bool)>) -> El {
let paint = DiagramStyle::neutral(true);
let render = if s.1 { render_streaming } else { render_with_hover };
col().w_full().children(render(&s.0, &paint, Hover::Edges, paint.text))
}
const ONE: &str = "graph TD\n A[Start] --> B[Check]\n";
const TWO: &str = "graph TD\n A[Start] --> B[Check]\n B --> C[Done]\n";
#[test]
fn a_finished_diagram_shows_whole_the_frame_it_mounts() {
let mut rt = Runtime::new((String::new(), false), view, (600.0, 600.0), Env::new(true, 1.0));
rt.frame(0.0);
rt.update(|s, _| s.0 = TWO.to_owned());
rt.frame(0.0);
// Everything but the hover groups, which stay unlit until hovered.
let shown: Vec<ElementInfo> = rt.elements().into_iter().filter(|e| e.key.as_deref().is_none_or(|k| !k.starts_with("hover:") && k != "lit")).collect();
assert!(find(&rt, "n:C").is_some() && find(&rt, "e:B>C").is_some());
for e in shown.iter().filter(|e| !e.path.contains("/hover:")) {
assert_eq!((e.opacity, e.scale), (1.0, 1.0), "{:?} fades or grows in", e.key);
}
// A rebuild that adds a node shows it whole too, and moves nothing that was there.
let mut rt = Runtime::new((ONE.to_owned(), false), view, (600.0, 600.0), Env::new(true, 1.0));
rt.frame(0.0);
rt.update(|s, _| s.0 = TWO.to_owned());
rt.frame(0.0);
assert_eq!(find(&rt, "n:C").unwrap().opacity, 1.0);
}
#[test]
fn a_streaming_diagram_brings_new_nodes_in_and_glides_the_rest() {
let mut rt = Runtime::new((ONE.to_owned(), true), view, (600.0, 600.0), Env::new(true, 1.0));
rt.frame(0.0);
for _ in 0..90 {
rt.frame(1.0 / 60.0);
}
let a = find(&rt, "n:A").unwrap();
rt.update(|s, _| s.0 = TWO.to_owned());
rt.frame(1.0 / 60.0);
let c = find(&rt, "n:C").unwrap();
assert!(c.opacity < 0.5 && c.scale < 1.0, "a new node fades and grows in: {} {}", c.opacity, c.scale);
assert_eq!(find(&rt, "n:A").unwrap().opacity, 1.0, "what's there stays");
for _ in 0..90 {
rt.frame(1.0 / 60.0);
}
let (c, a2) = (find(&rt, "n:C").unwrap(), find(&rt, "n:A").unwrap());
assert_eq!((c.opacity, c.scale), (1.0, 1.0));
assert_eq!(a.path, a2.path, "the same element throughout");
}
#[test]
fn a_streaming_diagram_glides_inside_a_growth_row() {
use rune::GrowthSpec;
// A reply's row in a timeline snaps its contents' layout; the pieces still glide.
fn view(s: &String, _: &mut Cx<String>) -> El {
let paint = DiagramStyle::neutral(true);
col().key("stack").w_full().growth(GrowthSpec::default())
.child(col().key("row").w_full().children(render_streaming(s, &paint, Hover::Edges, paint.text)))
}
let find = |rt: &Runtime<String>, key: &str| rt.elements().into_iter().find(|e| e.key.as_deref() == Some(key)).unwrap();
let mut rt = Runtime::new(TWO.to_owned(), view, (600.0, 600.0), Env::new(true, 1.0));
rt.frame(0.0);
let before = find(&rt, "n:B").rect;
rt.update(|s, _| s.push_str(" Z[First] --> A\n"));
for _ in 0..90 {
rt.frame(1.0 / 60.0);
}
let after = find(&rt, "n:B").rect;
assert!((after[1] - before[1]).abs() > 10.0, "the new node moves B: {before:?} {after:?}");
let mut rt = Runtime::new(TWO.to_owned(), view, (600.0, 600.0), Env::new(true, 1.0));
rt.frame(0.0);
rt.update(|s, _| s.push_str(" Z[First] --> A\n"));
rt.frame(1.0 / 60.0);
let mid = find(&rt, "n:B").rect;
assert!((mid[1] - before[1]).abs() < (after[1] - before[1]).abs() - 1.0, "B glides, never jumps: {before:?} {mid:?} {after:?}");
}
+106
View File
@@ -0,0 +1,106 @@
//! Built scenes, kept by source, style and hover, so a diagram rebuilt with nothing new costs a
//! lookup, and a diagram streaming in builds each line held to the one before (see [`steady`]).
use std::cell::RefCell;
use std::collections::{HashMap, VecDeque};
use std::hash::{Hash, Hasher};
use std::rc::Rc;
use rune::Color;
use super::Scene;
use crate::layout::steady;
use crate::{DiagramStyle, Hover, scene};
const CACHE_LEN: usize = 16;
#[derive(Default)]
pub(crate) struct Cache {
map: HashMap<u64, Built>,
order: VecDeque<u64>,
}
thread_local! {
pub(crate) static SCENES: RefCell<Cache> = RefCell::new(Cache::default());
}
/// A scene and, for one built growing, what its layouts leave for the next build to hold to.
pub(crate) type Built = (Option<Rc<Scene>>, Option<Rc<steady::Memory>>);
/// `src`'s scene, from the cache or built and kept; held to `prev` when it is `Some`.
pub(crate) fn built(src: &str, style: &DiagramStyle, hover: Option<(Hover, Color)>, prev: Option<Option<Rc<steady::Memory>>>) -> Built {
let key = scene_key(src, style, hover, prev.is_some());
if let Some(b) = SCENES.with_borrow(|c| c.map.get(&key).cloned()) {
return b;
}
let b = build(src, style, hover, prev);
SCENES.with_borrow_mut(|c| {
if c.order.len() >= CACHE_LEN
&& let Some(old) = c.order.pop_front()
{
c.map.remove(&old);
}
c.order.push_back(key);
c.map.insert(key, b.clone());
});
b
}
fn build(src: &str, style: &DiagramStyle, hover: Option<(Hover, Color)>, prev: Option<Option<Rc<steady::Memory>>>) -> Built {
// Defensive: a bug in layout must cost a diagram, not the app.
let safe = || std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| scene(src, style, hover))).ok().flatten();
match prev {
None => (safe().map(Rc::new), None),
Some(prev) => {
let held = prev.as_ref().map_or([0.0; 2], |m| m.size);
let (s, mut memory) = steady::build(prev, safe);
// Nor does the card shrink, even as the diagram shrinks to fit a wider layout.
let s = s.map(|mut s| {
s.size = [s.size[0].max(held[0]), s.size[1].max(held[1])];
s
});
memory.size = s.as_ref().map_or(held, |s| s.size);
(s.map(Rc::new), Some(Rc::new(memory)))
}
}
}
fn scene_key(src: &str, style: &DiagramStyle, hover: Option<(Hover, Color)>, growing: bool) -> u64 {
let mut h = std::collections::hash_map::DefaultHasher::new();
src.hash(&mut h);
style.hash(&mut h);
hover.hash(&mut h);
growing.hash(&mut h);
// Layout measures labels in the app's fonts.
rune::text::font_epoch().hash(&mut h);
h.finish()
}
/// How many lines back a growing build looks for one it can hold to before it starts afresh.
const MAX_HELD_LINES: usize = 64;
/// `src` laid out held to the same source a line shorter, laid out held to the one a line
/// shorter again, and so on, so it lays out the same however many lines each build added.
pub(crate) fn growing(src: &str, style: &DiagramStyle, hover: Option<(Hover, Color)>) -> Option<Rc<Scene>> {
let mut chain = vec![src.trim_end()];
let mut prev = None;
if let Some(b) = SCENES.with_borrow(|c| c.map.get(&scene_key(chain[0], style, hover, true)).cloned()) {
return b.0;
}
while let Some(shorter) = chain.last().and_then(|s| s.rfind('\n').map(|i| s[..i].trim_end())) {
if let Some(b) = SCENES.with_borrow(|c| c.map.get(&scene_key(shorter, style, hover, true)).cloned()) {
prev = b.1;
break;
}
if chain.len() >= MAX_HELD_LINES {
break;
}
chain.push(shorter);
}
// Only the source asked for is kept: the shorter ones were built for it alone.
let last = chain.remove(0);
for s in chain.into_iter().rev() {
prev = build(s, style, hover, Some(prev)).1;
}
built(last, style, hover, Some(prev)).0
}
+557
View File
@@ -0,0 +1,557 @@
//! Flowchart node shapes: every Mermaid v11 shape, its size around a label, its outline (what
//! edges meet and hovering lights up) and its drawing.
use rune::{Align, Color};
use super::{Canvas, Measured, arc, ellipse, rounded_rect};
use crate::DiagramStyle;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum NodeShape {
Rect,
Round,
Stadium,
Subroutine,
Cylinder,
Circle,
DoubleCircle,
Asymmetric,
Diamond,
Hexagon,
/// `[/text/]`
LeanRight,
/// `[\text\]`
LeanLeft,
/// `[/text\]`, wider at the bottom.
TrapBottom,
/// `[\text/]`, wider at the top.
TrapTop,
SmallCircle,
FilledCircle,
FramedCircle,
CrossedCircle,
Bang,
Cloud,
Card,
Hourglass,
Bolt,
BraceLeft,
BraceRight,
Braces,
Delay,
HCylinder,
LinedCylinder,
CurvedTrapezoid,
DividedRect,
Document,
LinedDocument,
Documents,
TaggedDocument,
Triangle,
FlippedTriangle,
Fork,
WindowPane,
LinedRect,
NotchedPentagon,
SlopedRect,
StackedRect,
Flag,
BowRect,
TaggedRect,
Text,
/// A sticky note with a folded corner, in the note colours.
Note,
}
use NodeShape as S;
impl NodeShape {
/// The shape a Mermaid `@{ shape: … }` name stands for, by short name or alias.
pub(crate) fn named(name: &str) -> Option<Self> {
Some(match name {
"rect" | "proc" | "process" | "rectangle" | "icon" | "image" => S::Rect,
"rounded" | "event" => S::Round,
"stadium" | "pill" | "terminal" => S::Stadium,
"fr-rect" | "framed-rectangle" | "subproc" | "subprocess" | "subroutine" => S::Subroutine,
"cyl" | "cylinder" | "database" | "db" => S::Cylinder,
"circle" | "circ" => S::Circle,
"dbl-circ" | "double-circle" => S::DoubleCircle,
"odd" => S::Asymmetric,
"diam" | "decision" | "diamond" | "question" => S::Diamond,
"hex" | "hexagon" | "prepare" => S::Hexagon,
"lean-r" | "lean-right" | "in-out" => S::LeanRight,
"lean-l" | "lean-left" | "out-in" => S::LeanLeft,
"trap-b" | "priority" | "trapezoid" | "trapezoid-bottom" => S::TrapBottom,
"trap-t" | "inv-trapezoid" | "manual" | "trapezoid-top" => S::TrapTop,
"sm-circ" | "small-circle" | "start" => S::SmallCircle,
"f-circ" | "filled-circle" | "junction" => S::FilledCircle,
"fr-circ" | "framed-circle" | "stop" => S::FramedCircle,
"cross-circ" | "crossed-circle" | "summary" => S::CrossedCircle,
"bang" => S::Bang,
"cloud" => S::Cloud,
"notch-rect" | "card" | "notched-rectangle" => S::Card,
"hourglass" | "collate" => S::Hourglass,
"bolt" | "com-link" | "lightning-bolt" => S::Bolt,
"brace" | "brace-l" | "comment" => S::BraceLeft,
"brace-r" => S::BraceRight,
"braces" => S::Braces,
"delay" | "half-rounded-rectangle" => S::Delay,
"h-cyl" | "das" | "horizontal-cylinder" => S::HCylinder,
"lin-cyl" | "disk" | "lined-cylinder" => S::LinedCylinder,
"curv-trap" | "curved-trapezoid" | "display" => S::CurvedTrapezoid,
"div-rect" | "div-proc" | "divided-process" | "divided-rectangle" => S::DividedRect,
"doc" | "document" => S::Document,
"lin-doc" | "lined-document" => S::LinedDocument,
"docs" | "documents" | "st-doc" | "stacked-document" => S::Documents,
"tag-doc" | "tagged-document" => S::TaggedDocument,
"tri" | "extract" | "triangle" => S::Triangle,
"flip-tri" | "flipped-triangle" | "manual-file" => S::FlippedTriangle,
"fork" | "join" => S::Fork,
"win-pane" | "internal-storage" | "window-pane" => S::WindowPane,
"lin-rect" | "lin-proc" | "lined-process" | "lined-rectangle" | "shaded-process" => S::LinedRect,
"notch-pent" | "loop-limit" | "notched-pentagon" => S::NotchedPentagon,
"sl-rect" | "manual-input" | "sloped-rectangle" => S::SlopedRect,
"st-rect" | "processes" | "procs" | "stacked-rectangle" => S::StackedRect,
"flag" | "paper-tape" => S::Flag,
"bow-rect" | "bow-tie-rectangle" | "stored-data" => S::BowRect,
"tag-rect" | "tag-proc" | "tagged-process" | "tagged-rectangle" => S::TaggedRect,
"text" => S::Text,
_ => return None,
})
}
/// Markers too small to hold their label, which they don't draw.
fn unlabelled(self) -> bool {
matches!(self, S::SmallCircle | S::FilledCircle | S::FramedCircle | S::CrossedCircle | S::Fork)
}
/// Shapes whose side facing the next rank is straight, so edges can meet it anywhere along it.
pub(crate) fn flat(self) -> bool {
!matches!(
self,
S::Stadium
| S::Cylinder
| S::Circle
| S::DoubleCircle
| S::Diamond
| S::Hexagon
| S::LeanRight
| S::LeanLeft
| S::TrapBottom
| S::TrapTop
| S::SmallCircle
| S::FilledCircle
| S::FramedCircle
| S::CrossedCircle
| S::Bang
| S::Cloud
| S::LinedCylinder
| S::Triangle
| S::FlippedTriangle
)
}
}
const PAD: [f32; 2] = [30.0, 22.0];
const GLYPH: f32 = 32.0;
/// How far a stacked shape's back copies sit up and to the right.
const STACK: f32 = 5.0;
pub(crate) fn node_size(shape: NodeShape, t: [f32; 2]) -> [f32; 2] {
let [w, h] = [t[0] + PAD[0], (t[1] + PAD[1]).max(40.0)];
let rect = w.max(60.0);
match shape {
S::Rect | S::Round | S::TaggedRect | S::Note => [rect, h],
S::Stadium | S::Hexagon => [w + h / 2.0, h],
S::Subroutine | S::LinedRect | S::Card => [w + 16.0, h],
S::Asymmetric => [w + h / 3.0, h],
// The top rim, the body a box would be, and the bottom rim's bulge.
S::Cylinder => [rect, h + 3.0 * rim(rect)],
S::LinedCylinder => [rect, h + 3.0 * rim(rect) + LINED],
S::HCylinder => [w + 24.0, h],
S::LeanRight | S::LeanLeft | S::TrapBottom | S::TrapTop => [w + h * 0.6, h],
S::Circle => circle(t, 20.0),
S::DoubleCircle => circle(t, 30.0),
S::Diamond => {
let a = t[0] / 2.0 + t[1] + 12.0;
let b = t[1] / 2.0 * a / (t[1] + 12.0) + 10.0;
[2.0 * a, (2.0 * b).max(40.0)]
}
S::SmallCircle | S::FilledCircle => [14.0, 14.0],
S::FramedCircle => [20.0, 20.0],
S::CrossedCircle => [30.0, 30.0],
S::Fork => [70.0, 10.0],
S::Bang => [w * 1.5, h * 1.7],
S::Cloud => [w * 1.35, h * 1.55],
S::Hourglass | S::Bolt => [t[0].max(GLYPH), if t[1] > 0.0 { GLYPH + 6.0 + t[1] } else { GLYPH }],
S::BraceLeft | S::BraceRight => [w + 6.0, h],
S::Braces => [w + 18.0, h],
S::Delay | S::CurvedTrapezoid | S::BowRect => [w + h / 2.0, h],
S::DividedRect => [rect, h + 10.0],
S::Document | S::LinedDocument | S::TaggedDocument | S::Flag | S::SlopedRect => [rect + 8.0, h + 12.0],
S::Documents => [rect + 8.0 + 2.0 * STACK, h + 12.0 + 2.0 * STACK],
S::StackedRect => [rect + 2.0 * STACK, h + 2.0 * STACK],
S::Triangle | S::FlippedTriangle => {
let w = 1.6 * (t[0] + 16.0);
[w.max(60.0), (0.7 * w).max(3.0 * t[1] + 16.0)]
}
S::WindowPane => [rect + 10.0, h + 10.0],
S::NotchedPentagon => [w + 24.0, h],
S::Text => [t[0] + 12.0, t[1] + 12.0],
}
}
/// How deep a cylinder `w` wide draws its rims: half their height, in Mermaid's proportion.
pub(crate) fn rim(w: f32) -> f32 {
w / 2.0 / (2.5 + w / 50.0)
}
/// How far a lined cylinder's second rim sits below its first.
const LINED: f32 = 6.0;
fn circle(t: [f32; 2], pad: f32) -> [f32; 2] {
let d = ((t[0] * t[0] + t[1] * t[1]).sqrt() + pad).max(48.0);
[d, d]
}
/// Where the line from `c` toward `toward` leaves a node of `shape` and `size` centred at `c`.
pub(crate) fn boundary(shape: NodeShape, c: [f32; 2], size: [f32; 2], toward: [f32; 2]) -> [f32; 2] {
let (dx, dy) = (toward[0] - c[0], toward[1] - c[1]);
if dx.abs() < 1e-3 && dy.abs() < 1e-3 {
return c;
}
let (a, b) = (size[0] / 2.0, size[1] / 2.0);
let rect = || {
let tx = if dx.abs() > 1e-3 { a / dx.abs() } else { f32::MAX };
let ty = if dy.abs() > 1e-3 { b / dy.abs() } else { f32::MAX };
tx.min(ty)
};
let t = match shape {
S::Circle | S::DoubleCircle | S::SmallCircle | S::FilledCircle | S::FramedCircle | S::CrossedCircle => {
1.0 / ((dx / a).powi(2) + (dy / b).powi(2)).sqrt()
}
S::Diamond => 1.0 / (dx.abs() / a + dy.abs() / b),
S::Rect
| S::Round
| S::Subroutine
| S::Asymmetric
| S::Stadium
| S::Hexagon
| S::Cylinder
| S::LeanRight
| S::LeanLeft
| S::TrapBottom
| S::TrapTop
| S::Hourglass
| S::Bolt
| S::BraceLeft
| S::BraceRight
| S::Braces
| S::Text => rect(),
_ => ray_exit(&outline(shape, c, size), c, [dx, dy]).unwrap_or_else(rect),
};
let t = t.min(1.0);
[c[0] + dx * t, c[1] + dy * t]
}
/// The furthest `t` at which `c + t·d` crosses `poly`.
fn ray_exit(poly: &[[f32; 2]], c: [f32; 2], d: [f32; 2]) -> Option<f32> {
let mut best: Option<f32> = None;
for i in 0..poly.len() {
let (p, q) = (poly[i], poly[(i + 1) % poly.len()]);
let e = [q[0] - p[0], q[1] - p[1]];
let den = d[0] * e[1] - d[1] * e[0];
if den.abs() < 1e-9 {
continue;
}
let w = [p[0] - c[0], p[1] - c[1]];
let t = (w[0] * e[1] - w[1] * e[0]) / den;
let u = (w[0] * d[1] - w[1] * d[0]) / den;
if t > 0.0 && (0.0..=1.0).contains(&u) && best.is_none_or(|b| t > b) {
best = Some(t);
}
}
best
}
/// The box a node takes: `(x0, y0, x1, y1)`.
fn bounds(c: [f32; 2], s: [f32; 2]) -> (f32, f32, f32, f32) {
(c[0] - s[0] / 2.0, c[1] - s[1] / 2.0, c[0] + s[0] / 2.0, c[1] + s[1] / 2.0)
}
fn rect(x0: f32, y0: f32, x1: f32, y1: f32) -> Vec<[f32; 2]> {
vec![[x0, y0], [x1, y0], [x1, y1], [x0, y1]]
}
/// A wavy line from `x0` to `x1` around `y`, one and a half periods long.
fn wave(x0: f32, x1: f32, y: f32, amp: f32) -> Vec<[f32; 2]> {
let n = 24;
(0..=n)
.map(|i| {
let f = i as f32 / n as f32;
[x0 + (x1 - x0) * f, y + amp * (f * std::f32::consts::TAU * 1.5).sin()]
})
.collect()
}
/// A quadratic Bézier from `a` through control `k` to `b`, as points.
fn quad(a: [f32; 2], k: [f32; 2], b: [f32; 2]) -> Vec<[f32; 2]> {
(0..=8)
.map(|i| {
let t = i as f32 / 8.0;
let m = 1.0 - t;
[m * m * a[0] + 2.0 * m * t * k[0] + t * t * b[0], m * m * a[1] + 2.0 * m * t * k[1] + t * t * b[1]]
})
.collect()
}
/// A curly brace down the line `x` from `y0` to `y1`, its point toward `side` (-1 left, 1 right).
fn brace(x: f32, y0: f32, y1: f32, side: f32) -> Vec<[f32; 2]> {
let (r, cy) = (6.0, (y0 + y1) / 2.0);
let mut p = quad([x - side * r, y0], [x, y0], [x, y0 + r]);
p.extend(quad([x, cy - r], [x, cy], [x + side * r, cy]));
p.extend(quad([x + side * r, cy], [x, cy], [x, cy + r]));
p.extend(quad([x, y1 - r], [x, y1], [x - side * r, y1]));
p
}
/// A document's outline: a box whose bottom edge waves.
fn document(x0: f32, y0: f32, x1: f32, y1: f32) -> Vec<[f32; 2]> {
let mut p = vec![[x0, y0], [x1, y0]];
p.extend(wave(x1, x0, y1 - 6.0, 5.0));
p
}
/// The glyph's box for shapes drawn as a glyph over their label.
fn glyph_box(c: [f32; 2], s: [f32; 2]) -> (f32, f32, f32, f32) {
let y0 = c[1] - s[1] / 2.0;
(c[0] - GLYPH / 2.0, y0, c[0] + GLYPH / 2.0, y0 + GLYPH)
}
pub(crate) fn outline(shape: NodeShape, c: [f32; 2], s: [f32; 2]) -> Vec<[f32; 2]> {
let (x0, y0, x1, y1) = bounds(c, s);
let (h, cy) = (s[1], c[1]);
match shape {
S::Rect | S::Subroutine | S::DividedRect | S::LinedRect | S::WindowPane | S::TaggedRect => rounded_rect(x0, y0, x1, y1, 3.0),
S::Round => rounded_rect(x0, y0, x1, y1, 10.0),
S::Stadium => rounded_rect(x0, y0, x1, y1, h / 2.0),
S::Circle | S::DoubleCircle | S::SmallCircle | S::FilledCircle | S::FramedCircle | S::CrossedCircle => {
ellipse(c, s[0] / 2.0, s[1] / 2.0)
}
S::Diamond => vec![[c[0], y0], [x1, cy], [c[0], y1], [x0, cy]],
S::Hexagon => {
let i = h / 4.0;
vec![[x0 + i, y0], [x1 - i, y0], [x1, cy], [x1 - i, y1], [x0 + i, y1], [x0, cy]]
}
S::Asymmetric => vec![[x0, y0], [x1, y0], [x1, y1], [x0, y1], [x0 + h / 3.0, cy]],
S::LeanRight => vec![[x0 + h * 0.3, y0], [x1, y0], [x1 - h * 0.3, y1], [x0, y1]],
S::LeanLeft => vec![[x0, y0], [x1 - h * 0.3, y0], [x1, y1], [x0 + h * 0.3, y1]],
S::TrapBottom => vec![[x0 + h * 0.3, y0], [x1 - h * 0.3, y0], [x1, y1], [x0, y1]],
S::TrapTop => vec![[x0, y0], [x1, y0], [x1 - h * 0.3, y1], [x0 + h * 0.3, y1]],
S::Cylinder | S::LinedCylinder => {
let (rx, ry) = (s[0] / 2.0, rim(s[0]));
let mut pts = arc([c[0], y0 + ry], rx, ry, 180.0, 360.0, 20);
pts.extend(arc([c[0], y1 - ry], rx, ry, 0.0, 180.0, 20));
pts
}
S::HCylinder => {
let (rx, ry) = (8.0, h / 2.0);
let mut pts = arc([x1 - rx, cy], rx, ry, -90.0, 90.0, 20);
pts.extend(arc([x0 + rx, cy], rx, ry, 90.0, 270.0, 20));
pts
}
S::Bang => (0..28)
.map(|i| {
let a = (i as f32 * 360.0 / 28.0).to_radians();
let r = if i % 2 == 0 { 1.0 } else { 0.8 };
[c[0] + s[0] / 2.0 * r * a.cos(), cy + s[1] / 2.0 * r * a.sin()]
})
.collect(),
S::Cloud => (0..120)
.map(|i| {
let a = (i as f32 * 3.0).to_radians();
let r = 0.84 + 0.16 * (5.0 * a).sin().abs().sqrt();
[c[0] + s[0] / 2.0 * r * a.cos(), cy + s[1] / 2.0 * r * a.sin()]
})
.collect(),
S::Card => vec![[x0 + 12.0, y0], [x1, y0], [x1, y1], [x0, y1], [x0, y0 + 12.0]],
S::Note => vec![[x0, y0], [x1 - 10.0, y0], [x1, y0 + 10.0], [x1, y1], [x0, y1]],
S::NotchedPentagon => vec![[x0 + 12.0, y0], [x1 - 12.0, y0], [x1, y0 + 12.0], [x1, y1], [x0, y1], [x0, y0 + 12.0]],
S::SlopedRect => vec![[x0, y0 + 12.0], [x1, y0], [x1, y1], [x0, y1]],
S::Delay => {
let mut p = vec![[x0, y0]];
p.extend(arc([x1 - h / 2.0, cy], h / 2.0, h / 2.0, -90.0, 90.0, 16));
p.push([x0, y1]);
p
}
S::CurvedTrapezoid => {
let k = h / 4.0;
let mut p = vec![[x0 + k, y0]];
p.extend(arc([x1 - h / 2.0, cy], h / 2.0, h / 2.0, -90.0, 90.0, 16));
p.extend(quad([x0 + k, y1], [x0, y1], [x0, cy]));
p.extend(quad([x0, cy], [x0, y0], [x0 + k, y0]));
p
}
S::BowRect => {
let rx = h / 4.0;
let mut p = arc([x1, cy], rx, h / 2.0, 270.0, 90.0, 16);
p.extend(arc([x0 + rx, cy], rx, h / 2.0, 90.0, 270.0, 16));
p
}
S::Document | S::LinedDocument | S::TaggedDocument => document(x0, y0, x1, y1),
S::Documents => document(x0, y0 + 2.0 * STACK, x1 - 2.0 * STACK, y1),
S::StackedRect => rect(x0, y0 + 2.0 * STACK, x1 - 2.0 * STACK, y1),
S::Flag => {
let mut p = wave(x0, x1, y0 + 6.0, 5.0);
p.extend(wave(x1, x0, y1 - 6.0, 5.0));
p
}
S::Triangle => vec![[c[0], y0], [x1, y1], [x0, y1]],
S::FlippedTriangle => vec![[x0, y0], [x1, y0], [c[0], y1]],
S::Fork => rounded_rect(x0, y0, x1, y1, 2.0),
S::Hourglass | S::Bolt | S::BraceLeft | S::BraceRight | S::Braces | S::Text => rect(x0, y0, x1, y1),
}
}
/// Draws a node of `shape` at `ctr` with its label, in `fill`, `border` and `text` colours.
#[allow(clippy::too_many_arguments, reason = "one node's whole drawing")]
/// A cylinder's open end, a shade off its side so the shape reads even without an outline.
fn lid(fill: Color, paint: &DiagramStyle) -> Color {
super::over_color(paint.text.alpha(0.06), fill)
}
pub(crate) fn draw(
c: &mut Canvas,
shape: NodeShape,
label: &Measured,
ctr: [f32; 2],
size: [f32; 2],
[fill, border, text]: [Color; 3],
paint: &DiagramStyle,
) {
let (x0, y0, x1, y1) = bounds(ctr, size);
let h = size[1];
let line = |c: &mut Canvas, pts: Vec<[f32; 2]>| c.stroke(pts, false, 1.0, border);
let mut at = ctr;
match shape {
S::Text => {}
S::BraceLeft => {
c.stroke(brace(x0 + 6.0, y0 + 2.0, y1 - 2.0, -1.0), false, 1.25, border);
at[0] += 3.0;
}
S::BraceRight => {
c.stroke(brace(x1 - 6.0, y0 + 2.0, y1 - 2.0, 1.0), false, 1.25, border);
at[0] -= 3.0;
}
S::Braces => {
c.stroke(brace(x0 + 6.0, y0 + 2.0, y1 - 2.0, -1.0), false, 1.25, border);
c.stroke(brace(x1 - 6.0, y0 + 2.0, y1 - 2.0, 1.0), false, 1.25, border);
}
S::FilledCircle | S::Fork => c.fill(outline(shape, ctr, size), paint.line),
S::FramedCircle => {
c.shape(outline(shape, ctr, size), fill, paint.line, 1.5);
c.fill(ellipse(ctr, 5.5, 5.5), paint.line);
}
S::Hourglass => {
let (g0, gy0, g1, gy1) = glyph_box(ctr, size);
let mid = [ctr[0], (gy0 + gy1) / 2.0];
c.shape(vec![[g0, gy0], [g1, gy0], mid, [g1, gy1], [g0, gy1], mid], fill, border, 1.0);
at[1] = gy1 + 6.0 + label.size[1] / 2.0;
}
S::Bolt => {
let (g0, gy0, _, _) = glyph_box(ctr, size);
let p = |x: f32, y: f32| [g0 + x * GLYPH, gy0 + y * GLYPH];
c.shape(vec![p(0.6, 0.0), p(0.15, 0.58), p(0.45, 0.58), p(0.35, 1.0), p(0.85, 0.4), p(0.55, 0.4), p(0.75, 0.0)], fill, border, 1.0);
at[1] = gy0 + GLYPH + 6.0 + label.size[1] / 2.0;
}
S::Documents => {
for k in [2.0, 1.0] {
let d = k * STACK;
c.shape(document(x0 + d, y0 + 2.0 * STACK - d, x1 - 2.0 * STACK + d, y1 - d), fill, border, 1.0);
}
c.shape(outline(shape, ctr, size), fill, border, 1.0);
at = [ctr[0] - STACK, ctr[1] + STACK - 3.0];
}
S::StackedRect => {
for k in [2.0, 1.0] {
let d = k * STACK;
c.shape(rect(x0 + d, y0 + 2.0 * STACK - d, x1 - 2.0 * STACK + d, y1 - d), fill, border, 1.0);
}
c.shape(outline(shape, ctr, size), fill, border, 1.0);
at = [ctr[0] - STACK, ctr[1] + STACK];
}
S::Note => {
c.shape(outline(shape, ctr, size), paint.note_fill, paint.note_border, 1.0);
c.stroke(vec![[x1 - 10.0, y0], [x1 - 10.0, y0 + 10.0], [x1, y0 + 10.0]], false, 1.0, paint.note_border);
}
_ => {
c.shape(outline(shape, ctr, size), fill, border, 1.0);
match shape {
S::Subroutine => {
line(c, vec![[x0 + 8.0, y0], [x0 + 8.0, y1]]);
line(c, vec![[x1 - 8.0, y0], [x1 - 8.0, y1]]);
}
// The top is a filled lid, a shade off the side, so it reads without a heavy rim. The
// label sits in the body under it.
S::Cylinder => {
let ry = rim(size[0]);
c.shape(ellipse([ctr[0], y0 + ry], size[0] / 2.0, ry), lid(fill, paint), border, 1.0);
at[1] += ry / 2.0;
}
S::LinedCylinder => {
let ry = rim(size[0]);
c.shape(ellipse([ctr[0], y0 + ry], size[0] / 2.0, ry), lid(fill, paint), border, 1.0);
line(c, arc([ctr[0], y0 + ry + LINED], size[0] / 2.0, ry, 0.0, 180.0, 24));
at[1] += (ry + LINED) / 2.0;
}
S::HCylinder => {
c.shape(ellipse([x1 - 8.0, ctr[1]], 8.0, h / 2.0), lid(fill, paint), border, 1.0);
at[0] -= 4.0;
}
S::DoubleCircle => c.stroke(ellipse(ctr, size[0] / 2.0 - 5.0, size[1] / 2.0 - 5.0), true, 1.0, border),
S::CrossedCircle => {
let r = size[0] / 2.0 * std::f32::consts::FRAC_1_SQRT_2;
line(c, vec![[ctr[0] - r, ctr[1] - r], [ctr[0] + r, ctr[1] + r]]);
line(c, vec![[ctr[0] - r, ctr[1] + r], [ctr[0] + r, ctr[1] - r]]);
}
S::DividedRect => {
line(c, vec![[x0, y0 + 10.0], [x1, y0 + 10.0]]);
at[1] += 5.0;
}
S::LinedRect => {
line(c, vec![[x0 + 8.0, y0], [x0 + 8.0, y1]]);
at[0] += 4.0;
}
S::WindowPane => {
line(c, vec![[x0 + 10.0, y0], [x0 + 10.0, y1]]);
line(c, vec![[x0, y0 + 10.0], [x1, y0 + 10.0]]);
at = [at[0] + 5.0, at[1] + 5.0];
}
S::TaggedRect => line(c, vec![[x1 - 12.0, y1], [x1, y1 - 12.0]]),
S::LinedDocument => {
line(c, vec![[x0 + 8.0, y0], [x0 + 8.0, y1 - 6.0]]);
at = [at[0] + 4.0, at[1] - 3.0];
}
S::TaggedDocument => {
line(c, vec![[x1 - 14.0, y1 - 4.0], [x1, y1 - 16.0]]);
at[1] -= 3.0;
}
S::Document => at[1] -= 3.0,
S::SlopedRect => at[1] += 6.0,
S::CurvedTrapezoid => at[0] -= h / 8.0,
S::Delay => at[0] -= h / 6.0,
S::Card => at[0] += 4.0,
S::Triangle => at[1] = y0 + 0.68 * h,
S::FlippedTriangle => at[1] = y0 + 0.32 * h,
_ => {}
}
}
}
if !shape.unlabelled() {
c.label(label, at, paint.font, text, Align::Center);
}
}
#[cfg(test)]
#[path = "shape_tests.rs"]
mod tests;
@@ -0,0 +1,127 @@
use super::*;
use crate::canvas::{Op, measure};
const ALL: &[NodeShape] = &[
S::Rect,
S::Round,
S::Stadium,
S::Subroutine,
S::Cylinder,
S::Circle,
S::DoubleCircle,
S::Asymmetric,
S::Diamond,
S::Hexagon,
S::LeanRight,
S::LeanLeft,
S::TrapBottom,
S::TrapTop,
S::SmallCircle,
S::FilledCircle,
S::FramedCircle,
S::CrossedCircle,
S::Bang,
S::Cloud,
S::Card,
S::Hourglass,
S::Bolt,
S::BraceLeft,
S::BraceRight,
S::Braces,
S::Delay,
S::HCylinder,
S::LinedCylinder,
S::CurvedTrapezoid,
S::DividedRect,
S::Document,
S::LinedDocument,
S::Documents,
S::TaggedDocument,
S::Triangle,
S::FlippedTriangle,
S::Fork,
S::WindowPane,
S::LinedRect,
S::NotchedPentagon,
S::SlopedRect,
S::StackedRect,
S::Flag,
S::BowRect,
S::TaggedRect,
S::Text,
S::Note,
];
fn inside(p: [f32; 2], c: [f32; 2], s: [f32; 2], slack: f32) -> bool {
(p[0] - c[0]).abs() <= s[0] / 2.0 + slack && (p[1] - c[1]).abs() <= s[1] / 2.0 + slack
}
#[test]
fn every_shape_stays_in_its_box_and_holds_its_label() {
let paint = DiagramStyle::neutral(false);
let label = measure("Process step", paint.font);
let c = [100.0, 80.0];
for &shape in ALL {
let size = node_size(shape, label.size);
let poly = outline(shape, c, size);
assert!(poly.len() >= 3, "{shape:?}");
assert!(poly.iter().all(|&p| inside(p, c, size, 0.5)), "{shape:?} outline leaves its box");
let mut canvas = Canvas::default();
draw(&mut canvas, shape, &label, c, size, [paint.node_fill, paint.node_border, paint.text], &paint);
for op in &canvas.ops {
let (Op::Fill(points, _) | Op::Stroke { points, .. }) = op;
assert!(points.iter().all(|&p| inside(p, c, size, 0.5)), "{shape:?} draws outside its box");
}
if shape.unlabelled() {
assert!(canvas.labels.is_empty(), "{shape:?} is too small for a label");
} else {
let l = &canvas.labels[0];
let (lo, hi) = (l.at, [l.at[0] + l.size[0], l.at[1] + l.size[1]]);
assert!(inside(lo, c, size, 0.5) && inside(hi, c, size, 0.5), "{shape:?} label leaves its box");
}
}
}
#[test]
fn boundary_points_stay_on_or_in_the_box() {
let c = [0.0, 0.0];
for &shape in ALL {
let size = node_size(shape, [80.0, 18.0]);
for toward in [[0.0, 200.0], [0.0, -200.0], [200.0, 0.0], [-150.0, 90.0]] {
let b = boundary(shape, c, size, toward);
assert!(inside(b, c, size, 0.5), "{shape:?} toward {toward:?}: {b:?}");
assert!(b[0].abs() + b[1].abs() > 3.0, "{shape:?} toward {toward:?} stops at the centre");
}
}
}
#[test]
fn a_ray_leaves_a_triangle_on_its_slanted_side() {
let size = [100.0, 60.0];
let b = boundary(S::Triangle, [0.0, 0.0], size, [0.0, -100.0]);
assert!((b[1] + 30.0).abs() < 1e-3, "straight up meets the apex: {b:?}");
let b = boundary(S::Triangle, [0.0, 0.0], size, [100.0, -60.0]);
assert!(b[0] < 50.0 && b[0] > 0.0 && b[1] > -30.0, "up and right meets the slant first: {b:?}");
}
#[test]
fn a_cylinder_has_mermaids_rims_and_its_label_under_the_front_one() {
let paint = DiagramStyle::neutral(false);
let label = measure("Note: lasts, has versions", paint.font);
let size = node_size(S::Cylinder, label.size);
let ry = rim(size[0]);
assert!((ry - size[0] / 2.0 / (2.5 + size[0] / 50.0)).abs() < 1e-3, "rim {ry} for width {}", size[0]);
let mut c = Canvas::default();
draw(&mut c, S::Cylinder, &label, [0.0, 0.0], size, [paint.node_fill, paint.node_border, paint.text], &paint);
let (top, bottom) = (-size[1] / 2.0, size[1] / 2.0);
// Past the outline, all a cylinder draws is its top rim, however it's painted.
let body = outline(S::Cylinder, [0.0, 0.0], size);
let rims: Vec<&Vec<[f32; 2]>> = c.ops.iter().map(|op| match op {
Op::Fill(points, _) | Op::Stroke { points, .. } => points,
}).filter(|p| **p != body).collect();
assert!(!rims.is_empty(), "a front rim on top");
assert!(rims.iter().flat_map(|p| p.iter()).all(|p| p[1] >= top - 0.01 && p[1] <= top + 2.0 * ry + 0.01), "nothing but the top rim inside the body");
let l = &c.labels[0];
assert!(l.at[1] >= top + 2.0 * ry, "the label clears the front rim: {} vs {}", l.at[1], top + 2.0 * ry);
assert!(l.at[1] + l.size[1] <= bottom - ry, "and the bottom rim");
}
+377
View File
@@ -0,0 +1,377 @@
//! Calendar arithmetic for gantt charts, with no time zones: times are milliseconds from
//! 1970-01-01 00:00. Dates read with a dayjs-style `dateFormat` and print with a d3-style
//! `axisFormat`.
const SEC: f64 = 1000.0;
const MIN: f64 = 60.0 * SEC;
const HOUR: f64 = 60.0 * MIN;
pub(crate) const DAY: f64 = 24.0 * HOUR;
/// Days from 1970-01-01 to `y-m-d` (proleptic Gregorian).
pub(crate) fn days_from_civil(y: i64, m: u32, d: u32) -> i64 {
let y = if m <= 2 { y - 1 } else { y };
let era = y.div_euclid(400);
let yoe = y - era * 400;
let mp = (m as i64 + 9) % 12;
let doy = (153 * mp + 2) / 5 + d as i64 - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
era * 146_097 + doe - 719_468
}
/// `(year, month, day)` of a day number from [`days_from_civil`].
fn civil_from_days(z: i64) -> (i64, u32, u32) {
let z = z + 719_468;
let era = z.div_euclid(146_097);
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
(if m <= 2 { yoe + era * 400 + 1 } else { yoe + era * 400 }, m, d)
}
fn days_in_month(y: i64, m: u32) -> u32 {
match m {
2 if (y % 4 == 0 && y % 100 != 0) || y % 400 == 0 => 29,
2 => 28,
4 | 6 | 9 | 11 => 30,
_ => 31,
}
}
/// A time's calendar fields.
#[derive(Clone, Copy, Debug, PartialEq)]
struct Fields {
y: i64,
mo: u32,
d: u32,
h: u32,
mi: u32,
s: u32,
ms: u32,
/// 0 is Sunday.
wd: u32,
}
fn fields(t: f64) -> Fields {
let day = (t / DAY).floor();
let (y, mo, d) = civil_from_days(day as i64);
let rest = (t - day * DAY).max(0.0) as u64;
Fields {
y,
mo,
d,
h: (rest / HOUR as u64) as u32,
mi: (rest / MIN as u64 % 60) as u32,
s: (rest / SEC as u64 % 60) as u32,
ms: (rest % 1000) as u32,
wd: (day as i64 + 4).rem_euclid(7) as u32,
}
}
fn at(y: i64, mo: u32, d: u32, h: u32, mi: u32, s: u32, ms: u32) -> Option<f64> {
let ok = (1..=12).contains(&mo) && d >= 1 && d <= days_in_month(y, mo) && h < 24 && mi < 60 && s < 60 && (-9999..=9999).contains(&y);
ok.then(|| days_from_civil(y, mo, d) as f64 * DAY + h as f64 * HOUR + mi as f64 * MIN + s as f64 * SEC + ms as f64)
}
/// `t` moved by `n` calendar months, keeping its day where the month has it.
fn add_months(t: f64, n: i64) -> f64 {
let f = fields(t);
let m0 = f.y * 12 + f.mo as i64 - 1 + n;
let (y, mo) = (m0.div_euclid(12), m0.rem_euclid(12) as u32 + 1);
let d = f.d.min(days_in_month(y, mo));
at(y, mo, d, f.h, f.mi, f.s, f.ms).unwrap_or(t)
}
const MONTHS: [&str; 12] = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const DAYS: [&str; 7] = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
/// `s` read with a dayjs format (`YYYY-MM-DD`, `DD/MM/YYYY HH:mm`, `X`, …), or, failing that,
/// as an ISO date and time.
pub(crate) fn parse(s: &str, format: &str) -> Option<f64> {
let s = s.trim();
with_format(s, format)
.or_else(|| ["YYYY-MM-DDTHH:mm:ss", "YYYY-MM-DD HH:mm:ss", "YYYY-MM-DDTHH:mm", "YYYY-MM-DD HH:mm", "YYYY-MM-DD"].iter().find_map(|f| with_format(s, f)))
}
fn with_format(s: &str, format: &str) -> Option<f64> {
let (mut y, mut mo, mut d, mut h, mut mi, mut sec, mut ms) = (1970i64, 1u32, 1u32, 0u32, 0u32, 0u32, 0u32);
let mut pm = None;
let (f, mut rest) = (format.as_bytes(), s);
let mut i = 0;
let number = |rest: &mut &str, max: usize| -> Option<i64> {
let n = rest.bytes().take(max).take_while(u8::is_ascii_digit).count();
let v = rest.get(..n).filter(|v| !v.is_empty())?.parse().ok()?;
*rest = &rest[n..];
Some(v)
};
const TOKENS: [&str; 20] = ["YYYY", "MMMM", "MMM", "SSS", "YY", "MM", "DD", "HH", "hh", "mm", "ss", "Do", "M", "D", "H", "h", "m", "s", "A", "a"];
while i < f.len() {
if f[i] == b'[' {
let end = format[i..].find(']').map_or(f.len(), |e| i + e);
rest = rest.strip_prefix(&format[i + 1..end])?;
i = end + 1;
continue;
}
if f[i] == b'X' || f[i] == b'x' {
let neg = rest.starts_with('-');
let digits = rest.trim_start_matches('-');
let n = digits.bytes().take_while(|b| b.is_ascii_digit() || *b == b'.').count();
let v: f64 = digits[..n].parse().ok()?;
let v = if neg { -v } else { v } * if f[i] == b'X' { SEC } else { 1.0 };
return (digits[n..].trim().is_empty() && v.abs() < 2.5e14).then_some(v);
}
let Some(tok) = TOKENS.iter().find(|t| format[i..].starts_with(**t)) else {
rest = rest.strip_prefix(format[i..].chars().next()?)?;
i += format[i..].chars().next()?.len_utf8();
continue;
};
match *tok {
"YYYY" => y = number(&mut rest, 4)?,
"YY" => y = 2000 + number(&mut rest, 2)?,
"MMMM" | "MMM" => {
let lower = rest.to_ascii_lowercase();
let (m, len) = MONTHS.iter().enumerate().find_map(|(k, name)| {
let name = name.to_ascii_lowercase();
if lower.starts_with(&name) {
Some((k, name.len()))
} else {
lower.starts_with(&name[..3]).then_some((k, 3))
}
})?;
mo = m as u32 + 1;
rest = &rest[len..];
}
"MM" | "M" => mo = number(&mut rest, 2)? as u32,
"DD" | "D" => d = number(&mut rest, 2)? as u32,
"Do" => {
d = number(&mut rest, 2)? as u32;
rest = rest.get(2..).filter(|_| rest.starts_with(|c: char| c.is_ascii_alphabetic()))?;
}
"HH" | "H" | "hh" | "h" => h = number(&mut rest, 2)? as u32,
"mm" | "m" => mi = number(&mut rest, 2)? as u32,
"ss" | "s" => sec = number(&mut rest, 2)? as u32,
"SSS" => ms = number(&mut rest, 3)? as u32,
_ => {
let lower = rest.get(..2)?.to_ascii_lowercase();
pm = Some(match lower.as_str() {
"am" => false,
"pm" => true,
_ => return None,
});
rest = &rest[2..];
}
}
i += tok.len();
}
if !rest.trim().is_empty() {
return None;
}
if let Some(pm) = pm {
h = h % 12 + if pm { 12 } else { 0 };
}
at(y, mo, d, h, mi, sec, ms)
}
/// A length of time: fixed milliseconds, or calendar months.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum Span {
Ms(f64),
Months(f64),
}
impl Span {
pub(crate) fn after(self, t: f64) -> f64 {
match self {
Span::Ms(ms) => t + ms,
Span::Months(n) => {
let whole = n.trunc();
add_months(t, whole as i64) + (n - whole) * 30.0 * DAY
}
}
}
}
/// `3d`, `1.5h`, `2w`, `30m`, `250ms`, `1M` (a month), `1y`.
pub(crate) fn span(s: &str) -> Option<Span> {
let s = s.trim();
let n = s.bytes().take_while(|b| b.is_ascii_digit() || *b == b'.').count();
let v: f64 = s.get(..n).filter(|v| !v.is_empty())?.parse().ok()?;
if !v.is_finite() || v > 1e6 {
return None;
}
Some(match s[n..].trim() {
"ms" => Span::Ms(v),
"s" => Span::Ms(v * SEC),
"m" => Span::Ms(v * MIN),
"h" => Span::Ms(v * HOUR),
"d" => Span::Ms(v * DAY),
"w" => Span::Ms(v * 7.0 * DAY),
"M" => Span::Months(v),
"y" => Span::Months(v * 12.0),
_ => return None,
})
}
/// `t` printed with a d3 time format: `%Y %y %m %d %e %H %I %M %S %L %p %b %B %a %A %j %%`, with
/// `-`, `_` or `0` after `%` for no, space or zero padding.
pub(crate) fn format(t: f64, fmt: &str) -> String {
let f = fields(t);
let mut out = String::new();
let mut chars = fmt.chars();
while let Some(c) = chars.next() {
if c != '%' {
out.push(c);
continue;
}
let mut code = chars.next().unwrap_or('%');
let pad = match code {
'-' | '_' | '0' => {
let p = code;
code = chars.next().unwrap_or('%');
Some(p)
}
_ => None,
};
let num = |out: &mut String, v: i64, width: usize, default: char| match pad.unwrap_or(default) {
'-' => out.push_str(&v.to_string()),
'_' => out.push_str(&format!("{v:>width$}")),
_ => out.push_str(&format!("{v:0width$}")),
};
let doy = days_from_civil(f.y, f.mo, f.d) - days_from_civil(f.y, 1, 1) + 1;
match code {
'Y' => num(&mut out, f.y, 4, '0'),
'y' => num(&mut out, f.y.rem_euclid(100), 2, '0'),
'm' => num(&mut out, f.mo as i64, 2, '0'),
'd' => num(&mut out, f.d as i64, 2, '0'),
'e' => num(&mut out, f.d as i64, 2, '_'),
'H' => num(&mut out, f.h as i64, 2, '0'),
'I' => num(&mut out, ((f.h + 11) % 12 + 1) as i64, 2, '0'),
'M' => num(&mut out, f.mi as i64, 2, '0'),
'S' => num(&mut out, f.s as i64, 2, '0'),
'L' => num(&mut out, f.ms as i64, 3, '0'),
'j' => num(&mut out, doy, 3, '0'),
'p' => out.push_str(if f.h < 12 { "AM" } else { "PM" }),
'b' => out.push_str(&MONTHS[f.mo as usize - 1][..3]),
'B' => out.push_str(MONTHS[f.mo as usize - 1]),
'a' => out.push_str(&DAYS[f.wd as usize][..3]),
'A' => out.push_str(DAYS[f.wd as usize]),
other => out.push(other),
}
}
out
}
/// A step between axis ticks, aligned to the calendar.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum Step {
Ms(f64),
Days(u32),
Weeks(u32),
Months(u32),
}
impl Step {
/// The step's rough length, for spacing ticks.
pub(crate) fn len(self) -> f64 {
match self {
Step::Ms(ms) => ms,
Step::Days(n) => n as f64 * DAY,
Step::Weeks(n) => n as f64 * 7.0 * DAY,
Step::Months(n) => n as f64 * 30.44 * DAY,
}
}
/// `1day`, `2week`, `6hour`, `1month` (Mermaid's `tickInterval`).
pub(crate) fn parse(s: &str) -> Option<Self> {
let s = s.trim();
let n = s.bytes().take_while(u8::is_ascii_digit).count();
let v: u32 = s[..n].parse().ok().filter(|v| (1..=1000).contains(v))?;
Some(match s[n..].trim() {
"millisecond" => Step::Ms(v as f64),
"second" => Step::Ms(v as f64 * SEC),
"minute" => Step::Ms(v as f64 * MIN),
"hour" => Step::Ms(v as f64 * HOUR),
"day" => Step::Days(v),
"week" => Step::Weeks(v),
"month" => Step::Months(v),
_ => return None,
})
}
/// The steps an axis picks from, finest first.
pub(crate) const LADDER: [Step; 21] = [
Step::Ms(SEC),
Step::Ms(5.0 * SEC),
Step::Ms(15.0 * SEC),
Step::Ms(30.0 * SEC),
Step::Ms(MIN),
Step::Ms(5.0 * MIN),
Step::Ms(15.0 * MIN),
Step::Ms(30.0 * MIN),
Step::Ms(HOUR),
Step::Ms(3.0 * HOUR),
Step::Ms(6.0 * HOUR),
Step::Ms(12.0 * HOUR),
Step::Days(1),
Step::Days(2),
Step::Weeks(1),
Step::Weeks(2),
Step::Months(1),
Step::Months(3),
Step::Months(6),
Step::Months(12),
Step::Months(60),
];
/// Ticks from `lo` to `hi` inclusive, at most `max` of them: midnights for days, Sundays for
/// weeks, the first of the month for months.
pub(crate) fn ticks(self, lo: f64, hi: f64, max: usize) -> Vec<f64> {
let mut t = match self {
Step::Ms(ms) => (lo / ms).ceil() * ms,
Step::Days(n) => {
let mut day = (lo / DAY).ceil() as i64;
while (civil_from_days(day).2 - 1) % n != 0 {
day += 1;
}
day as f64 * DAY
}
Step::Weeks(_) => {
let day = (lo / DAY).ceil() as i64;
(day + (7 - (day + 4).rem_euclid(7)) % 7) as f64 * DAY
}
Step::Months(n) => {
let f = fields(lo);
let mut m0 = f.y * 12 + f.mo as i64 - 1;
if at(f.y, f.mo, 1, 0, 0, 0, 0).is_some_and(|first| first < lo) {
m0 += 1;
}
while m0.rem_euclid(n as i64) != 0 {
m0 += 1;
}
at(m0.div_euclid(12), m0.rem_euclid(12) as u32 + 1, 1, 0, 0, 0, 0).unwrap_or(lo)
}
};
let mut out = Vec::new();
while t <= hi + 1e-6 && out.len() < max {
out.push(t);
t = match self {
Step::Ms(ms) => t + ms,
Step::Weeks(n) => t + n as f64 * 7.0 * DAY,
Step::Days(n) => {
// Back to the 1st at month ends, as d3 does.
let next = t + n as f64 * DAY;
let (f, g) = (fields(t), fields(next));
if g.mo != f.mo && g.d > 1 { at(g.y, g.mo, 1, 0, 0, 0, 0).unwrap_or(next) } else { next }
}
Step::Months(n) => add_months(t, n as i64),
};
}
out
}
}
#[cfg(test)]
#[path = "date_tests.rs"]
mod tests;
@@ -0,0 +1,60 @@
use super::*;
#[test]
fn civil_days_round_trip() {
assert_eq!(days_from_civil(1970, 1, 1), 0);
assert_eq!(days_from_civil(2000, 3, 1), 11_017);
for z in [-800_000, -1, 0, 59, 11_016, 19_723, 2_000_000] {
let (y, m, d) = civil_from_days(z);
assert_eq!(days_from_civil(y, m, d), z);
}
assert_eq!(fields(days_from_civil(2024, 1, 7) as f64 * DAY).wd, 0, "2024-01-07 was a Sunday");
}
#[test]
fn reads_dayjs_formats_and_iso() {
let jan5 = days_from_civil(2024, 1, 5) as f64 * DAY;
assert_eq!(parse("2024-01-05", "YYYY-MM-DD"), Some(jan5));
assert_eq!(parse("05/01/2024", "DD/MM/YYYY"), Some(jan5));
assert_eq!(parse("2024-01-05 13:30", "YYYY-MM-DD HH:mm"), Some(jan5 + 13.5 * HOUR));
assert_eq!(parse("Jan 5 2024 1:30 pm", "MMM D YYYY h:mm a"), Some(jan5 + 13.5 * HOUR));
assert_eq!(parse("2024-01-05", "DD.MM.YY"), Some(jan5), "falls back to ISO");
assert_eq!(parse("1704412800", "X"), Some(jan5));
assert_eq!(parse("2024-02-30", "YYYY-MM-DD"), None);
assert_eq!(parse("soon", "YYYY-MM-DD"), None);
assert_eq!(parse("99999999999999999999", "X"), None);
}
#[test]
fn spans_and_months() {
let jan31 = days_from_civil(2024, 1, 31) as f64 * DAY;
assert_eq!(span("3d"), Some(Span::Ms(3.0 * DAY)));
assert_eq!(span("1.5h"), Some(Span::Ms(1.5 * HOUR)));
assert_eq!(span("2w"), Some(Span::Ms(14.0 * DAY)));
assert_eq!(span("3x"), None);
assert_eq!(Span::Months(1.0).after(jan31), days_from_civil(2024, 2, 29) as f64 * DAY);
}
#[test]
fn prints_d3_formats() {
let t = days_from_civil(2024, 3, 7) as f64 * DAY + 15.0 * HOUR + 4.0 * MIN;
assert_eq!(format(t, "%Y-%m-%d"), "2024-03-07");
assert_eq!(format(t, "%b %-d"), "Mar 7");
assert_eq!(format(t, "%a %e %I:%M %p"), "Thu 7 03:04 PM");
assert_eq!(format(t, "%B %j %%"), "March 067 %");
}
#[test]
fn ticks_land_on_the_calendar() {
let lo = days_from_civil(2024, 1, 3) as f64 * DAY + HOUR;
let hi = days_from_civil(2024, 4, 20) as f64 * DAY;
let day = |t: f64| civil_from_days((t / DAY) as i64);
let weeks = Step::Weeks(1).ticks(lo, hi, 100);
assert_eq!(day(weeks[0]), (2024, 1, 7));
assert!(weeks.iter().all(|&t| fields(t).wd == 0));
let months = Step::Months(1).ticks(lo, hi, 100);
assert_eq!(months.iter().map(|&t| day(t)).collect::<Vec<_>>(), [(2024, 2, 1), (2024, 3, 1), (2024, 4, 1)]);
assert_eq!(Step::Days(1).ticks(lo, hi, 5).len(), 5, "capped");
assert_eq!(Step::parse("2week"), Some(Step::Weeks(2)));
assert_eq!(Step::parse("6hour"), Some(Step::Ms(6.0 * HOUR)));
}
+364
View File
@@ -0,0 +1,364 @@
//! Gantt charts (`gantt`): sections of tasks as bars on a time axis, with `done`, `active`,
//! `crit`, `milestone` and `vert` tags, `after`/`until` links, durations and `excludes`.
use std::collections::{HashMap, HashSet};
use rune::{Align, TextStyle};
use super::date::{self, DAY, Span, Step};
use super::{axis_x, ink, soft, strong};
use crate::canvas::{Canvas, Measured, Scene, measure, measure_wrap, over_color, room, rounded_rect};
use crate::{DiagramStyle, MAX_ITEMS, clean, clean_quoted, oklab_mix, statements};
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(crate) struct Tags {
pub done: bool,
pub active: bool,
pub crit: bool,
pub milestone: bool,
/// A vertical marker across the chart rather than a bar.
pub vert: bool,
}
#[derive(Debug)]
pub(crate) struct Task {
pub name: String,
pub section: Option<usize>,
pub start: f64,
pub end: f64,
pub tags: Tags,
}
#[derive(Debug)]
pub(crate) struct Gantt {
pub title: Option<String>,
pub sections: Vec<String>,
pub tasks: Vec<Task>,
pub axis: String,
pub tick: Option<Step>,
/// Days left out of durations, drawn shaded.
pub excludes: Excludes,
}
#[derive(Debug, Default)]
pub(crate) struct Excludes {
/// By weekday, 0 Sunday.
pub weekdays: [bool; 7],
pub days: HashSet<i64>,
}
impl Excludes {
pub(crate) fn any(&self) -> bool {
self.weekdays.contains(&true) || !self.days.is_empty()
}
fn has(&self, day: i64) -> bool {
self.weekdays[(day + 4).rem_euclid(7) as usize] || self.days.contains(&day)
}
}
enum From {
Prev,
At(f64),
After(Vec<String>),
}
enum To {
At(f64),
Span(Span),
Until(Vec<String>),
}
struct Raw {
name: String,
section: Option<usize>,
tags: Tags,
id: Option<String>,
from: From,
to: To,
}
pub(crate) fn parse(header: &str, body: &[&str]) -> Option<Gantt> {
let mut g = Gantt { title: None, sections: Vec::new(), tasks: Vec::new(), axis: "%Y-%m-%d".into(), tick: None, excludes: Excludes::default() };
let mut format = "YYYY-MM-DD".to_owned();
let (mut raws, mut inclusive, mut weekend_friday, mut weekends) = (Vec::new(), false, false, false);
// `dateFormat` applies to every task, wherever it is set, so tasks are read after it.
let mut lines: Vec<&str> = Vec::new();
for line in std::iter::once(header).chain(body.iter().copied()) {
for stmt in statements(line) {
let (word, rest) = stmt.split_once(char::is_whitespace).map_or((stmt, ""), |(w, r)| (w, r.trim()));
match word {
"dateFormat" if !rest.is_empty() => format = rest.to_owned(),
"axisFormat" if !rest.is_empty() => g.axis = rest.to_owned(),
"tickInterval" => g.tick = Step::parse(rest).or(g.tick),
"inclusiveEndDates" => inclusive = true,
"weekend" => weekend_friday = rest.eq_ignore_ascii_case("friday"),
"title" => g.title = Some(clean_quoted(rest)).filter(|t| !t.is_empty()),
"excludes" => {
let mut dates = false;
for part in rest.split([',', ' ']).map(str::trim).filter(|p| !p.is_empty()) {
if part.eq_ignore_ascii_case("weekends") {
weekends = true;
} else if let Some(wd) = WEEKDAYS.iter().position(|d| part.eq_ignore_ascii_case(d)) {
g.excludes.weekdays[wd] = true;
} else {
dates = true;
}
}
// Dates read once `dateFormat` is known.
if dates {
lines.push(stmt);
}
}
"includes" | "todayMarker" | "topAxis" | "weekday" | "displayMode" | "click" | "accTitle" | "accDescr" => {}
_ => lines.push(stmt),
}
}
}
if weekends {
let (a, b) = if weekend_friday { (5, 6) } else { (6, 0) };
g.excludes.weekdays[a] = true;
g.excludes.weekdays[b] = true;
}
for stmt in lines {
if let Some(rest) = stmt.strip_prefix("excludes") {
for part in rest.split([',', ' ']).map(str::trim).filter(|p| !p.is_empty()) {
if let Some(t) = date::parse(part, &format) {
g.excludes.days.insert((t / DAY).floor() as i64);
}
}
continue;
}
if let Some(rest) = stmt.strip_prefix("section") {
if g.sections.len() + raws.len() >= MAX_ITEMS {
return None;
}
g.sections.push(clean(rest));
continue;
}
let Some((name, meta)) = stmt.split_once(':') else { continue };
let section = g.sections.len().checked_sub(1);
if let Some(r) = task(clean(name), section, meta, &format, inclusive) {
if g.sections.len() + raws.len() >= MAX_ITEMS {
return None;
}
raws.push(r);
}
}
g.tasks = resolve(&raws, &g.excludes);
(!g.tasks.is_empty()).then_some(g)
}
const WEEKDAYS: [&str; 7] = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];
/// `crit, active, id, after a b, 3d` and the shorter forms.
fn task(name: String, section: Option<usize>, meta: &str, format: &str, inclusive: bool) -> Option<Raw> {
let mut parts: Vec<&str> = meta.split(',').map(str::trim).collect();
let mut tags = Tags::default();
while let Some(first) = parts.first() {
match *first {
"done" => tags.done = true,
"active" => tags.active = true,
"crit" => tags.crit = true,
"milestone" => tags.milestone = true,
"vert" => tags.vert = true,
_ => break,
}
parts.remove(0);
}
let (id, from, to) = match parts.as_slice() {
[to] => (None, From::Prev, *to),
[from, to] => (None, from_spec(from, format)?, *to),
[id, from, to] => (Some((*id).to_owned()).filter(|i| !i.is_empty()), from_spec(from, format)?, *to),
_ => return None,
};
let to = if let Some(ids) = to.strip_prefix("until ") {
To::Until(ids.split_whitespace().map(str::to_owned).collect())
} else if let Some(s) = date::span(to) {
To::Span(s)
} else {
// `inclusiveEndDates` makes an end date the last day of the task, not the day after.
To::At(date::parse(to, format)? + if inclusive { DAY } else { 0.0 })
};
Some(Raw { name, section, tags, id, from, to })
}
fn from_spec(s: &str, format: &str) -> Option<From> {
match s.strip_prefix("after ") {
Some(ids) => Some(From::After(ids.split_whitespace().map(str::to_owned).collect())),
None => date::parse(s, format).map(From::At),
}
}
/// Starts and ends for every task that has them, following links in any order; a task left
/// without one (a link to nothing, a loop) is dropped.
fn resolve(raws: &[Raw], excludes: &Excludes) -> Vec<Task> {
let ids: HashMap<&str, usize> = raws.iter().enumerate().filter_map(|(i, r)| Some((r.id.as_deref()?, i))).collect();
let mut times: Vec<Option<(f64, f64)>> = vec![None; raws.len()];
for _ in 0..=raws.len() {
let mut changed = false;
for (i, r) in raws.iter().enumerate() {
if times[i].is_some() {
continue;
}
let linked = |names: &[String], pick: fn(&(f64, f64)) -> f64, best: fn(f64, f64) -> f64| -> Option<f64> {
let known: Vec<usize> = names.iter().filter_map(|n| ids.get(n.as_str()).copied()).collect();
let got: Vec<f64> = known.iter().filter_map(|&k| times[k].as_ref().map(pick)).collect();
(!known.is_empty() && got.len() == known.len()).then(|| got.into_iter().reduce(best)).flatten()
};
let start = match &r.from {
From::At(t) => Some(*t),
From::Prev => i.checked_sub(1).and_then(|p| times[p]).map(|t| t.1),
From::After(names) => linked(names, |t| t.1, f64::max),
};
let Some(start) = start else { continue };
let end = match &r.to {
To::At(t) => Some(*t),
To::Span(s) => Some(skip_excluded(start, s.after(start), excludes)),
To::Until(names) => linked(names, |t| t.0, f64::min),
};
if let Some(end) = end {
times[i] = Some((start, end.max(start)));
changed = true;
}
}
if !changed {
break;
}
}
raws.iter()
.zip(times)
.filter_map(|(r, t)| t.map(|(start, end)| Task { name: r.name.clone(), section: r.section, start, end, tags: r.tags }))
.collect()
}
/// `end` pushed back a day for each excluded day from `start` up to it.
fn skip_excluded(start: f64, mut end: f64, excludes: &Excludes) -> f64 {
if !excludes.any() {
return end;
}
let mut day = (start / DAY).floor() as i64;
for _ in 0..3660 {
if day as f64 * DAY >= end {
break;
}
if excludes.has(day) {
end += DAY;
}
day += 1;
}
end
}
/// Section hues: the series palette without its reds, which mean `crit`.
const SECTION_HUES: [f32; 8] = [255.0, 150.0, 70.0, 305.0, 195.0, 110.0, 280.0, 225.0];
const CRIT: f32 = 25.0;
fn section_hue(s: usize) -> f32 {
SECTION_HUES[s % SECTION_HUES.len()]
}
const BAR: f32 = 22.0;
const PITCH: f32 = 28.0;
pub(crate) fn draw(g: &Gantt, paint: &DiagramStyle) -> Option<Scene> {
let small = TextStyle { size: paint.font.size - 1.0, line_height: paint.font.line_height - 2.0, ..paint.font };
let bold = TextStyle { weight: 600.0, ..small };
let w = room(paint);
let rows: Vec<&Task> = g.tasks.iter().filter(|t| !t.tags.vert).collect();
let marks: Vec<&Task> = g.tasks.iter().filter(|t| t.tags.vert).collect();
let used: Vec<usize> = {
let mut v: Vec<usize> = rows.iter().filter_map(|t| t.section).collect();
v.dedup();
v
};
let side = (w * 0.28).floor();
let titles: Vec<Measured> = g.sections.iter().map(|s| measure_wrap(s, bold, side - 16.0)).collect();
let left = used.iter().map(|&s| titles[s].size[0] + 16.0).fold(0.0, f32::max).min(side);
let (x0, x1) = (left + 4.0, w - 4.0);
let lo = g.tasks.iter().map(|t| t.start).fold(f64::MAX, f64::min);
let mut hi = g.tasks.iter().map(|t| t.end).fold(f64::MIN, f64::max);
if hi - lo < 1.0 {
hi = lo + DAY;
}
let sx = |t: f64| x0 + ((t - lo) / (hi - lo)) as f32 * (x1 - x0);
let mark_labels: Vec<Measured> = marks.iter().map(|t| measure(&t.name, small)).collect();
let top = mark_labels.iter().map(|m| m.size[1] + 6.0).fold(0.0, f32::max);
let bottom = top + rows.len() as f32 * PITCH + 4.0;
let mut c = Canvas::default();
// Section bands, then shaded excluded days, then the grid, then bars.
let mut r0 = 0;
while r0 < rows.len() {
let sec = rows[r0].section;
let r1 = rows[r0..].iter().position(|t| t.section != sec).map_or(rows.len(), |n| r0 + n);
let (y0, y1) = (top + r0 as f32 * PITCH, top + r1 as f32 * PITCH + if r1 == rows.len() { 4.0 } else { 0.0 });
if let Some(s) = sec {
c.fill(vec![[0.0, y0], [x1, y0], [x1, y1], [0.0, y1]], strong(paint, section_hue(s)).alpha(0.07));
c.label(&titles[s], [left / 2.0, (y0 + y1) / 2.0], bold, paint.text, Align::Center);
}
r0 = r1;
}
let (d0, d1) = ((lo / DAY).floor() as i64, (hi / DAY).ceil() as i64);
if g.excludes.any() && d1 - d0 <= 400 {
for day in (d0..d1).filter(|&d| g.excludes.has(d)) {
let (a, b) = (sx(day as f64 * DAY).max(x0), sx((day + 1) as f64 * DAY).min(x1));
c.fill(vec![[a, top], [b, top], [b, bottom], [a, bottom]], paint.text.alpha(0.05));
}
}
let probe = measure(&date::format(lo, &g.axis), small).size[0] + 16.0;
let step = g.tick.unwrap_or_else(|| {
let px = |s: Step| s.len() / (hi - lo) * (x1 - x0) as f64;
Step::LADDER.into_iter().find(|&s| px(s) >= probe as f64 && (hi - lo) / s.len() <= 40.0).unwrap_or(Step::Months(60))
});
let ticks: Vec<(f32, Measured)> = step.ticks(lo, hi, 200).into_iter().map(|t| (sx(t), measure(&date::format(t, &g.axis), small))).collect();
axis_x(&mut c, &ticks, [x0, x1], [top, bottom], small, paint);
// Markers under the bars, so a bar's text stays whole.
for (t, m) in marks.iter().zip(&mark_labels) {
let x = sx(t.start);
let color = if t.tags.crit { strong(paint, CRIT) } else { paint.muted };
c.dashed(&[[x, top - 2.0], [x, bottom]], 1.25, color, 4.0, 3.0);
c.label_at(m, [(x - m.size[0] / 2.0).clamp(0.0, (x1 - m.size[0]).max(0.0)), 0.0], small, color, Align::Start);
}
for (r, t) in rows.iter().enumerate() {
let y = top + r as f32 * PITCH + (PITCH - BAR) / 2.0 + 2.0;
let h = if t.tags.crit { CRIT } else { section_hue(t.section.unwrap_or(0)) };
let (mut fill, mut border, mut width) = (soft(paint, h), strong(paint, h), 1.0);
if t.tags.active {
fill = oklab_mix(fill, paint.surface, 0.55);
width = 1.5;
}
if t.tags.done {
fill = over_color(paint.text.alpha(0.12), paint.surface);
if !t.tags.crit {
border = paint.node_border;
}
}
let m = measure(&t.name, small);
let (a, b) = (sx(t.start), sx(t.end).max(sx(t.start) + 2.0));
let mid = y + BAR / 2.0;
if t.tags.milestone {
let r = BAR / 2.0;
c.shape(vec![[a, mid - r], [a + r, mid], [a, mid + r], [a - r, mid]], fill, border, width);
let x = if a + r + 6.0 + m.size[0] <= x1 { a + r + 6.0 } else { (a - r - 6.0 - m.size[0]).max(0.0) };
c.label_at(&m, [x, mid - m.size[1] / 2.0], small, paint.text, Align::Start);
continue;
}
c.shape(rounded_rect(a, y, b, y + BAR, 3.0), fill, border, width);
let at = if m.size[0] + 12.0 <= b - a {
((a + b - m.size[0]) / 2.0, ink(fill))
} else if b + 6.0 + m.size[0] <= x1 {
(b + 6.0, paint.text)
} else {
((a - 6.0 - m.size[0]).max(0.0), paint.text)
};
c.label_at(&m, [at.0, mid - m.size[1] / 2.0], small, at.1, Align::Start);
}
c.finish_fit(paint)
}
#[cfg(test)]
#[path = "gantt_tests.rs"]
mod tests;
@@ -0,0 +1,91 @@
use super::*;
use super::super::date::days_from_civil;
fn gantt(src: &str) -> Gantt {
match crate::parse(src).map(|p| p.diagram) {
Some(crate::Diagram::Gantt(g)) => g,
_ => panic!("not a gantt chart: {src:?}"),
}
}
fn day(y: i64, m: u32, d: u32) -> f64 {
days_from_civil(y, m, d) as f64 * DAY
}
fn span_of<'a>(g: &'a Gantt, name: &str) -> (f64, f64, &'a Task) {
let t = g.tasks.iter().find(|t| t.name == name).unwrap_or_else(|| panic!("no task {name}"));
(t.start, t.end, t)
}
#[test]
fn tasks_links_tags_and_sections() {
let g = gantt(
"gantt\n\
title Release\n\
dateFormat YYYY-MM-DD\n\
axisFormat %b %d\n\
section Build\n\
Design :done, des, 2024-01-01, 2024-01-05\n\
Code :active, code, after des, 5d\n\
Test :crit, 3d\n\
section Ship\n\
Review :rev, after code test2, 2d\n\
Launch :milestone, after des, until rev\n\
Freeze :vert, 2024-01-08, 0d",
);
assert_eq!(g.title.as_deref(), Some("Release"));
assert_eq!(g.sections, ["Build", "Ship"]);
assert_eq!(g.axis, "%b %d");
let (s, e, t) = span_of(&g, "Design");
assert_eq!((s, e, t.tags.done, t.section), (day(2024, 1, 1), day(2024, 1, 5), true, Some(0)));
let (s, e, t) = span_of(&g, "Code");
assert_eq!((s, e, t.tags.active), (day(2024, 1, 5), day(2024, 1, 10), true));
let (s, e, t) = span_of(&g, "Test");
assert_eq!((s, e, t.tags.crit), (day(2024, 1, 10), day(2024, 1, 13), true), "follows the task before it");
// `test2` names nothing, so `after` reads only `code`.
assert_eq!(span_of(&g, "Review").0, day(2024, 1, 10));
assert_eq!(span_of(&g, "Review").2.section, Some(1));
let (s, e, t) = span_of(&g, "Launch");
assert_eq!((s, e, t.tags.milestone), (day(2024, 1, 5), day(2024, 1, 10), true));
assert!(span_of(&g, "Freeze").2.tags.vert);
}
#[test]
fn forward_links_resolve_and_loops_drop() {
let g = gantt("gantt\nB :b, after a, 1d\nA :a, 2024-03-01, 2d\nC :c, after d, 1d\nD :d, after c, 1d");
assert_eq!(span_of(&g, "B").0, day(2024, 3, 3));
assert_eq!(g.tasks.len(), 2, "c and d wait on each other");
}
#[test]
fn excludes_push_durations_past_weekends_and_dates() {
// 2024-01-05 is a Friday.
let g = gantt("gantt\nexcludes weekends, 2024-01-09\nA :2024-01-05, 3d\nB :2024-01-05, 2024-01-08");
assert_eq!(span_of(&g, "A").1, day(2024, 1, 11), "Fri, (Sat, Sun skipped), Mon, (Tue skipped), Wed");
assert_eq!(span_of(&g, "B").1, day(2024, 1, 8), "a fixed end stays put");
assert!(g.excludes.weekdays[0] && g.excludes.weekdays[6]);
let g = gantt("gantt\nweekend friday\nexcludes weekends\nA :2024-01-04, 2d");
assert_eq!(span_of(&g, "A").1, day(2024, 1, 8), "Thu, (Fri, Sat skipped), Sun");
}
#[test]
fn formats_inclusive_ends_and_bad_lines() {
let g = gantt("gantt\ndateFormat DD/MM/YYYY\ninclusiveEndDates\nnot a task\nA :01/02/2024, 03/02/2024\nB :what, ever\nC :after nobody, 1d");
assert_eq!(g.tasks.len(), 1);
assert_eq!(span_of(&g, "A").1, day(2024, 2, 4), "the end date is the task's last day");
assert!(crate::parse("gantt\ntitle Nothing\nsection Empty").is_none());
}
#[test]
fn draws_bars_labels_and_an_axis() {
let paint = DiagramStyle::neutral(true);
let s = crate::scene("gantt\ntitle Plan\nsection Work\nShort :2024-01-01, 1d\nA much longer task name :2024-01-02, 20d", &paint, None).unwrap();
assert_eq!(s.title.as_deref(), Some("Plan"));
let texts: Vec<&str> = s.labels.iter().map(|l| l.text.as_str()).collect();
assert!(texts.contains(&"Work") && texts.contains(&"Short") && texts.contains(&"A much longer task name"), "{texts:?}");
assert!(texts.iter().any(|t| t.starts_with("2024-01-")), "axis ticks: {texts:?}");
let late = crate::scene("gantt\nA :a, 2024-01-01, 20d\nA long milestone name at the very end :milestone, after a, 0d", &paint, None).unwrap();
assert!(late.size[0] <= crate::canvas::room(&paint) + 2.01, "a milestone at the end keeps its label inside: {}", late.size[0]);
let budget = format!("gantt\n{}", (0..=MAX_ITEMS).map(|i| format!("T{i} :2024-01-01, 1d")).collect::<Vec<_>>().join("\n"));
assert!(crate::parse(&budget).is_none());
}
+354
View File
@@ -0,0 +1,354 @@
//! Git graphs (`gitGraph`, `LR:`, `TB:` or `BT:`): `commit` (`id`, `tag`, `type: NORMAL |
//! REVERSE | HIGHLIGHT`), `branch` (`order`), `checkout`/`switch`, `merge` and `cherry-pick`,
//! one lane per branch in its own colour. Commits without an `id` are drawn unlabelled, since
//! Mermaid would label them with random hashes.
use rune::{Align, Color};
use super::{bold, hue, ink, small, solid};
use crate::canvas::{Canvas, Measured, Scene, dist, ellipse, lerp, measure, rounded_rect, unit};
use crate::{DiagramStyle, MAX_ITEMS, clean, oklab_mix, statements};
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum Kind {
Normal,
Reverse,
Highlight,
Merge,
CherryPick,
}
#[derive(Debug)]
pub(crate) struct Commit {
pub id: Option<String>,
pub tag: Option<String>,
pub kind: Kind,
pub branch: usize,
pub parents: Vec<usize>,
/// The commit a cherry-pick copies.
pub picked: Option<usize>,
}
#[derive(Debug)]
pub(crate) struct Branch {
pub name: String,
pub order: Option<f32>,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum Flow {
Right,
Down,
Up,
}
#[derive(Debug)]
pub(crate) struct GitGraph {
pub flow: Flow,
pub branches: Vec<Branch>,
pub commits: Vec<Commit>,
}
pub(crate) fn parse(header: &str, body: &[&str]) -> Option<GitGraph> {
let flow = match header.trim().trim_end_matches(':') {
"TB" | "TD" => Flow::Down,
"BT" => Flow::Up,
_ => Flow::Right,
};
let mut g = GitGraph { flow, branches: vec![Branch { name: "main".into(), order: None }], commits: Vec::new() };
let mut heads: Vec<Option<usize>> = vec![None];
let mut cur = 0;
for &line in body {
for stmt in statements(line) {
let (cmd, rest) = stmt.split_once(char::is_whitespace).unwrap_or((stmt, ""));
let rest = rest.trim();
if g.commits.len() + g.branches.len() > MAX_ITEMS {
return None;
}
let find = |g: &GitGraph, name: &str| g.branches.iter().position(|b| b.name == name);
match cmd {
"commit" => {
let a = attrs(rest);
let kind = kind(&a).unwrap_or(Kind::Normal);
g.commits.push(Commit { id: get(&a, "id"), tag: get(&a, "tag"), kind, branch: cur, parents: heads[cur].into_iter().collect(), picked: None });
heads[cur] = Some(g.commits.len() - 1);
}
"branch" => {
let (name, rest) = name(rest);
if name.is_empty() || find(&g, &name).is_some() {
continue;
}
let order = get(&attrs(rest), "order").and_then(|o| o.parse::<f32>().ok()).filter(|o| o.is_finite());
g.branches.push(Branch { name, order });
heads.push(heads[cur]);
cur = g.branches.len() - 1;
}
"checkout" | "switch" => {
if let Some(b) = find(&g, &name(rest).0) {
cur = b;
}
}
"merge" => {
let (name, rest) = name(rest);
let Some(b) = find(&g, &name).filter(|&b| b != cur) else { continue };
let (Some(theirs), ours) = (heads[b], heads[cur]) else { continue };
// Nothing to merge when ours already has theirs.
if ours.is_some_and(|o| reaches(&g.commits, o, theirs)) {
continue;
}
let a = attrs(rest);
let parents = ours.into_iter().chain([theirs]).collect();
g.commits.push(Commit { id: get(&a, "id"), tag: get(&a, "tag"), kind: kind(&a).unwrap_or(Kind::Merge), branch: cur, parents, picked: None });
heads[cur] = Some(g.commits.len() - 1);
}
"cherry-pick" => {
let a = attrs(rest);
let Some(src) = get(&a, "id").and_then(|id| g.commits.iter().position(|c| c.id.as_deref() == Some(id.as_str()))) else { continue };
if g.commits[src].branch == cur {
continue;
}
g.commits.push(Commit { id: None, tag: get(&a, "tag"), kind: Kind::CherryPick, branch: cur, parents: heads[cur].into_iter().collect(), picked: Some(src) });
heads[cur] = Some(g.commits.len() - 1);
}
_ => {}
}
}
}
(!g.commits.is_empty()).then_some(g)
}
/// Whether `to` is `from` or one of its ancestors.
fn reaches(commits: &[Commit], from: usize, to: usize) -> bool {
let mut seen = vec![false; commits.len()];
let mut stack = vec![from];
while let Some(c) = stack.pop() {
if c == to {
return true;
}
if !std::mem::replace(&mut seen[c], true) {
stack.extend(&commits[c].parents);
}
}
false
}
/// A branch name, quoted or bare, and what follows it.
fn name(s: &str) -> (String, &str) {
let s = s.trim();
if let Some(r) = s.strip_prefix('"')
&& let Some(end) = r.find('"')
{
return (clean(&r[..end]), &r[end + 1..]);
}
let end = s.find(char::is_whitespace).unwrap_or(s.len());
(clean(&s[..end]), &s[end..])
}
/// `key: value` pairs, values quoted or bare.
fn attrs(s: &str) -> Vec<(String, String)> {
let mut out = Vec::new();
let mut rest = s.trim();
while let Some(colon) = rest.find(':') {
let key = rest[..colon].trim().rsplit(char::is_whitespace).next().unwrap_or("").to_owned();
let after = rest[colon + 1..].trim_start();
let (value, next) = match after.strip_prefix('"') {
Some(r) => match r.find('"') {
Some(end) => (&r[..end], &r[end + 1..]),
None => (r, ""),
},
None => {
let end = after.find(char::is_whitespace).unwrap_or(after.len());
(&after[..end], &after[end..])
}
};
out.push((key, clean(value)));
rest = next.trim_start();
}
out
}
fn get(a: &[(String, String)], key: &str) -> Option<String> {
a.iter().find(|(k, _)| k == key).map(|(_, v)| v.clone()).filter(|v| !v.is_empty())
}
fn kind(a: &[(String, String)]) -> Option<Kind> {
match get(a, "type")?.as_str() {
"REVERSE" => Some(Kind::Reverse),
"HIGHLIGHT" => Some(Kind::Highlight),
"NORMAL" => Some(Kind::Normal),
_ => None,
}
}
const R: f32 = 9.0;
const STEP: f32 = 44.0;
const PAD: [f32; 2] = [6.0, 2.0];
pub(crate) fn draw(g: &GitGraph, paint: &DiagramStyle) -> Option<Scene> {
let note = small(paint);
let head = bold(note);
// Lanes in `order`, then creation order.
let mut lanes: Vec<usize> = (0..g.branches.len()).collect();
lanes.sort_by(|&a, &b| {
let key = |i: usize| g.branches[i].order.unwrap_or(if i == 0 { f32::MIN } else { i as f32 });
key(a).total_cmp(&key(b)).then(a.cmp(&b))
});
let mut lane_of = vec![0; g.branches.len()];
for (pos, &b) in lanes.iter().enumerate() {
lane_of[b] = pos;
}
let labels: Vec<Measured> = g.commits.iter().map(|c| c.id.as_deref().map_or_else(Measured::default, |t| measure(t, note))).collect();
let tags: Vec<Measured> = g.commits.iter().map(|c| c.tag.as_deref().map_or_else(Measured::default, |t| measure(t, note))).collect();
let names: Vec<Measured> = g.branches.iter().map(|b| measure(&b.name, head)).collect();
let boxed = |m: &Measured| if m.text.is_empty() { 0.0 } else { m.size[0] + 2.0 * PAD[0] };
let line_h = note.line_height + 2.0 * PAD[1];
let across = g.flow == Flow::Right;
// Along the flow: each commit after the last, and clear of the label before it on its lane.
let mut along = vec![0.0f32; g.commits.len()];
let mut last_on: Vec<Option<usize>> = vec![None; g.branches.len()];
for (k, c) in g.commits.iter().enumerate() {
let mut u = if k == 0 { 0.0 } else { along[k - 1] + STEP };
if across && let Some(p) = last_on[c.branch] {
let w = |i: usize| boxed(&labels[i]).max(boxed(&tags[i]));
u = u.max(along[p] + (w(p) + w(k)) / 2.0 + 10.0);
}
along[k] = u;
last_on[c.branch] = Some(k);
}
let has_tags = tags.iter().any(|t| !t.text.is_empty());
// Across, each lane is as tall as its labels and tags; down, as wide as the widest.
let mut lane_v = vec![0.0f32; lanes.len()];
if across {
let mut v = 0.0;
for (pos, &b) in lanes.iter().enumerate() {
let tagged = g.commits.iter().zip(&tags).any(|(c, t)| c.branch == b && !t.text.is_empty());
if tagged {
v += line_h + 10.0;
}
lane_v[pos] = v;
v += 2.0 * R + 22.0 + line_h;
}
} else {
let wide = |ms: &[Measured]| ms.iter().map(|m| boxed(m)).fold(0.0, f32::max);
let tag_w = wide(&tags);
let lane = (2.0 * R + 28.0 + wide(&labels) + tag_w + if has_tags { 10.0 } else { 0.0 }).max(names.iter().map(|m| m.size[0] + 24.0).fold(0.0, f32::max));
for (pos, v) in lane_v.iter_mut().enumerate() {
*v = tag_w + pos as f32 * lane;
}
}
let pt = |u: f32, v: usize| {
let v = lane_v[v];
match g.flow {
Flow::Right => [u, v],
Flow::Down => [v, u],
Flow::Up => [v, -u],
}
};
let end = along.last().copied().unwrap_or(0.0) + 2.0 * R;
let color = |b: usize| solid(paint, hue(b));
let mut c = Canvas::default();
// Lanes, with their names before them.
for (b, m) in names.iter().enumerate() {
let v = lane_of[b];
let w = m.size[0] + 16.0;
let h = m.size[1] + 8.0;
let (start, at) = match g.flow {
Flow::Right => (pt(-2.0 * R, v), [pt(0.0, v)[0] - 2.0 * R - 10.0 - w, pt(0.0, v)[1] - h / 2.0]),
Flow::Down => (pt(-2.0 * R, v), [pt(0.0, v)[0] - w / 2.0, -2.0 * R - 10.0 - h]),
Flow::Up => (pt(-2.0 * R, v), [pt(0.0, v)[0] - w / 2.0, 2.0 * R + 10.0]),
};
c.dashed(&[start, pt(end, v)], 1.0, color(b).alpha(0.45), 5.0, 4.0);
c.fill(rounded_rect(at[0], at[1], at[0] + w, at[1] + h, h / 2.0), color(b));
c.label_at(m, [at[0] + 8.0, at[1] + 4.0], head, ink(color(b)), Align::Start);
}
// Links: an elbow toward the lower lane, in that lane's colour.
for (k, commit) in g.commits.iter().enumerate() {
for &p in &commit.parents {
let parent = &g.commits[p];
let (vp, vk) = (lane_of[parent.branch], lane_of[commit.branch]);
let (a, b) = (pt(along[p], vp), pt(along[k], vk));
let pts = if vp == vk {
vec![a, b]
} else if vp < vk {
elbow(a, pt(along[p], vk), b)
} else {
elbow(a, pt(along[k], vp), b)
};
let lane_color = color(if vp < vk { commit.branch } else { parent.branch });
c.stroke(pts, false, 2.0, lane_color);
}
if let Some(src) = commit.picked {
let (a, b) = (pt(along[src], lane_of[g.commits[src].branch]), pt(along[k], lane_of[commit.branch]));
c.dashed(&elbow(a, pt(along[k], lane_of[g.commits[src].branch]), b), 1.5, color(commit.branch), 4.0, 3.0);
}
}
for (k, commit) in g.commits.iter().enumerate() {
let at = pt(along[k], lane_of[commit.branch]);
glyph(&mut c, commit.kind, at, color(commit.branch), paint);
let label = &labels[k];
if !label.text.is_empty() {
let w = boxed(label);
let o = if across { [at[0] - w / 2.0, at[1] + R + 6.0] } else { [at[0] + R + 8.0, at[1] - line_h / 2.0] };
c.fill(rounded_rect(o[0], o[1], o[0] + w, o[1] + line_h, 4.0), oklab_mix(paint.surface, paint.text, 0.08));
c.label_at(label, [o[0] + PAD[0], o[1] + PAD[1]], note, paint.muted, Align::Start);
}
let tag = &tags[k];
if !tag.text.is_empty() {
let w = boxed(tag);
let o = if across { [at[0] - w / 2.0, at[1] - R - 8.0 - line_h] } else { [at[0] - R - 8.0 - w, at[1] - line_h / 2.0] };
c.shape(rounded_rect(o[0], o[1], o[0] + w, o[1] + line_h, 3.0), paint.note_fill, paint.note_border, 1.0);
c.label_at(tag, [o[0] + PAD[0], o[1] + PAD[1]], note, paint.text, Align::Start);
}
}
c.finish_fit(paint)
}
/// `a` to `b` through corner `k`, rounded.
fn elbow(a: [f32; 2], k: [f32; 2], b: [f32; 2]) -> Vec<[f32; 2]> {
let r = 10.0f32.min(dist(a, k) / 2.0).min(dist(k, b) / 2.0);
if r < 0.5 {
return vec![a, b];
}
let (ua, ub) = (unit(k, a), unit(k, b));
let p = [k[0] + ua[0] * r, k[1] + ua[1] * r];
let q = [k[0] + ub[0] * r, k[1] + ub[1] * r];
let mut pts = vec![a];
pts.extend((0..=6).map(|i| {
let t = i as f32 / 6.0;
lerp(lerp(p, k, t), lerp(k, q, t), t)
}));
pts.push(b);
pts
}
fn glyph(c: &mut Canvas, kind: Kind, at: [f32; 2], fill: Color, paint: &DiagramStyle) {
let [x, y] = at;
match kind {
Kind::Highlight => {
c.shape(rounded_rect(x - R, y - R, x + R, y + R, 3.0), fill, paint.surface, 2.0);
c.fill(rounded_rect(x - R / 2.0, y - R / 2.0, x + R / 2.0, y + R / 2.0, 1.5), ink(fill).alpha(0.4));
}
_ => c.shape(ellipse(at, R, R), fill, paint.surface, 2.0),
}
let mark = ink(fill);
match kind {
Kind::Merge => c.fill(ellipse(at, R * 0.45, R * 0.45), paint.surface),
Kind::Reverse => {
let d = R * 0.45;
c.stroke(vec![[x - d, y - d], [x + d, y + d]], false, 1.75, mark);
c.stroke(vec![[x - d, y + d], [x + d, y - d]], false, 1.75, mark);
}
Kind::CherryPick => {
c.fill(ellipse([x - 2.6, y + 2.0], 2.3, 2.3), mark);
c.fill(ellipse([x + 2.6, y + 2.0], 2.3, 2.3), mark);
c.stroke(vec![[x - 2.0, y], [x + 0.5, y - 5.0], [x + 2.4, y]], false, 1.0, mark);
}
_ => {}
}
}
#[cfg(test)]
#[path = "git_tests.rs"]
mod tests;
@@ -0,0 +1,57 @@
use super::*;
fn git(src: &str) -> GitGraph {
match crate::parse(src).map(|p| p.diagram) {
Some(crate::Diagram::Git(g)) => g,
_ => panic!("not a git graph: {src:?}"),
}
}
#[test]
fn branches_merges_and_cherry_picks() {
let g = git(
"gitGraph\n commit id: \"Alpha\"\n commit tag: \"v1.0\" type: HIGHLIGHT\n branch develop order: 2\n checkout develop\n commit id:\"Beta\" type: REVERSE\n commit\n switch main\n merge develop id: \"M\" tag: \"v2\"\n branch \"feature/x\"\n commit id: \"F\"\n cherry-pick id: \"Beta\"\n checkout nowhere\n merge main\n merge feature/x\n bogus line",
);
assert_eq!(g.flow, Flow::Right);
let names: Vec<&str> = g.branches.iter().map(|b| b.name.as_str()).collect();
assert_eq!(names, ["main", "develop", "feature/x"]);
assert_eq!(g.branches[1].order, Some(2.0));
let shape: Vec<(Option<&str>, Kind, usize, &[usize])> =
g.commits.iter().map(|c| (c.id.as_deref(), c.kind, c.branch, c.parents.as_slice())).collect();
assert_eq!(
shape,
[
(Some("Alpha"), Kind::Normal, 0, &[][..]),
(None, Kind::Highlight, 0, &[0][..]),
(Some("Beta"), Kind::Reverse, 1, &[1][..]),
(None, Kind::Normal, 1, &[2][..]),
(Some("M"), Kind::Merge, 0, &[1, 3][..]),
(Some("F"), Kind::Normal, 2, &[4][..]),
(None, Kind::CherryPick, 2, &[5][..]),
],
"merging main into feature/x is skipped: feature/x already has main's head"
);
assert_eq!(g.commits[1].tag.as_deref(), Some("v1.0"));
assert_eq!(g.commits[4].tag.as_deref(), Some("v2"));
assert_eq!(g.commits[6].picked, Some(2));
}
#[test]
fn flows_and_bounds() {
assert_eq!(git("gitGraph TB:\ncommit").flow, Flow::Down);
assert_eq!(git("gitGraph BT:\ncommit").flow, Flow::Up);
assert!(crate::parse("gitGraph\nbranch x").is_none(), "no commits");
let budget = format!("gitGraph\n{}", "commit\n".repeat(MAX_ITEMS + 1));
assert!(crate::parse(&budget).is_none());
}
#[test]
fn draws_lanes_ids_and_tags() {
for src in ["gitGraph\ncommit id: \"A\" tag: \"v1\"\nbranch dev\ncommit id: \"B\"\ncheckout main\nmerge dev", "gitGraph TB:\ncommit id: \"A\"\nbranch dev\ncommit id: \"B\" tag: \"t\""] {
let s = crate::scene(src, &DiagramStyle::neutral(false), None).unwrap();
let texts: Vec<&str> = s.labels.iter().map(|l| l.text.as_str()).collect();
for t in ["main", "dev", "A", "B"] {
assert!(texts.contains(&t), "{t} in {texts:?}");
}
}
}
+155
View File
@@ -0,0 +1,155 @@
//! User journeys (`journey`): tasks left to right under their sections, each with a face at its
//! score (1 to 5) and dots for the actors in it, and a legend of actors.
use rune::{Align, oklch};
use super::{bold, dark, hue, ink, small, soft, solid, strong};
use crate::canvas::{Canvas, Measured, Scene, arc, arrowhead, ellipse, measure, measure_wrap, rounded_rect};
use crate::{DiagramStyle, MAX_ITEMS, clean, word};
#[derive(Debug, PartialEq)]
pub(crate) struct Task {
pub name: String,
pub score: f32,
pub actors: Vec<usize>,
pub section: Option<usize>,
}
#[derive(Debug)]
pub(crate) struct Journey {
pub title: Option<String>,
pub sections: Vec<String>,
pub actors: Vec<String>,
pub tasks: Vec<Task>,
}
pub(crate) fn parse(body: &[&str]) -> Option<Journey> {
let mut j = Journey { title: None, sections: Vec::new(), actors: Vec::new(), tasks: Vec::new() };
for &l in body {
if let Some(rest) = word(l, "title") {
j.title = Some(clean(rest)).filter(|s| !s.is_empty());
continue;
}
if let Some(rest) = word(l, "section") {
j.sections.push(clean(rest));
continue;
}
if l.starts_with("accTitle") || l.starts_with("accDescr") {
continue;
}
let mut parts = l.splitn(3, ':');
let (Some(name), Some(score)) = (parts.next(), parts.next()) else { continue };
let Ok(score) = score.trim().parse::<f32>() else { continue };
if !score.is_finite() {
continue;
}
if j.tasks.len() + j.sections.len() >= MAX_ITEMS {
return None;
}
let mut actors = Vec::new();
for a in parts.next().unwrap_or("").split(',').map(clean).filter(|a| !a.is_empty()) {
let i = j.actors.iter().position(|x| *x == a).unwrap_or_else(|| {
j.actors.push(a);
j.actors.len() - 1
});
if !actors.contains(&i) {
actors.push(i);
}
}
j.tasks.push(Task { name: clean(name), score: score.clamp(1.0, 5.0), actors, section: j.sections.len().checked_sub(1) });
}
(!j.tasks.is_empty()).then_some(j)
}
const COL: f32 = 112.0;
const GAP: f32 = 10.0;
const STEP: f32 = 20.0;
const FACE: f32 = 11.0;
const DOT: f32 = 4.5;
fn actor_hue(i: usize) -> f32 {
hue(i + 6)
}
/// Green for 5 down to red for 1.
fn mood(score: f32, paint: &DiagramStyle) -> rune::Color {
let h = 25.0 + (score - 1.0) / 4.0 * 125.0;
if dark(paint) { oklch(0.7, 0.14, h) } else { oklch(0.8, 0.14, h) }
}
pub(crate) fn draw(j: &Journey, paint: &DiagramStyle) -> Option<Scene> {
let head = bold(paint.font);
let note = small(paint);
let x_of = |i: usize| i as f32 * (COL + GAP);
let mut c = Canvas::default();
// The legend: one row of actors.
let mut y = 0.0;
if !j.actors.is_empty() {
let mut x = 0.0;
let names: Vec<Measured> = j.actors.iter().map(|a| measure(a, note)).collect();
let h = names.iter().map(|m| m.size[1]).fold(0.0, f32::max);
for (i, m) in names.iter().enumerate() {
c.fill(ellipse([x + DOT + 1.0, h / 2.0], DOT + 1.0, DOT + 1.0), solid(paint, actor_hue(i)));
c.label_at(m, [x + 2.0 * DOT + 8.0, 0.0], note, paint.muted, Align::Start);
x += 2.0 * DOT + 8.0 + m.size[0] + 16.0;
}
y = h + 12.0;
}
if !j.sections.is_empty() {
let titles: Vec<Measured> = j.sections.iter().map(|s| measure_wrap(s, head, 3.0 * COL)).collect();
let band = titles.iter().map(|m| m.size[1]).fold(0.0, f32::max) + 14.0;
for (s, m) in titles.iter().enumerate() {
let cols: Vec<usize> = (0..j.tasks.len()).filter(|&i| j.tasks[i].section == Some(s)).collect();
let (Some(&a), Some(&b)) = (cols.first(), cols.last()) else { continue };
let fill = solid(paint, hue(s));
c.fill(rounded_rect(x_of(a), y, x_of(b) + COL, y + band, 6.0), fill);
c.label(m, [(x_of(a) + x_of(b) + COL) / 2.0, y + band / 2.0], head, ink(fill), Align::Center);
}
y += band + 8.0;
}
let names: Vec<Measured> = j.tasks.iter().map(|t| measure_wrap(&t.name, paint.font, COL - 16.0)).collect();
let box_h = names.iter().map(|m| m.size[1]).fold(0.0, f32::max) + 20.0;
let faces_top = y + box_h + 22.0 + FACE;
let faces_bottom = faces_top + 4.0 * STEP;
for (i, (t, m)) in j.tasks.iter().zip(&names).enumerate() {
let x = x_of(i);
let h = hue(t.section.unwrap_or(0));
let mid = x + COL / 2.0;
let face = [mid, faces_top + (5.0 - t.score) * STEP];
c.dashed(&[[mid, y + box_h], [mid, faces_bottom + FACE + 8.0]], 1.0, paint.text.alpha(0.25), 4.0, 3.0);
c.shape(rounded_rect(x, y, x + COL, y + box_h, 6.0), soft(paint, h), strong(paint, h), 1.0);
c.label(m, [mid, y + box_h / 2.0 + 2.0], paint.font, paint.text, Align::Center);
for (k, &a) in t.actors.iter().enumerate() {
c.shape(ellipse([x + 12.0 + k as f32 * (2.0 * DOT + 4.0), y], DOT, DOT), solid(paint, actor_hue(a)), paint.surface, 1.5);
}
draw_face(&mut c, face, t.score, paint);
}
let base = faces_bottom + FACE + 8.0;
let right = x_of(j.tasks.len() - 1) + COL + 12.0;
c.stroke(vec![[-4.0, base], [right - 8.0, base]], false, 1.5, paint.line);
c.fill(arrowhead([right, base], [1.0, 0.0], 9.0, 8.0), paint.line);
c.finish_fit(paint)
}
fn draw_face(c: &mut Canvas, at: [f32; 2], score: f32, paint: &DiagramStyle) {
let line = oklch(0.25, 0.02, 60.0);
c.shape(ellipse(at, FACE, FACE), mood(score, paint), line.alpha(0.6), 1.0);
for dx in [-3.8, 3.8] {
c.fill(ellipse([at[0] + dx, at[1] - 3.0], 1.4, 1.6), line);
}
let mouth = if score > 3.0 {
arc([at[0], at[1] + 1.0], 5.0, 4.0, 20.0, 160.0, 12)
} else if score < 3.0 {
arc([at[0], at[1] + 8.0], 5.0, 3.5, 200.0, 340.0, 12)
} else {
vec![[at[0] - 4.5, at[1] + 4.5], [at[0] + 4.5, at[1] + 4.5]]
};
c.stroke(mouth, false, 1.3, line);
}
#[cfg(test)]
#[path = "journey_tests.rs"]
mod tests;
@@ -0,0 +1,44 @@
use super::*;
fn journey(src: &str) -> Journey {
match crate::parse(src).map(|p| p.diagram) {
Some(crate::Diagram::Journey(j)) => j,
_ => panic!("not a journey: {src:?}"),
}
}
#[test]
fn sections_tasks_scores_and_actors() {
let j = journey(
"journey\n title My working day\n section Go to work\n Make tea: 5: Me\n Go upstairs: 3: Me\n Do work: 1: Me, Cat\n section Go home\n Go downstairs: 9: Cat\n No score here\n Bad: lots: Me\n Sit down: 0",
);
assert_eq!(j.title.as_deref(), Some("My working day"));
assert_eq!(j.sections, ["Go to work", "Go home"]);
assert_eq!(j.actors, ["Me", "Cat"]);
let got: Vec<(&str, f32, &[usize], Option<usize>)> = j.tasks.iter().map(|t| (t.name.as_str(), t.score, t.actors.as_slice(), t.section)).collect();
assert_eq!(
got,
[
("Make tea", 5.0, &[0][..], Some(0)),
("Go upstairs", 3.0, &[0][..], Some(0)),
("Do work", 1.0, &[0, 1][..], Some(0)),
("Go downstairs", 5.0, &[1][..], Some(1)),
("Sit down", 1.0, &[][..], Some(1)),
]
);
assert!(crate::parse("journey\ntitle Empty\nsection A").is_none());
let budget = format!("journey\n{}", (0..=MAX_ITEMS).map(|i| format!("t{i}: 3: Me")).collect::<Vec<_>>().join("\n"));
assert!(crate::parse(&budget).is_none());
}
#[test]
fn draws_tasks_sections_and_actors() {
let paint = DiagramStyle::neutral(false);
let s = crate::scene("journey\nsection Day\nGood: 5: Me\nBad: 1: Me", &paint, None).unwrap();
let texts: Vec<&str> = s.labels.iter().map(|l| l.text.as_str()).collect();
for t in ["Day", "Good", "Bad", "Me"] {
assert!(texts.contains(&t), "{t} in {texts:?}");
}
let low = |p: &DiagramStyle, score: f32| mood(score, p).to_oklab();
assert!(low(&paint, 5.0)[0] > 0.5 && low(&paint, 1.0)[0] > 0.5);
}
+267
View File
@@ -0,0 +1,267 @@
//! Mindmaps (`mindmap`): a tree nested by indentation, drawn from its root out to both sides with
//! each top-level branch in its own colour. Node shapes are `[square]`, `(rounded)`,
//! `((circle))`, `))bang((`, `)cloud(` and `{{hexagon}}`; a bare line is a plain node.
use rune::{Align, Color, TextStyle};
use super::{bold, hue, ink, s_curve, soft, solid, strong};
use crate::canvas::shape::{self, NodeShape};
use crate::canvas::{Canvas, Measured, Scene, measure_wrap, over_color, rounded_rect};
use crate::{DiagramStyle, MAX_DEPTH, MAX_ITEMS, clean_quoted};
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum Look {
Plain,
Square,
Rounded,
Circle,
Bang,
Cloud,
Hexagon,
}
#[derive(Debug)]
pub(crate) struct Node {
pub text: String,
pub look: Look,
pub depth: usize,
pub children: Vec<usize>,
}
/// Nodes in source order; the first is the root.
#[derive(Debug)]
pub(crate) struct Mindmap {
pub nodes: Vec<Node>,
}
pub(crate) fn parse(body: &[&str], indents: &[usize]) -> Option<Mindmap> {
let mut nodes: Vec<Node> = Vec::new();
let mut stack: Vec<(usize, usize)> = Vec::new();
for (i, line) in body.iter().enumerate() {
let l = line.trim();
if l.starts_with("::icon(") || l.starts_with(":::") || l.starts_with("accTitle") || l.starts_with("accDescr") {
continue;
}
let Some((text, look)) = node(l) else { continue };
if nodes.len() >= MAX_ITEMS {
return None;
}
let indent = indents.get(i).copied().unwrap_or(0);
let id = nodes.len();
if id == 0 {
nodes.push(Node { text, look, depth: 0, children: Vec::new() });
stack.push((indent, 0));
continue;
}
// A line no deeper than the root still hangs off it: there is one root.
while stack.len() > 1 && stack.last().is_some_and(|s| s.0 >= indent) {
stack.pop();
}
let parent = stack.last().map_or(0, |s| s.1);
let depth = nodes[parent].depth + 1;
if depth > MAX_DEPTH {
return None;
}
nodes[parent].children.push(id);
nodes.push(Node { text, look, depth, children: Vec::new() });
stack.push((indent, id));
}
(!nodes.is_empty()).then_some(Mindmap { nodes })
}
/// `id[text]`, `id((text))`, … or a bare line. An opener without its closer reads as written.
fn node(l: &str) -> Option<(String, Look)> {
let l = match l.rfind(":::") {
Some(i) if !l[i..].contains([')', ']', '}']) => l[..i].trim(),
_ => l,
};
if l.is_empty() {
return None;
}
if let Some(p) = l.find(['[', '(', ')', '{']) {
let rest = &l[p..];
const SHAPES: [(&str, &str, Look); 7] = [
("((", "))", Look::Circle),
("))", "((", Look::Bang),
("{{", "}}", Look::Hexagon),
(")", "(", Look::Cloud),
("(", ")", Look::Rounded),
("[", "]", Look::Square),
("{", "}", Look::Rounded),
];
for (open, close, look) in SHAPES {
if let Some(inner) = rest.strip_prefix(open).and_then(|r| r.strip_suffix(close))
&& !inner.is_empty()
{
return Some((clean_quoted(inner), look));
}
}
}
Some((clean_quoted(l), Look::Plain))
}
const GAP_X: f32 = 40.0;
const GAP_Y: f32 = 10.0;
const WRAP: f32 = 150.0;
struct Placed {
label: Measured,
size: [f32; 2],
/// -1 left of the root, 1 right, 0 the root.
side: f32,
/// The top-level branch it's on.
branch: usize,
at: [f32; 2],
}
pub(crate) fn draw(m: &Mindmap, paint: &DiagramStyle) -> Option<Scene> {
let n = m.nodes.len();
let font = |i: usize| if i == 0 { bold(paint.font) } else { paint.font };
let mut placed: Vec<Placed> = (0..n)
.map(|i| {
let node = &m.nodes[i];
let label = measure_wrap(&node.text, font(i), WRAP);
Placed { size: size(look(i, node.look), label.size), label, side: 0.0, branch: 0, at: [0.0; 2] }
})
.collect();
let mut block = vec![0.0f32; n];
for i in (0..n).rev() {
let kids = &m.nodes[i].children;
let stacked: f32 = kids.iter().map(|&k| block[k]).sum::<f32>() + GAP_Y * kids.len().saturating_sub(1) as f32;
block[i] = placed[i].size[1].max(stacked);
}
// Top-level branches fill the right side in order until it holds half the height.
let top = &m.nodes[0].children;
let total: f32 = top.iter().map(|&k| block[k]).sum();
let mut right = Vec::new();
let mut left = Vec::new();
let mut held = 0.0;
for &k in top {
if right.is_empty() || held + block[k] / 2.0 <= total / 2.0 {
held += block[k];
right.push(k);
} else {
left.push(k);
}
}
for (b, &k) in top.iter().enumerate() {
mark(m, &mut placed, k, b, if right.contains(&k) { 1.0 } else { -1.0 });
}
// Each depth on each side is a column as wide as its widest node.
let mut cols = [vec![0.0f32; MAX_DEPTH + 1], vec![0.0f32; MAX_DEPTH + 1]];
for (i, p) in placed.iter().enumerate().skip(1) {
let c = &mut cols[usize::from(p.side > 0.0)][m.nodes[i].depth];
*c = c.max(p.size[0]);
}
for (kids, side) in [(&right, 1.0f32), (&left, -1.0)] {
let col = &cols[usize::from(side > 0.0)];
let height: f32 = kids.iter().map(|&k| block[k]).sum::<f32>() + GAP_Y * kids.len().saturating_sub(1) as f32;
let mut y = -height / 2.0;
for &k in kids.iter() {
place(m, &mut placed, &block, col, k, y);
y += block[k] + GAP_Y;
}
}
let mut c = Canvas::default();
for (i, node) in m.nodes.iter().enumerate() {
let p = &placed[i];
for &k in &node.children {
let q = &placed[k];
let a = [p.at[0] + q.side * p.size[0] / 2.0, p.at[1]];
let b = [q.at[0] - q.side * q.size[0] / 2.0, q.at[1]];
let width = (3.5 - node.depth as f32 * 0.75).max(1.25);
c.stroke(s_curve(a, b, false), false, width, solid(paint, branch_hue(q.branch)));
}
}
for (i, node) in m.nodes.iter().enumerate() {
let p = &placed[i];
let h = branch_hue(p.branch);
let (fill, border) = match node.depth {
0 => (solid(paint, hue(0)), strong(paint, hue(0))),
1 => (soft(paint, h), strong(paint, h)),
_ => (over_color(soft(paint, h).alpha(0.55), paint.surface), strong(paint, h).alpha(0.7)),
};
let text = if node.depth == 0 { ink(fill) } else { paint.text };
draw_node(&mut c, look(i, node.look), p, [fill, border, text], font(i));
}
c.finish_fit(paint)
}
/// A plain root is drawn rounded, so it reads as the centre.
fn look(i: usize, look: Look) -> Look {
if i == 0 && look == Look::Plain { Look::Rounded } else { look }
}
/// Branch `b`'s hue; the root keeps the first.
fn branch_hue(b: usize) -> f32 {
hue(b + 1)
}
fn mark(m: &Mindmap, placed: &mut [Placed], i: usize, branch: usize, side: f32) {
placed[i].side = side;
placed[i].branch = branch;
for &k in &m.nodes[i].children {
mark(m, placed, k, branch, side);
}
}
/// Places `i`'s subtree in a band of its block height from `top`.
fn place(m: &Mindmap, placed: &mut [Placed], block: &[f32], col: &[f32], i: usize, top: f32) {
let node = &m.nodes[i];
let side = placed[i].side;
let inner = col[1..node.depth].iter().map(|w| w + GAP_X).sum::<f32>() + placed[0].size[0] / 2.0 + GAP_X;
placed[i].at = [side * (inner + placed[i].size[0] / 2.0), top + block[i] / 2.0];
let stacked: f32 = node.children.iter().map(|&k| block[k]).sum::<f32>() + GAP_Y * node.children.len().saturating_sub(1) as f32;
let mut y = top + (block[i] - stacked) / 2.0;
for &k in &node.children {
place(m, placed, block, col, k, y);
y += block[k] + GAP_Y;
}
}
fn as_shape(look: Look) -> Option<NodeShape> {
match look {
Look::Circle => Some(NodeShape::Circle),
Look::Bang => Some(NodeShape::Bang),
Look::Cloud => Some(NodeShape::Cloud),
Look::Hexagon => Some(NodeShape::Hexagon),
_ => None,
}
}
fn size(look: Look, t: [f32; 2]) -> [f32; 2] {
match as_shape(look) {
Some(s) => {
let [w, h] = shape::node_size(s, t);
if look == Look::Hexagon { [w, (t[1] + 16.0).max(34.0)] } else { [w, h] }
}
None => [t[0] + 24.0, (t[1] + 14.0).max(32.0)],
}
}
fn draw_node(c: &mut Canvas, look: Look, p: &Placed, [fill, border, text]: [Color; 3], font: TextStyle) {
let [x, y] = p.at;
let [w, h] = p.size;
let (x0, y0, x1, y1) = (x - w / 2.0, y - h / 2.0, x + w / 2.0, y + h / 2.0);
match look {
Look::Plain => {
c.fill(rounded_rect(x0, y0, x1, y1, 4.0), fill);
c.stroke(vec![[x0, y1], [x1, y1]], false, 2.0, border);
}
Look::Square => c.shape(rounded_rect(x0, y0, x1, y1, 0.0), fill, border, 1.0),
Look::Rounded => c.shape(rounded_rect(x0, y0, x1, y1, 10.0), fill, border, 1.0),
_ => {
if let Some(s) = as_shape(look) {
c.shape(shape::outline(s, p.at, p.size), fill, border, 1.0);
}
}
}
c.label(&p.label, p.at, font, text, Align::Center);
}
#[cfg(test)]
#[path = "mindmap_tests.rs"]
mod tests;
@@ -0,0 +1,52 @@
use super::*;
fn mindmap(src: &str) -> Mindmap {
match crate::parse(src).map(|p| p.diagram) {
Some(crate::Diagram::Mindmap(m)) => m,
_ => panic!("not a mindmap: {src:?}"),
}
}
fn texts(m: &Mindmap, i: usize) -> Vec<&str> {
m.nodes[i].children.iter().map(|&k| m.nodes[k].text.as_str()).collect()
}
#[test]
fn nests_by_indentation_with_shapes() {
let m = mindmap(
"mindmap\n root((mindmap))\n Origins\n Long history\n ::icon(fa fa-book)\n Popularisation\n British author\n Research\n a[On effectiveness<br/>and features]\n b))Bang((\n c)Cloud(\n d{{Hex}}\n e(Rounded):::urgent\n Tools\n f[unclosed",
);
assert_eq!(m.nodes[0].text, "mindmap");
assert_eq!(m.nodes[0].look, Look::Circle);
assert_eq!(texts(&m, 0), ["Origins", "Research", "Tools"]);
assert_eq!(texts(&m, 1), ["Long history", "Popularisation"]);
let research = m.nodes[0].children[1];
assert_eq!(texts(&m, research), ["On effectiveness\nand features", "Bang", "Cloud", "Hex", "Rounded"]);
let looks: Vec<Look> = m.nodes[research].children.iter().map(|&k| m.nodes[k].look).collect();
assert_eq!(looks, [Look::Square, Look::Bang, Look::Cloud, Look::Hexagon, Look::Rounded]);
let tools = m.nodes[0].children[2];
let f = m.nodes[tools].children[0];
assert_eq!((m.nodes[f].text.as_str(), m.nodes[f].look), ("f[unclosed", Look::Plain), "read as written");
}
#[test]
fn one_root_and_bounds() {
let m = mindmap("mindmap\n Root\n Shallower\n Sibling\n Child");
assert_eq!(texts(&m, 0), ["Shallower", "Sibling"], "a line no deeper than the root hangs off it");
assert_eq!(texts(&m, 2), ["Child"]);
assert!(crate::parse("mindmap").is_none());
let deep: String = (0..=MAX_DEPTH + 1).map(|d| format!("{}n{d}\n", " ".repeat(d * 2))).collect();
assert!(crate::parse(&format!("mindmap\n{deep}")).is_none());
let wide = format!("mindmap\nroot\n{}", (0..MAX_ITEMS).map(|i| format!(" n{i}")).collect::<Vec<_>>().join("\n"));
assert!(crate::parse(&wide).is_none());
}
#[test]
fn branches_split_left_and_right() {
let paint = DiagramStyle::neutral(true);
let s = crate::scene("mindmap\n Centre\n One\n Two\n Three\n Four", &paint, None).unwrap();
let at = |t: &str| s.labels.iter().find(|l| l.text == t).map(|l| l.at[0] + l.size[0] / 2.0).unwrap();
let centre = at("Centre");
assert!(at("One") > centre && at("Two") > centre, "the first branches go right");
assert!(at("Three") < centre && at("Four") < centre, "the rest go left");
}
+102
View File
@@ -0,0 +1,102 @@
//! What charts share: a series palette that themes with [`DiagramStyle`], text colour on a fill,
//! smaller and bolder type, an S-curve between two points, and a horizontal axis with grid lines.
mod date;
pub(crate) mod gantt;
pub(crate) mod git;
pub(crate) mod journey;
pub(crate) mod mindmap;
pub(crate) mod pie;
pub(crate) mod quadrant;
pub(crate) mod sankey;
pub(crate) mod timeline;
pub(crate) mod xychart;
use rune::{Align, Color, TextStyle, oklch};
use crate::DiagramStyle;
use crate::canvas::{Canvas, Measured};
/// Series hues, spread so neighbours never look alike.
const HUES: [f32; 12] = [255.0, 25.0, 150.0, 70.0, 305.0, 195.0, 350.0, 110.0, 280.0, 170.0, 45.0, 225.0];
pub(crate) fn dark(paint: &DiagramStyle) -> bool {
paint.surface.to_oklab()[0] < 0.5
}
/// The hue of series `i`.
pub(crate) fn hue(i: usize) -> f32 {
HUES[i % HUES.len()]
}
/// A series' solid colour: pie slices, lines, swatches.
pub(crate) fn solid(paint: &DiagramStyle, h: f32) -> Color {
if dark(paint) { oklch(0.62, 0.12, h) } else { oklch(0.72, 0.12, h) }
}
/// A series' quiet fill, for bars that carry text and bands behind rows.
pub(crate) fn soft(paint: &DiagramStyle, h: f32) -> Color {
if dark(paint) { oklch(0.38, 0.07, h) } else { oklch(0.9, 0.05, h) }
}
/// A series' outline, for [`soft`] fills.
pub(crate) fn strong(paint: &DiagramStyle, h: f32) -> Color {
if dark(paint) { oklch(0.7, 0.12, h) } else { oklch(0.56, 0.13, h) }
}
/// Text that reads on `fill`.
pub(crate) fn ink(fill: Color) -> Color {
if fill.to_oklab()[0] > 0.6 { oklch(0.22, 0.01, 260.0) } else { oklch(0.97, 0.005, 260.0) }
}
/// The diagram's type a point smaller: axis ticks, legends, notes.
pub(crate) fn small(paint: &DiagramStyle) -> TextStyle {
TextStyle { size: paint.font.size - 1.0, line_height: paint.font.line_height - 2.0, ..paint.font }
}
pub(crate) fn bold(font: TextStyle) -> TextStyle {
TextStyle { weight: 600.0, ..font }
}
/// A curve from `a` to `b` that leaves and arrives level (or upright when `upright`).
pub(crate) fn s_curve(a: [f32; 2], b: [f32; 2], upright: bool) -> Vec<[f32; 2]> {
let (c1, c2) = if upright {
let m = (a[1] + b[1]) / 2.0;
([a[0], m], [b[0], m])
} else {
let m = (a[0] + b[0]) / 2.0;
([m, a[1]], [m, b[1]])
};
(0..=20)
.map(|i| {
let t = i as f32 / 20.0;
let u = 1.0 - t;
let (k0, k1, k2, k3) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t);
[k0 * a[0] + k1 * c1[0] + k2 * c2[0] + k3 * b[0], k0 * a[1] + k1 * c1[1] + k2 * c2[1] + k3 * b[1]]
})
.collect()
}
/// Grid lines from `top` to `bottom` at each tick's x, between `x0` and `x1`, with its label
/// centred under `bottom` and kept inside `[x0, x1]` (one that would overlap the last is dropped).
pub(crate) fn axis_x(c: &mut Canvas, ticks: &[(f32, Measured)], [x0, x1]: [f32; 2], [top, bottom]: [f32; 2], font: TextStyle, paint: &DiagramStyle) {
let grid = paint.text.alpha(0.08);
c.stroke(vec![[x0, bottom], [x1, bottom]], false, 1.0, paint.surface_border);
let mut right = f32::MIN;
for (x, m) in ticks {
if *x < x0 - 0.5 || *x > x1 + 0.5 {
continue;
}
c.stroke(vec![[*x, top], [*x, bottom]], false, 1.0, grid);
c.stroke(vec![[*x, bottom], [*x, bottom + 4.0]], false, 1.0, paint.surface_border);
let left = (x - m.size[0] / 2.0).clamp(x0, (x1 - m.size[0]).max(x0));
if left < right + 8.0 {
continue;
}
c.label_at(m, [left, bottom + 6.0], font, paint.muted, Align::Start);
right = left + m.size[0];
}
}
#[cfg(test)]
mod tests;
+129
View File
@@ -0,0 +1,129 @@
//! Pie charts (`pie`): slices from twelve o'clock clockwise in source order, percentages on the
//! slices wide enough to hold them, and a legend (with values under `showData`).
use rune::{Align, TextStyle};
use super::{hue, ink, solid};
use crate::canvas::{Canvas, Measured, Scene, arc, measure, room, rounded_rect};
use crate::{DiagramStyle, MAX_ITEMS, clean_quoted, statements};
#[derive(Debug)]
pub(crate) struct Pie {
pub title: Option<String>,
pub show_data: bool,
pub slices: Vec<(String, f64)>,
}
pub(crate) fn parse(header: &str, body: &[&str]) -> Option<Pie> {
let mut p = Pie { title: None, show_data: false, slices: Vec::new() };
for line in std::iter::once(header).chain(body.iter().copied()) {
for stmt in statements(line) {
let mut s = stmt;
if let Some(rest) = s.strip_prefix("showData") {
p.show_data = true;
s = rest.trim();
}
if let Some(rest) = s.strip_prefix("title").filter(|r| r.is_empty() || r.starts_with(char::is_whitespace)) {
p.title = Some(clean_quoted(rest)).filter(|t| !t.is_empty());
continue;
}
if s.is_empty() || s.starts_with("accTitle") || s.starts_with("accDescr") {
continue;
}
let Some((label, value)) = s.rsplit_once(':') else { continue };
let Ok(v) = value.trim().parse::<f64>() else { continue };
if !(v.is_finite() && v > 0.0) {
continue;
}
if p.slices.len() >= MAX_ITEMS {
return None;
}
p.slices.push((clean_quoted(label), v));
}
}
(!p.slices.is_empty()).then_some(p)
}
/// `386`, `12.5`, `0.33`.
pub(crate) fn number(v: f64) -> String {
if v.fract() == 0.0 && v.abs() < 1e15 {
return format!("{v:.0}");
}
let s = format!("{v:.2}");
s.trim_end_matches('0').trim_end_matches('.').to_owned()
}
const R: f32 = 100.0;
const SWATCH: f32 = 12.0;
pub(crate) fn draw(p: &Pie, paint: &DiagramStyle) -> Option<Scene> {
let small = TextStyle { size: paint.font.size - 1.0, line_height: paint.font.line_height - 2.0, ..paint.font };
let pct_font = TextStyle { weight: 600.0, ..small };
let total: f64 = p.slices.iter().map(|s| s.1).sum();
let names: Vec<Measured> = p.slices.iter().map(|s| measure(&s.0, paint.font)).collect();
let values: Vec<Option<Measured>> = p.slices.iter().map(|s| p.show_data.then(|| measure(&number(s.1), paint.font))).collect();
let row_h = paint.font.line_height.max(SWATCH) + 6.0;
let legend_w = names
.iter()
.zip(&values)
.map(|(n, v)| SWATCH + 8.0 + n.size[0] + v.as_ref().map_or(0.0, |v| v.size[0] + 8.0))
.fold(0.0, f32::max);
let legend_h = p.slices.len() as f32 * row_h - 6.0;
let beside = 2.0 * R + 32.0 + legend_w <= room(paint);
let (centre, legend) = if beside {
let h = legend_h.max(2.0 * R);
([R, h / 2.0], [2.0 * R + 32.0, (h - legend_h) / 2.0])
} else {
([R.max(legend_w / 2.0), R], [(R - legend_w / 2.0).max(0.0), 2.0 * R + 20.0])
};
let mut c = Canvas::default();
let mut a = -90.0f32;
let mut edges = Vec::new();
for (i, s) in p.slices.iter().enumerate() {
let sweep = (s.1 / total) as f32 * 360.0;
let steps = ((sweep / 4.0).ceil() as usize).max(2);
let mut pts = arc(centre, R, R, a, a + sweep, steps);
if p.slices.len() > 1 {
pts.push(centre);
}
c.fill(pts, solid(paint, hue(i)));
edges.push(a);
a += sweep;
}
if p.slices.len() > 1 {
for a in edges {
let r = a.to_radians();
c.stroke(vec![centre, [centre[0] + R * r.cos(), centre[1] + R * r.sin()]], false, 2.0, paint.surface);
}
}
let mut a = -90.0f32;
for (i, s) in p.slices.iter().enumerate() {
let frac = s.1 / total;
let sweep = frac as f32 * 360.0;
let m = measure(&format!("{:.0}%", frac * 100.0), pct_font);
// Only where the slice is wide enough at that radius to hold it.
let room_across = 2.0 * R * 0.66 * (sweep / 2.0).min(90.0).to_radians().sin();
if p.slices.len() == 1 || m.size[0] + 6.0 <= room_across {
let mid = (a + sweep / 2.0).to_radians();
let at = if p.slices.len() == 1 { centre } else { [centre[0] + R * 0.66 * mid.cos(), centre[1] + R * 0.66 * mid.sin()] };
c.label(&m, at, pct_font, ink(solid(paint, hue(i))), Align::Center);
}
a += sweep;
}
for (i, (n, v)) in names.iter().zip(&values).enumerate() {
let y = legend[1] + i as f32 * row_h;
let mid = y + (row_h - 6.0) / 2.0;
let x = legend[0];
c.fill(rounded_rect(x, mid - SWATCH / 2.0, x + SWATCH, mid + SWATCH / 2.0, 3.0), solid(paint, hue(i)));
c.label_at(n, [x + SWATCH + 8.0, mid - n.size[1] / 2.0], paint.font, paint.text, Align::Start);
if let Some(v) = v {
c.label_at(v, [x + SWATCH + 16.0 + n.size[0], mid - v.size[1] / 2.0], paint.font, paint.muted, Align::Start);
}
}
c.finish(1.0, paint)
}
#[cfg(test)]
#[path = "pie_tests.rs"]
mod tests;
@@ -0,0 +1,41 @@
use super::*;
fn pie(src: &str) -> Pie {
match crate::parse(src).map(|p| p.diagram) {
Some(crate::Diagram::Pie(p)) => p,
_ => panic!("not a pie chart: {src:?}"),
}
}
#[test]
fn slices_titles_and_show_data() {
let p = pie("pie showData title Pets adopted\n\"Dogs\" : 386\n\"Cats\" : 85.5\nRats : 15\n\"Bad\" : -3\n\"Zero\" : 0\nnot a slice\n\"x\" : lots");
assert_eq!(p.title.as_deref(), Some("Pets adopted"));
assert!(p.show_data);
assert_eq!(p.slices, [("Dogs".to_owned(), 386.0), ("Cats".to_owned(), 85.5), ("Rats".to_owned(), 15.0)]);
let p = pie("pie\n title Key: value\n \"A: one\" : 1");
assert_eq!(p.title.as_deref(), Some("Key: value"));
assert_eq!(p.slices[0].0, "A: one", "the value is after the last colon");
assert!(!p.show_data);
assert!(crate::parse("pie title Empty").is_none());
}
#[test]
fn numbers_print_short() {
assert_eq!(number(386.0), "386");
assert_eq!(number(85.5), "85.5");
assert_eq!(number(1.0 / 3.0), "0.33");
}
#[test]
fn draws_percentages_and_a_legend() {
let paint = DiagramStyle::neutral(false);
let s = crate::scene("pie showData\n\"Dogs\" : 70\n\"Cats\" : 26\n\"Fish\" : 4", &paint, None).unwrap();
let texts: Vec<&str> = s.labels.iter().map(|l| l.text.as_str()).collect();
for t in ["70%", "26%", "Dogs", "Cats", "Fish", "70", "4"] {
assert!(texts.contains(&t), "{t} in {texts:?}");
}
assert!(!texts.contains(&"4%"), "a sliver has no room for its percentage: {texts:?}");
let budget = format!("pie\n{}", (0..=MAX_ITEMS).map(|i| format!("\"s{i}\" : 1")).collect::<Vec<_>>().join("\n"));
assert!(crate::parse(&budget).is_none());
}
@@ -0,0 +1,189 @@
//! Quadrant charts (`quadrantChart`): `x-axis`/`y-axis` ends, four named quadrants, and points
//! at `[x, y]` in 0 to 1, with `radius`, `color`, `stroke-color` and `stroke-width` set inline
//! or through `classDef` and `:::class`.
use std::collections::HashMap;
use rune::{Align, Color};
use super::{bold, small, soft, strong};
use crate::canvas::{Canvas, Measured, Scene, ellipse, measure, measure_wrap, over_color, room};
use crate::{DiagramStyle, MAX_ITEMS, clean, parse_color_spec, word};
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct Look {
pub radius: Option<f32>,
pub color: Option<Color>,
pub stroke: Option<Color>,
pub stroke_width: Option<f32>,
}
impl Look {
fn or(self, base: &Look) -> Look {
Look {
radius: self.radius.or(base.radius),
color: self.color.or(base.color),
stroke: self.stroke.or(base.stroke),
stroke_width: self.stroke_width.or(base.stroke_width),
}
}
}
#[derive(Debug, PartialEq)]
pub(crate) struct Point {
pub name: String,
pub at: [f32; 2],
pub look: Look,
}
#[derive(Debug, Default)]
pub(crate) struct Quadrant {
pub title: Option<String>,
/// Low and high ends; an empty high end means one label for the whole axis.
pub x: [String; 2],
pub y: [String; 2],
/// Quadrants 1 (top right) to 4 (bottom right), anticlockwise.
pub names: [String; 4],
pub points: Vec<Point>,
}
pub(crate) fn parse(body: &[&str]) -> Option<Quadrant> {
let mut q = Quadrant::default();
let mut classes: HashMap<String, Look> = HashMap::new();
let mut pending: Vec<(String, [f32; 2], Look, Option<String>)> = Vec::new();
let mut any = false;
for &l in body {
let axis = |rest: &str| {
let (a, b) = rest.split_once("-->").unwrap_or((rest, ""));
[clean(a), clean(b)]
};
if let Some(rest) = word(l, "title") {
q.title = Some(clean(rest)).filter(|t| !t.is_empty());
} else if let Some(rest) = word(l, "x-axis") {
q.x = axis(rest);
any = true;
} else if let Some(rest) = word(l, "y-axis") {
q.y = axis(rest);
any = true;
} else if let Some((n, rest)) = l.strip_prefix("quadrant-").and_then(|r| r.split_once(char::is_whitespace)) {
if let Ok(n @ 1..=4) = n.parse::<usize>() {
q.names[n - 1] = clean(rest);
any = true;
}
} else if let Some(rest) = word(l, "classDef") {
let (name, props) = rest.split_once(char::is_whitespace).unwrap_or((rest, ""));
classes.insert(name.to_owned(), look(props));
} else if let Some(p) = point(l) {
if pending.len() >= MAX_ITEMS {
return None;
}
pending.push(p);
}
}
q.points = pending
.into_iter()
.map(|(name, at, look, class)| {
let base = class.and_then(|c| classes.get(&c).cloned()).unwrap_or_default();
Point { name, at, look: look.or(&base) }
})
.collect();
(any || !q.points.is_empty()).then_some(q)
}
/// `Name[:::class]: [x, y] props`.
fn point(l: &str) -> Option<(String, [f32; 2], Look, Option<String>)> {
let open = l.find('[')?;
let close = open + l[open..].find(']')?;
let head = l[..open].trim().strip_suffix(':')?;
let (name, class) = match head.split_once(":::") {
Some((n, c)) => (n, Some(c.trim().to_owned())),
None => (head, None),
};
let (x, y) = l[open + 1..close].split_once(',')?;
let (x, y) = (x.trim().parse::<f32>().ok()?, y.trim().parse::<f32>().ok()?);
if !(x.is_finite() && y.is_finite()) {
return None;
}
Some((clean(name.trim().trim_matches('"')), [x.clamp(0.0, 1.0), y.clamp(0.0, 1.0)], look(&l[close + 1..]), class))
}
fn look(props: &str) -> Look {
let mut out = Look::default();
for part in props.split(',') {
let Some((k, v)) = part.split_once(':') else { continue };
let v = v.trim();
let px = || v.trim_end_matches("px").trim().parse::<f32>().ok().filter(|r| r.is_finite());
match k.trim() {
"radius" => out.radius = px().map(|r| r.clamp(1.0, 30.0)),
"color" => out.color = parse_color_spec(v),
"stroke-color" => out.stroke = parse_color_spec(v),
"stroke-width" => out.stroke_width = px().map(|w| w.clamp(0.0, 8.0)),
_ => {}
}
}
out
}
const HUE: f32 = 255.0;
pub(crate) fn draw(q: &Quadrant, paint: &DiagramStyle) -> Option<Scene> {
let note = small(paint);
let head = bold(paint.font);
let ys: Vec<Measured> = q.y.iter().map(|t| measure_wrap(t, note, 96.0)).collect();
let yw = ys.iter().map(|m| m.size[0]).fold(0.0, f32::max);
let x0 = if yw > 0.0 { yw + 12.0 } else { 0.0 };
let side = (room(paint) - x0).clamp(220.0, 440.0);
let half = side / 2.0;
let (x1, y1) = (x0 + side, side);
let mut c = Canvas::default();
// 1 top right, 2 top left, 3 bottom left, 4 bottom right.
let origins = [[x0 + half, 0.0], [x0, 0.0], [x0, half], [x0 + half, half]];
let tints = [0.95, 0.7, 0.45, 0.7];
for (o, a) in origins.iter().zip(tints) {
let fill = over_color(soft(paint, HUE).alpha(a), paint.surface);
c.fill(vec![*o, [o[0] + half, o[1]], [o[0] + half, o[1] + half], [o[0], o[1] + half]], fill);
}
c.stroke(vec![[x0 + half, 0.0], [x0 + half, y1]], false, 2.0, paint.surface);
c.stroke(vec![[x0, half], [x1, half]], false, 2.0, paint.surface);
for (o, name) in origins.iter().zip(&q.names) {
let m = measure_wrap(name, head, half - 16.0);
let y = if q.points.is_empty() { o[1] + half / 2.0 } else { o[1] + 10.0 + m.size[1] / 2.0 };
c.label(&m, [o[0] + half / 2.0, y], head, paint.text, Align::Center);
}
let xs: Vec<Measured> = q.x.iter().map(|t| measure_wrap(t, note, half - 8.0)).collect();
let below = y1 + 8.0;
if xs[1].text.is_empty() {
c.label_at(&xs[0], [x0 + half - xs[0].size[0] / 2.0, below], note, paint.muted, Align::Center);
} else {
for (i, m) in xs.iter().enumerate() {
c.label_at(m, [x0 + half * (i as f32 + 0.5) - m.size[0] / 2.0, below], note, paint.muted, Align::Center);
}
}
if ys[1].text.is_empty() {
c.label_at(&ys[0], [x0 - 12.0 - ys[0].size[0], half - ys[0].size[1] / 2.0], note, paint.muted, Align::End);
} else {
// Low at the bottom, high at the top.
for (i, m) in ys.iter().enumerate() {
let mid = if i == 0 { half * 1.5 } else { half * 0.5 };
c.label_at(m, [x0 - 12.0 - m.size[0], mid - m.size[1] / 2.0], note, paint.muted, Align::End);
}
}
for p in &q.points {
let at = [x0 + p.at[0] * side, y1 - p.at[1] * side];
let r = p.look.radius.unwrap_or(5.0);
let fill = p.look.color.unwrap_or_else(|| strong(paint, HUE));
let width = p.look.stroke_width.unwrap_or(if p.look.stroke.is_some() { 2.0 } else { 0.0 });
c.fill(ellipse(at, r, r), fill);
if width > 0.0 {
c.stroke(ellipse(at, r, r), true, width, p.look.stroke.unwrap_or(fill));
}
let m = measure(&p.name, note);
c.label_at(&m, [at[0] - m.size[0] / 2.0, at[1] + r + 3.0], note, paint.text, Align::Center);
}
c.finish_fit(paint)
}
#[cfg(test)]
#[path = "quadrant_tests.rs"]
mod tests;
@@ -0,0 +1,40 @@
use super::*;
fn quadrant(src: &str) -> Quadrant {
match crate::parse(src).map(|p| p.diagram) {
Some(crate::Diagram::Quadrant(q)) => q,
_ => panic!("not a quadrant chart: {src:?}"),
}
}
#[test]
fn axes_quadrants_points_and_classes() {
let q = quadrant(
"quadrantChart\n title Reach and engagement\n x-axis Low Reach --> High Reach\n y-axis Engagement\n quadrant-1 We should expand\n quadrant-4 May be improved\n quadrant-9 Nope\n Campaign A: [0.3, 0.6]\n Campaign B: [0.45, 0.23] radius: 12, color: #ff3300, stroke-color: #10f0f0, stroke-width: 5px\n Point C:::hot: [1.4, -0.2]\n Broken: [x, 1]\n classDef hot color: #109060, radius : 10",
);
assert_eq!(q.title.as_deref(), Some("Reach and engagement"));
assert_eq!(q.x, ["Low Reach".to_owned(), "High Reach".to_owned()]);
assert_eq!(q.y, ["Engagement".to_owned(), String::new()]);
assert_eq!(q.names[0], "We should expand");
assert_eq!(q.names[3], "May be improved");
assert_eq!(q.names[1], "");
let names: Vec<&str> = q.points.iter().map(|p| p.name.as_str()).collect();
assert_eq!(names, ["Campaign A", "Campaign B", "Point C"]);
assert_eq!(q.points[1].look.radius, Some(12.0));
assert_eq!(q.points[1].look.stroke_width, Some(5.0));
assert!(q.points[1].look.color.is_some() && q.points[1].look.stroke.is_some());
assert_eq!(q.points[2].at, [1.0, 0.0], "clamped into the chart");
assert_eq!(q.points[2].look.radius, Some(10.0), "from its class, defined later");
assert!(crate::parse("quadrantChart\n title Only a title").is_none());
let budget = format!("quadrantChart\n{}", (0..=MAX_ITEMS).map(|i| format!("p{i}: [0.5, 0.5]")).collect::<Vec<_>>().join("\n"));
assert!(crate::parse(&budget).is_none());
}
#[test]
fn points_land_by_their_values() {
let paint = DiagramStyle::neutral(false);
let s = crate::scene("quadrantChart\nquadrant-1 Q1\nquadrant-3 Q3\nHigh: [0.9, 0.9]\nLow: [0.1, 0.1]", &paint, None).unwrap();
let at = |t: &str| s.labels.iter().find(|l| l.text == t).unwrap().at;
assert!(at("High")[0] > at("Low")[0] && at("High")[1] < at("Low")[1]);
assert!(at("Q1")[0] > at("Q3")[0] && at("Q1")[1] < at("Q3")[1]);
}
+192
View File
@@ -0,0 +1,192 @@
//! Sankey diagrams (`sankey-beta`, `sankey`): `source,target,value` rows (CSV, quotes allowed)
//! drawn as columns of nodes joined by bands as thick as their flow.
use std::collections::HashMap;
use rune::Align;
use super::pie::number;
use super::{hue, s_curve, small, solid};
use crate::canvas::{Canvas, Scene, measure, room};
use crate::{DiagramStyle, MAX_ITEMS, clean};
#[derive(Debug, Default)]
pub(crate) struct Sankey {
pub nodes: Vec<String>,
/// `(from, to, value)`.
pub links: Vec<(usize, usize, f32)>,
}
pub(crate) fn parse(body: &[&str]) -> Option<Sankey> {
let mut s = Sankey::default();
let mut ids: HashMap<String, usize> = HashMap::new();
for &l in body {
let f = fields(l);
let [a, b, v] = f.as_slice() else { continue };
let Some(v) = v.trim().parse::<f32>().ok().filter(|v| v.is_finite() && *v >= 0.0) else { continue };
let (a, b) = (clean(a), clean(b));
if a.is_empty() || b.is_empty() || a == b {
continue;
}
let mut node = |name: String| {
let next = ids.len();
*ids.entry(name.clone()).or_insert_with(|| {
s.nodes.push(name);
next
})
};
let (from, to) = (node(a), node(b));
s.links.push((from, to, v));
if s.nodes.len() + s.links.len() > MAX_ITEMS {
return None;
}
}
(!s.links.is_empty()).then_some(s)
}
/// One CSV row: commas split fields outside `"…"`, and `""` inside quotes is a quote.
fn fields(l: &str) -> Vec<String> {
let (mut out, mut cur, mut quoted) = (Vec::new(), String::new(), false);
let mut chars = l.chars().peekable();
while let Some(ch) = chars.next() {
match ch {
'"' if quoted && chars.peek() == Some(&'"') => {
chars.next();
cur.push('"');
}
'"' => quoted = !quoted,
',' if !quoted => out.push(std::mem::take(&mut cur)),
_ => cur.push(ch),
}
}
out.push(cur);
out
}
/// Each node's column: its longest path from a source, with sinks pushed to the last column.
pub(crate) fn columns(s: &Sankey) -> Vec<usize> {
let n = s.nodes.len();
let mut depth = vec![0usize; n];
// Bounded, so a cycle stops growing at the last column.
for _ in 0..n {
let mut moved = false;
for &(a, b, _) in &s.links {
if depth[b] < depth[a] + 1 && depth[a] + 1 < n {
depth[b] = depth[a] + 1;
moved = true;
}
}
if !moved {
break;
}
}
let last = depth.iter().copied().max().unwrap_or(0);
for (i, d) in depth.iter_mut().enumerate() {
if !s.links.iter().any(|l| l.0 == i) {
*d = last;
}
}
depth
}
const HEIGHT: f32 = 300.0;
const NODE_W: f32 = 10.0;
const PAD: f32 = 12.0;
pub(crate) fn draw(s: &Sankey, paint: &DiagramStyle) -> Option<Scene> {
let n = s.nodes.len();
let note = small(paint);
let col = columns(s);
let cols = col.iter().copied().max().unwrap_or(0) + 1;
let (mut ins, mut outs) = (vec![0.0f32; n], vec![0.0f32; n]);
for &(a, b, v) in &s.links {
outs[a] += v;
ins[b] += v;
}
let value: Vec<f32> = (0..n).map(|i| ins[i].max(outs[i])).collect();
let members: Vec<Vec<usize>> = (0..cols).map(|c| (0..n).filter(|&i| col[i] == c).collect()).collect();
let ky = members
.iter()
.map(|m| (HEIGHT - PAD * (m.len() as f32 - 1.0)) / m.iter().map(|&i| value[i]).sum::<f32>().max(1e-6))
.fold(f32::MAX, f32::min)
.max(0.0);
let h: Vec<f32> = value.iter().map(|v| (v * ky).max(1.0)).collect();
// Stack each column, ordered by where its nodes' neighbours sit, centred on the tallest.
let mut y = vec![0.0f32; n];
let stack = |y: &mut Vec<f32>, m: &[usize]| {
let total: f32 = m.iter().map(|&i| h[i]).sum::<f32>() + PAD * (m.len() as f32 - 1.0);
let mut at = (HEIGHT - total) / 2.0;
for &i in m {
y[i] = at;
at += h[i] + PAD;
}
};
let mut order = members.clone();
for m in &order {
stack(&mut y, m);
}
for pass in 0..4 {
let forward = pass % 2 == 0;
for c in 0..cols {
let c = if forward { c } else { cols - 1 - c };
let mid = |i: usize| {
let (mut sum, mut w) = (0.0, 0.0);
for &(a, b, v) in &s.links {
let other = if b == i && forward { a } else if a == i && !forward { b } else { continue };
sum += (y[other] + h[other] / 2.0) * v;
w += v;
}
if w > 0.0 { sum / w } else { y[i] + h[i] / 2.0 }
};
let mut keyed: Vec<(f32, usize)> = order[c].iter().map(|&i| (mid(i), i)).collect();
keyed.sort_by(|a, b| a.0.total_cmp(&b.0));
order[c] = keyed.into_iter().map(|k| k.1).collect();
stack(&mut y, &order[c]);
}
}
// Columns spread across the room, leaving the labels of the first and last some space.
let width = room(paint);
let x_of = |c: usize| if cols == 1 { 0.0 } else { c as f32 * (width - NODE_W) / (cols - 1) as f32 };
let mut c = Canvas::default();
let mut links: Vec<usize> = (0..s.links.len()).collect();
links.sort_by(|&p, &q| y[s.links[p].1].total_cmp(&y[s.links[q].1]));
let mut out_at: Vec<f32> = y.clone();
let mut in_at: Vec<f32> = y.clone();
let mut ends = vec![[0.0f32; 2]; s.links.len()];
for &k in &links {
let (a, _, v) = s.links[k];
ends[k][0] = out_at[a];
out_at[a] += v * ky;
}
links.sort_by(|&p, &q| y[s.links[p].0].total_cmp(&y[s.links[q].0]));
for &k in &links {
let (_, b, v) = s.links[k];
ends[k][1] = in_at[b];
in_at[b] += v * ky;
}
for (k, &(a, b, v)) in s.links.iter().enumerate() {
let t = (v * ky).max(0.5);
let (sx, tx) = (x_of(col[a]) + NODE_W, x_of(col[b]));
let mut band = s_curve([sx, ends[k][0]], [tx, ends[k][1]], false);
band.extend(s_curve([tx, ends[k][1] + t], [sx, ends[k][0] + t], false));
c.fill(band, solid(paint, hue(a)).alpha(0.42));
}
for i in 0..n {
let x = x_of(col[i]);
c.fill(vec![[x, y[i]], [x + NODE_W, y[i]], [x + NODE_W, y[i] + h[i]], [x, y[i] + h[i]]], solid(paint, hue(i)));
let m = measure(&format!("{} {}", s.nodes[i], number(f64::from(value[i]))), note);
let mid = y[i] + h[i] / 2.0 - m.size[1] / 2.0;
if col[i] + 1 == cols && cols > 1 {
c.label_at(&m, [x - 6.0 - m.size[0], mid], note, paint.text, Align::End);
} else {
c.label_at(&m, [x + NODE_W + 6.0, mid], note, paint.text, Align::Start);
}
}
c.finish_fit(paint)
}
#[cfg(test)]
#[path = "sankey_tests.rs"]
mod tests;
@@ -0,0 +1,39 @@
use super::*;
fn sankey(src: &str) -> Sankey {
match crate::parse(src).map(|p| p.diagram) {
Some(crate::Diagram::Sankey(s)) => s,
_ => panic!("not a sankey diagram: {src:?}"),
}
}
#[test]
fn rows_read_as_csv() {
let s = sankey(
"sankey-beta\n\nAgricultural 'waste',Bio-conversion,124.729\n\"Bio, conversion\",Liquid,0.597\n\"Say \"\"hi\"\"\",Losses,26.862\nbad row\nA,A,3\nA,B,-1\nA,B,x",
);
assert_eq!(s.nodes, ["Agricultural 'waste'", "Bio-conversion", "Bio, conversion", "Liquid", "Say \"hi\"", "Losses"]);
assert_eq!(s.links.len(), 3, "self links, negative and unreadable values are skipped");
assert_eq!(s.links[2], (4, 5, 26.862));
assert!(crate::parse("sankey-beta\nnot,a number,here").is_none());
let budget = format!("sankey-beta\n{}", (0..MAX_ITEMS).map(|i| format!("a{i},b{i},1")).collect::<Vec<_>>().join("\n"));
assert!(crate::parse(&budget).is_none());
}
#[test]
fn sinks_go_last_and_cycles_stay_bounded() {
let s = sankey("sankey-beta\nA,B,5\nB,C,3\nA,D,2\nC,B,1");
let col = columns(&s);
assert_eq!(col[0], 0);
assert_eq!(col[3], *col.iter().max().unwrap(), "a sink sits in the last column");
assert!(col.iter().all(|&c| c < s.nodes.len()));
}
#[test]
fn flows_run_left_to_right() {
let paint = DiagramStyle::neutral(true);
let s = crate::scene("sankey-beta\nSolar,Grid,10\nWind,Grid,20\nGrid,Homes,30", &paint, None).unwrap();
let at = |t: &str| s.labels.iter().find(|l| l.text.starts_with(t)).unwrap().at;
assert!(at("Solar")[0] < at("Grid")[0] && at("Grid")[0] < at("Homes")[0]);
assert!(s.labels.iter().any(|l| l.text == "Grid 30"), "a node shows its flow");
}
+31
View File
@@ -0,0 +1,31 @@
use super::*;
use crate::canvas::measure;
#[test]
fn ink_reads_on_every_series_fill() {
for dark in [false, true] {
let paint = DiagramStyle::neutral(dark);
for i in 0..12 {
for fill in [solid(&paint, hue(i)), soft(&paint, hue(i))] {
let diff = (ink(fill).to_oklab()[0] - fill.to_oklab()[0]).abs();
assert!(diff > 0.35, "dark={dark} series {i}: {diff}");
}
}
}
}
#[test]
fn axis_labels_stay_inside_and_never_overlap() {
let paint = DiagramStyle::neutral(false);
let mut c = Canvas::default();
let ticks: Vec<(f32, Measured)> = [0.0, 10.0, 60.0, 200.0].iter().map(|&x| (x, measure("2024-01-01", paint.font))).collect();
axis_x(&mut c, &ticks, [0.0, 200.0], [0.0, 100.0], paint.font, &paint);
let xs: Vec<f32> = c.labels.iter().map(|l| l.at[0]).collect();
assert!(c.labels.len() < 4, "the tick at 10 crowds the first: {xs:?}");
for l in &c.labels {
assert!(l.at[0] >= 0.0 && l.at[0] + l.size[0] <= 200.0 + 0.01, "{xs:?}");
}
for w in c.labels.windows(2) {
assert!(w[1].at[0] >= w[0].at[0] + w[0].size[0], "{xs:?}");
}
}
@@ -0,0 +1,185 @@
//! Timelines (`timeline`): time periods left to right with their events stacked under them,
//! grouped and coloured by `section`. Too many periods to fit across run top to bottom instead.
use rune::Align;
use super::{bold, hue, ink, small, soft, solid, strong};
use crate::canvas::{Canvas, Measured, Scene, arrowhead, measure_wrap, room, rounded_rect};
use crate::{DiagramStyle, MAX_ITEMS, clean, word};
#[derive(Debug)]
pub(crate) struct Period {
pub time: String,
pub events: Vec<String>,
pub section: Option<usize>,
}
#[derive(Debug)]
pub(crate) struct Timeline {
pub title: Option<String>,
pub sections: Vec<String>,
pub periods: Vec<Period>,
/// `timeline TD`: top to bottom however many periods there are.
pub down: bool,
}
pub(crate) fn parse(header: &str, body: &[&str]) -> Option<Timeline> {
let mut t = Timeline { title: None, sections: Vec::new(), periods: Vec::new(), down: header.trim() == "TD" || header.trim() == "TB" };
let mut items = 0;
for &l in body {
if let Some(rest) = word(l, "title") {
t.title = Some(clean(rest)).filter(|s| !s.is_empty());
continue;
}
if let Some(rest) = word(l, "section") {
t.sections.push(clean(rest));
items += 1;
continue;
}
if l.starts_with("accTitle") || l.starts_with("accDescr") {
continue;
}
let mut parts = l.split(':').map(clean);
let time = parts.next().unwrap_or_default();
let events: Vec<String> = parts.filter(|e| !e.is_empty()).collect();
items += events.len() + usize::from(!time.is_empty());
if items > MAX_ITEMS {
return None;
}
// `: event` on its own line adds to the period above.
if time.is_empty() {
if let Some(p) = t.periods.last_mut() {
p.events.extend(events);
}
continue;
}
let section = t.sections.len().checked_sub(1);
t.periods.push(Period { time, events, section });
}
(!t.periods.is_empty()).then_some(t)
}
const COL: f32 = 136.0;
const GAP: f32 = 12.0;
const PAD: [f32; 2] = [10.0, 7.0];
/// The hue of period `i`: its section's, or its own when there are none.
fn period_hue(t: &Timeline, i: usize) -> f32 {
hue(t.periods[i].section.unwrap_or(i))
}
pub(crate) fn draw(t: &Timeline, paint: &DiagramStyle) -> Option<Scene> {
let n = t.periods.len() as f32;
if t.down || n * COL + (n - 1.0) * GAP > room(paint) / 0.75 {
return draw_down(t, paint);
}
let head = bold(paint.font);
let note = small(paint);
let inner = COL - 2.0 * PAD[0];
let times: Vec<Measured> = t.periods.iter().map(|p| measure_wrap(&p.time, head, inner)).collect();
let events: Vec<Vec<Measured>> = t.periods.iter().map(|p| p.events.iter().map(|e| measure_wrap(e, note, inner)).collect()).collect();
let titles: Vec<Measured> = t.sections.iter().map(|s| measure_wrap(s, head, 4.0 * COL)).collect();
let x_of = |i: usize| i as f32 * (COL + GAP);
let mut c = Canvas::default();
let mut y = 0.0;
if !t.sections.is_empty() {
let band = titles.iter().map(|m| m.size[1]).fold(0.0, f32::max) + 2.0 * PAD[1];
for (s, m) in titles.iter().enumerate() {
let cols: Vec<usize> = (0..t.periods.len()).filter(|&i| t.periods[i].section == Some(s)).collect();
let (Some(&a), Some(&b)) = (cols.first(), cols.last()) else { continue };
let fill = solid(paint, hue(s));
c.fill(rounded_rect(x_of(a), 0.0, x_of(b) + COL, band, 6.0), fill);
c.label(m, [(x_of(a) + x_of(b) + COL) / 2.0, band / 2.0], head, ink(fill), Align::Center);
}
y = band + 10.0;
}
let box_h = times.iter().map(|m| m.size[1]).fold(0.0, f32::max) + 2.0 * PAD[1];
let line_y = y + box_h + 18.0;
let mut bottom = line_y;
for (i, m) in times.iter().enumerate() {
let h = period_hue(t, i);
let x = x_of(i);
let mut ey = line_y + 18.0;
let boxes: Vec<(f32, f32)> = events[i]
.iter()
.map(|e| {
let top = ey;
ey += e.size[1] + 2.0 * PAD[1] + 8.0;
(top, e.size[1] + 2.0 * PAD[1])
})
.collect();
let end = boxes.last().map_or(line_y, |b| b.0 + b.1 / 2.0);
c.dashed(&[[x + COL / 2.0, y + box_h], [x + COL / 2.0, end]], 1.0, strong(paint, h).alpha(0.6), 4.0, 3.0);
c.shape(rounded_rect(x, y, x + COL, y + box_h, 6.0), soft(paint, h), strong(paint, h), 1.0);
c.label(m, [x + COL / 2.0, y + box_h / 2.0], head, paint.text, Align::Center);
for (e, (top, eh)) in events[i].iter().zip(boxes) {
c.shape(rounded_rect(x + 6.0, top, x + COL - 6.0, top + eh, 5.0), paint.node_fill, strong(paint, h).alpha(0.55), 1.0);
c.label(e, [x + COL / 2.0, top + eh / 2.0], note, paint.text, Align::Center);
bottom = bottom.max(top + eh);
}
}
let right = x_of(t.periods.len() - 1) + COL + 14.0;
c.stroke(vec![[-6.0, line_y], [right - 8.0, line_y]], false, 2.0, paint.line);
c.fill(arrowhead([right, line_y], [1.0, 0.0], 10.0, 9.0), paint.line);
c.finish_fit(paint)
}
/// Periods down a line on the left, each with its events as chips flowing to its right.
fn draw_down(t: &Timeline, paint: &DiagramStyle) -> Option<Scene> {
let head = bold(paint.font);
let note = small(paint);
let times: Vec<Measured> = t.periods.iter().map(|p| measure_wrap(&p.time, head, 140.0)).collect();
let tw = times.iter().map(|m| m.size[0]).fold(0.0, f32::max);
let spine = tw + 18.0;
let x0 = spine + 18.0;
let x1 = room(paint).max(x0 + 160.0);
let mut c = Canvas::default();
let mut y = 0.0;
let mut section = None;
for (i, (p, m)) in t.periods.iter().zip(&times).enumerate() {
if p.section != section
&& let Some(s) = p.section
{
section = Some(s);
let title = measure_wrap(&t.sections[s], head, x1 - 2.0 * PAD[0]);
let band = title.size[1] + 2.0 * PAD[1];
let fill = solid(paint, hue(s));
c.fill(rounded_rect(0.0, y, x1, y + band, 6.0), fill);
c.label_at(&title, [PAD[0], y + PAD[1]], head, ink(fill), Align::Start);
y += band + 10.0;
}
let h = period_hue(t, i);
let chips: Vec<Measured> = p.events.iter().map(|e| measure_wrap(e, note, x1 - x0 - 2.0 * PAD[0])).collect();
let mut at = Vec::new();
let (mut cx, mut cy, mut row_h) = (x0, y, 0.0f32);
for chip in &chips {
let w = chip.size[0] + 2.0 * PAD[0];
if cx > x0 && cx + w > x1 {
cx = x0;
cy += row_h + 6.0;
row_h = 0.0;
}
at.push([cx, cy]);
cx += w + 6.0;
row_h = row_h.max(chip.size[1] + 2.0 * PAD[1]);
}
let row_bottom = (cy + row_h).max(y + m.size[1] + 2.0 * PAD[1]);
let mid = y + (m.size[1] + 2.0 * PAD[1]) / 2.0;
c.label_at(m, [spine - 14.0 - m.size[0], mid - m.size[1] / 2.0], head, paint.text, Align::End);
c.stroke(vec![[spine, y - 5.0], [spine, row_bottom + 5.0]], false, 2.0, paint.line);
c.shape(crate::canvas::ellipse([spine, mid], 5.0, 5.0), solid(paint, h), paint.surface, 2.0);
for (chip, a) in chips.iter().zip(at) {
let w = chip.size[0] + 2.0 * PAD[0];
let ch = chip.size[1] + 2.0 * PAD[1];
c.shape(rounded_rect(a[0], a[1], a[0] + w, a[1] + ch, 5.0), soft(paint, h), strong(paint, h).alpha(0.6), 1.0);
c.label_at(chip, [a[0] + PAD[0], a[1] + PAD[1]], note, paint.text, Align::Start);
}
y = row_bottom + 10.0;
}
c.finish(1.0, paint)
}
#[cfg(test)]
#[path = "timeline_tests.rs"]
mod tests;
@@ -0,0 +1,46 @@
use super::*;
fn timeline(src: &str) -> Timeline {
match crate::parse(src).map(|p| p.diagram) {
Some(crate::Diagram::Timeline(t)) => t,
_ => panic!("not a timeline: {src:?}"),
}
}
#[test]
fn periods_events_and_sections() {
let t = timeline(
"timeline\n title History of Social Media\n 2002 : LinkedIn\n 2004 : Facebook : Google\n : MySpace\n section Later\n 2010 : Instagram\n 2012\n accTitle: skipped",
);
assert_eq!(t.title.as_deref(), Some("History of Social Media"));
assert_eq!(t.sections, ["Later"]);
let got: Vec<(&str, Vec<&str>, Option<usize>)> =
t.periods.iter().map(|p| (p.time.as_str(), p.events.iter().map(String::as_str).collect(), p.section)).collect();
assert_eq!(
got,
[
("2002", vec!["LinkedIn"], None),
("2004", vec!["Facebook", "Google", "MySpace"], None),
("2010", vec!["Instagram"], Some(0)),
("2012", vec![], Some(0)),
]
);
assert!(!t.down);
assert!(timeline("timeline TD\n2020 : a").down);
assert!(crate::parse("timeline\n title Nothing").is_none());
let budget = format!("timeline\n{}", (0..=MAX_ITEMS).map(|i| format!("{i} : e")).collect::<Vec<_>>().join("\n"));
assert!(crate::parse(&budget).is_none());
}
#[test]
fn runs_across_until_it_would_not_fit() {
let paint = DiagramStyle::neutral(false);
let across = crate::scene("timeline\n2001 : a\n2002 : b\n2003 : c", &paint, None).unwrap();
let ys: Vec<f32> = ["2001", "2002", "2003"].iter().map(|t| across.labels.iter().find(|l| l.text == *t).unwrap().at[1]).collect();
assert!(ys.windows(2).all(|w| (w[0] - w[1]).abs() < 0.5), "one row: {ys:?}");
let many = format!("timeline\n{}", (2000..2012).map(|y| format!("{y} : event")).collect::<Vec<_>>().join("\n"));
let down = crate::scene(&many, &paint, None).unwrap();
let y = |t: &str| down.labels.iter().find(|l| l.text == t).unwrap().at[1];
assert!(y("2001") > y("2000") && y("2011") > y("2010"), "top to bottom");
assert!(down.size[0] <= crate::canvas::room(&paint) + 2.01);
}
+256
View File
@@ -0,0 +1,256 @@
//! XY charts (`xychart-beta`, `xychart`): bars and lines over a category or numeric x-axis and a
//! value y-axis, upright or (`horizontal`) on their side.
use rune::Align;
use super::pie::number;
use super::{axis_x, hue, small, solid};
use crate::canvas::{Canvas, Measured, Scene, ellipse, measure, measure_wrap, room};
use crate::{DiagramStyle, MAX_ITEMS, clean_quoted, word};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Kind {
Bar,
Line,
}
#[derive(Debug)]
pub(crate) struct Series {
pub kind: Kind,
pub name: String,
pub values: Vec<f32>,
}
#[derive(Debug, Default)]
pub(crate) struct XyChart {
pub title: Option<String>,
pub horizontal: bool,
pub x_title: String,
/// Category names; empty when the x-axis is a range or not given.
pub bands: Vec<String>,
pub x_range: Option<[f32; 2]>,
pub y_title: String,
pub y_range: Option<[f32; 2]>,
pub series: Vec<Series>,
}
pub(crate) fn parse(header: &str, body: &[&str]) -> Option<XyChart> {
let mut x = XyChart { horizontal: header.trim() == "horizontal", ..XyChart::default() };
let mut items = 0;
for &l in body {
if let Some(rest) = word(l, "title") {
x.title = Some(clean_quoted(rest)).filter(|t| !t.is_empty());
} else if let Some(rest) = word(l, "x-axis") {
let (title, bands, range) = axis(rest);
items += bands.len();
(x.x_title, x.bands, x.x_range) = (title, bands, range);
} else if let Some(rest) = word(l, "y-axis") {
let (title, _, range) = axis(rest);
(x.y_title, x.y_range) = (title, range);
} else if let Some((kind, rest)) = word(l, "bar").map(|r| (Kind::Bar, r)).or_else(|| word(l, "line").map(|r| (Kind::Line, r))) {
let Some(open) = rest.find('[') else { continue };
let values: Option<Vec<f32>> = list(&rest[open..]).iter().map(|v| v.parse::<f32>().ok().filter(|f| f.is_finite())).collect();
let Some(values) = values.filter(|v| !v.is_empty()) else { continue };
items += values.len();
x.series.push(Series { kind, name: clean_quoted(&rest[..open]), values });
}
if items > MAX_ITEMS {
return None;
}
}
(!x.series.is_empty()).then_some(x)
}
/// `"Title" [a, b]`, `Title 0 --> 10`, or a title alone.
fn axis(rest: &str) -> (String, Vec<String>, Option<[f32; 2]>) {
if let Some(open) = rest.find('[') {
return (clean_quoted(&rest[..open]), list(&rest[open..]).iter().map(|s| clean_quoted(s)).collect(), None);
}
if let Some((a, b)) = rest.split_once("-->") {
let a = a.trim();
let (title, lo) = a.rsplit_once(char::is_whitespace).unwrap_or(("", a));
if let (Ok(lo), Ok(hi)) = (lo.parse::<f32>(), b.trim().parse::<f32>())
&& lo.is_finite()
&& hi.is_finite()
&& lo != hi
{
return (clean_quoted(title), Vec::new(), Some([lo.min(hi), lo.max(hi)]));
}
}
(clean_quoted(rest), Vec::new(), None)
}
/// The items of `[a, "b, c", d]`, trimmed.
fn list(s: &str) -> Vec<String> {
let Some(inner) = s.trim().strip_prefix('[').and_then(|r| r.rfind(']').map(|e| &r[..e])) else { return Vec::new() };
if inner.trim().is_empty() {
return Vec::new();
}
let (mut out, mut cur, mut quoted) = (Vec::new(), String::new(), false);
for ch in inner.chars() {
match ch {
'"' => {
quoted = !quoted;
cur.push(ch);
}
',' if !quoted => out.push(std::mem::take(&mut cur)),
_ => cur.push(ch),
}
}
out.push(cur);
out.into_iter().map(|s| s.trim().to_owned()).collect()
}
/// A round step near `raw`: 1, 2 or 5 times a power of ten.
fn nice(raw: f32) -> f32 {
let p = 10f32.powf(raw.max(1e-9).log10().floor());
let m = raw / p;
p * if m <= 1.0 {
1.0
} else if m <= 2.0 {
2.0
} else if m <= 5.0 {
5.0
} else {
10.0
}
}
/// The value axis's ends and ticks: `range` as given, or the data's (taking in zero) rounded out.
pub(crate) fn scale(range: Option<[f32; 2]>, series: &[Series]) -> ([f32; 2], Vec<f32>) {
let [lo, hi] = range.unwrap_or_else(|| {
let (lo, hi) = series.iter().flat_map(|s| &s.values).fold((0.0f32, 0.0f32), |(a, b), &v| (a.min(v), b.max(v)));
let hi = if hi - lo < 1e-9 { lo + 1.0 } else { hi };
let step = nice((hi - lo) / 5.0);
[(lo / step).floor() * step, (hi / step).ceil() * step]
});
let step = nice((hi - lo) / 5.0);
let first = (lo / step).ceil();
let ticks = (0..12)
.map(|k| (first + k as f32) * step)
.take_while(|t| *t <= hi + step * 1e-3)
.map(|t| if t.abs() < step * 1e-3 { 0.0 } else { t })
.collect();
([lo, hi], ticks)
}
const PLOT_H: f32 = 240.0;
pub(crate) fn draw(x: &XyChart, paint: &DiagramStyle) -> Option<Scene> {
let n = x.series.iter().map(|s| s.values.len()).max()?;
let note = small(paint);
let ([lo, hi], ticks) = scale(x.y_range, &x.series);
let names: Vec<String> = match x.x_range {
_ if !x.bands.is_empty() => (0..n).map(|i| x.bands.get(i).cloned().unwrap_or_default()).collect(),
Some([a, b]) => (0..n).map(|i| number(f64::from(a + (b - a) * i as f32 / (n.max(2) - 1) as f32))).collect(),
None => vec![String::new(); n],
};
let mut c = Canvas::default();
let mut top = 0.0;
if x.series.iter().any(|s| !s.name.is_empty()) {
let mut at = 0.0;
let mut h: f32 = 0.0;
for (i, s) in x.series.iter().enumerate() {
let m = measure(&s.name, note);
c.fill(ellipse([at + 5.0, m.size[1] / 2.0], 5.0, 5.0), solid(paint, hue(i)));
c.label_at(&m, [at + 14.0, 0.0], note, paint.muted, Align::Start);
at += 14.0 + m.size[0] + 16.0;
h = h.max(m.size[1]);
}
top = h + 12.0;
}
let value_title = measure(&x.y_title, note);
let band_title = measure(&x.x_title, note);
let values: Vec<(f32, Measured)> = ticks.iter().map(|&t| (t, measure(&number(f64::from(t)), note))).collect();
let v01 = |v: f32| ((v - lo) / (hi - lo)).clamp(0.0, 1.0);
let base = v01(0.0);
// Plot bounds and where a value lands along a band, as `point(u px along the bands, v 0..1)`.
let (x0, y0, x1, y1);
let labels: Vec<Measured>;
if x.horizontal {
labels = names.iter().map(|t| measure_wrap(t, note, 120.0)).collect();
let lw = labels.iter().map(|m| m.size[0]).fold(0.0, f32::max);
let band = (labels.iter().map(|m| m.size[1]).fold(0.0, f32::max) + 10.0).max(26.0);
if !band_title.text.is_empty() {
c.label_at(&band_title, [0.0, top], note, paint.muted, Align::Start);
top += band_title.size[1] + 6.0;
}
(x0, y0) = (if lw > 0.0 { lw + 10.0 } else { 0.0 }, top);
(x1, y1) = ((room(paint)).max(x0 + 200.0), y0 + band * n as f32);
} else {
let vw = values.iter().map(|v| v.1.size[0]).fold(0.0, f32::max);
if !value_title.text.is_empty() {
c.label_at(&value_title, [0.0, top], note, paint.muted, Align::Start);
top += value_title.size[1] + 8.0;
}
(x0, y0) = (vw + 10.0, top);
(x1, y1) = (room(paint).max(x0 + 200.0), top + PLOT_H);
let band = (x1 - x0) / n as f32;
labels = names.iter().map(|t| measure_wrap(t, note, (band - 4.0).max(24.0))).collect();
}
let length = if x.horizontal { y1 - y0 } else { x1 - x0 };
let band = length / n as f32;
let point = |u: f32, v: f32| if x.horizontal { [x0 + v * (x1 - x0), y0 + u] } else { [x0 + u, y1 - v * (y1 - y0)] };
// The value axis: grid lines and tick labels.
if x.horizontal {
let ticks: Vec<(f32, Measured)> = values.iter().map(|(t, m)| (point(0.0, v01(*t))[0], m.clone())).collect();
axis_x(&mut c, &ticks, [x0, x1], [y0, y1], note, paint);
if !value_title.text.is_empty() {
let h = values.iter().map(|v| v.1.size[1]).fold(0.0, f32::max);
c.label(&value_title, [(x0 + x1) / 2.0, y1 + h + 14.0 + value_title.size[1] / 2.0], note, paint.muted, Align::Center);
}
} else {
for (t, m) in &values {
let y = point(0.0, v01(*t))[1];
c.stroke(vec![[x0, y], [x1, y]], false, 1.0, paint.text.alpha(0.08));
c.label_at(m, [x0 - 8.0 - m.size[0], y - m.size[1] / 2.0], note, paint.muted, Align::End);
}
}
let axis_line = [point(0.0, base), point(length, base)];
c.stroke(axis_line.to_vec(), false, 1.0, paint.surface_border);
// Band labels.
for (i, m) in labels.iter().enumerate() {
let mid = (i as f32 + 0.5) * band;
if x.horizontal {
c.label_at(m, [x0 - 10.0 - m.size[0], y0 + mid - m.size[1] / 2.0], note, paint.muted, Align::End);
} else {
c.label_at(m, [x0 + mid - m.size[0] / 2.0, y1 + 6.0], note, paint.muted, Align::Center);
}
}
if !x.horizontal && !band_title.text.is_empty() {
let h = labels.iter().map(|m| m.size[1]).fold(0.0, f32::max);
c.label(&band_title, [(x0 + x1) / 2.0, y1 + h + 14.0 + band_title.size[1] / 2.0], note, paint.muted, Align::Center);
}
// Bars side by side within a band, then lines over them.
let bars: Vec<usize> = (0..x.series.len()).filter(|&i| x.series[i].kind == Kind::Bar).collect();
let group = band * 0.72;
let each = group / bars.len().max(1) as f32;
for (k, &i) in bars.iter().enumerate() {
let fill = solid(paint, hue(i));
for (b, &v) in x.series[i].values.iter().enumerate() {
let u0 = b as f32 * band + (band - group) / 2.0 + k as f32 * each + each * 0.06;
let u1 = u0 + each * 0.88;
let (p, q) = (point(u0, base), point(u1, v01(v)));
let (ax, ay, bx, by) = (p[0].min(q[0]), p[1].min(q[1]), p[0].max(q[0]), p[1].max(q[1]));
c.fill(vec![[ax, ay], [bx, ay], [bx, by], [ax, by]], fill);
}
}
for (i, s) in x.series.iter().enumerate().filter(|(_, s)| s.kind == Kind::Line) {
let color = solid(paint, hue(i));
let pts: Vec<[f32; 2]> = s.values.iter().enumerate().map(|(b, &v)| point((b as f32 + 0.5) * band, v01(v))).collect();
c.stroke(pts.clone(), false, 2.0, color);
for p in pts {
c.shape(ellipse(p, 3.0, 3.0), color, paint.surface, 1.0);
}
}
c.finish_fit(paint)
}
#[cfg(test)]
#[path = "xychart_tests.rs"]
mod tests;
@@ -0,0 +1,54 @@
use super::*;
fn chart(src: &str) -> XyChart {
match crate::parse(src).map(|p| p.diagram) {
Some(crate::Diagram::XyChart(x)) => x,
_ => panic!("not an xy chart: {src:?}"),
}
}
#[test]
fn axes_and_series() {
let x = chart(
"xychart-beta\n title \"Sales Revenue\"\n x-axis [jan, feb, \"mar, apr\", may]\n y-axis \"Revenue (in $)\" 4000 --> 11000\n bar [5000, 6000, 7500, 8200]\n line \"Trend\" [5000, 6000.5, -7500, 8200]\n line [1, two, 3]\n bar oops",
);
assert_eq!(x.title.as_deref(), Some("Sales Revenue"));
assert!(!x.horizontal);
assert_eq!(x.bands, ["jan", "feb", "mar, apr", "may"]);
assert_eq!(x.y_title, "Revenue (in $)");
assert_eq!(x.y_range, Some([4000.0, 11000.0]));
assert_eq!(x.series.len(), 2, "series that don't read are skipped");
assert_eq!((x.series[1].kind, x.series[1].name.as_str()), (Kind::Line, "Trend"));
assert_eq!(x.series[1].values[2], -7500.0);
let h = chart("xychart-beta horizontal\n x-axis \"Score\" 10 --> 0\n y-axis Votes\n bar [3, 5]");
assert!(h.horizontal);
assert_eq!((h.x_title.as_str(), h.x_range), ("Score", Some([0.0, 10.0])));
assert_eq!((h.y_title.as_str(), h.y_range), ("Votes", None));
assert!(crate::parse("xychart-beta\n title Nothing\n x-axis [a, b]").is_none());
let budget = format!("xychart-beta\n bar [{}]", vec!["1"; MAX_ITEMS + 1].join(", "));
assert!(crate::parse(&budget).is_none());
}
#[test]
fn the_value_axis_rounds_out_and_takes_in_zero() {
let series = |v: &[f32]| vec![Series { kind: Kind::Bar, name: String::new(), values: v.to_vec() }];
assert_eq!(scale(None, &series(&[3.0, 47.0])), ([0.0, 50.0], vec![0.0, 10.0, 20.0, 30.0, 40.0, 50.0]));
let ([lo, hi], ticks) = scale(None, &series(&[-12.0, 30.0]));
assert!(lo <= -12.0 && hi >= 30.0 && ticks.contains(&0.0));
assert_eq!(scale(Some([4000.0, 11000.0]), &series(&[5000.0])).1.first(), Some(&4000.0));
}
#[test]
fn bars_rise_with_their_values_upright_and_on_their_side() {
let paint = DiagramStyle::neutral(false);
for (src, horizontal) in [("xychart-beta\nx-axis [low, high]\nbar [1, 9]", false), ("xychart-beta horizontal\nx-axis [low, high]\nbar [1, 9]", true)] {
let s = crate::scene(src, &paint, None).unwrap();
let at = |t: &str| s.labels.iter().find(|l| l.text == t).unwrap().at;
if horizontal {
assert!(at("low")[1] < at("high")[1], "bands run down");
} else {
assert!(at("low")[0] < at("high")[0], "bands run across");
}
}
}
+417
View File
@@ -0,0 +1,417 @@
//! Block diagrams (`block-beta`, `block`): blocks in rows of `columns`, spanning cells with
//! `id:2`, gaps from `space`, nested `block … end` groups, block arrows `id<["label"]>(right)`,
//! and edges between blocks, laid out on a grid rather than by rank.
use std::collections::HashMap;
use rune::Align;
use super::flowchart::{ident, link, shape};
use crate::canvas::shape as shapes;
use crate::canvas::{Canvas, Measured, Scene, measure_wrap, rounded_rect, unit};
use crate::layout::connector::{connector, inset, label_box};
use crate::layout::draw::{Edge, NodeShape, boundary, node_size};
use crate::{Cur, DiagramStyle, EdgeStyle, MAX_DEPTH, MAX_ITEMS, NodeStyle, StyleSheet, clean_quoted, statements, word};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Point {
Right,
Left,
Up,
Down,
/// Both ways across.
X,
/// Both ways up and down.
Y,
}
#[derive(Debug, PartialEq)]
pub(crate) enum Kind {
Node,
Space,
Arrow(Point),
Group { columns: Option<usize>, children: Vec<usize> },
}
#[derive(Debug)]
pub(crate) struct Block {
#[cfg_attr(not(test), allow(dead_code, reason = "tests find blocks by id"))]
pub id: String,
pub label: String,
pub shape: NodeShape,
pub span: usize,
pub kind: Kind,
pub style: NodeStyle,
}
/// Block 0 is the diagram itself: a group that isn't drawn.
#[derive(Debug)]
pub(crate) struct BlockDiagram {
pub blocks: Vec<Block>,
pub edges: Vec<Edge>,
}
struct Item {
id: String,
label: Option<String>,
shape: Option<NodeShape>,
arrow: Option<Point>,
span: usize,
}
struct Parser {
d: BlockDiagram,
ids: HashMap<String, usize>,
stack: Vec<usize>,
styles: StyleSheet,
over: bool,
}
pub(crate) fn parse(body: &[&str]) -> Option<BlockDiagram> {
let root = Block { id: String::new(), label: String::new(), shape: NodeShape::Rect, span: 1, kind: Kind::Group { columns: None, children: Vec::new() }, style: NodeStyle::default() };
let mut p = Parser {
d: BlockDiagram { blocks: vec![root], edges: Vec::new() },
ids: HashMap::new(),
stack: vec![0],
styles: StyleSheet::default(),
over: false,
};
for &line in body {
for s in statements(line) {
p.statement(s);
if p.over {
return None;
}
}
}
let Parser { mut d, ids, styles, .. } = p;
for (id, i) in ids {
d.blocks[i].style = styles.get(&id);
}
(d.blocks.len() > 1).then_some(d)
}
impl Parser {
fn budget(&mut self) -> Option<()> {
self.over |= self.d.blocks.len() + self.d.edges.len() >= MAX_ITEMS;
(!self.over).then_some(())
}
fn group(&mut self) -> usize {
*self.stack.last().unwrap_or(&0)
}
fn statement(&mut self, s: &str) -> Option<()> {
if let Some(rest) = word(s, "columns") {
let n = rest.parse::<usize>().ok().map(|n| n.clamp(1, 24));
let g = self.group();
if let Kind::Group { columns, .. } = &mut self.d.blocks[g].kind {
*columns = n;
}
} else if s == "end" {
if self.stack.len() > 1 {
self.stack.pop();
}
} else if s == "block" || s.starts_with("block:") {
let mut parts = s["block".len()..].trim_start_matches(':').split(':');
let id = parts.next().unwrap_or("").trim();
let span = parts.next().and_then(|n| n.trim().parse::<usize>().ok()).unwrap_or(1).clamp(1, 24);
if self.stack.len() > MAX_DEPTH {
self.over = true;
return None;
}
let i = self.add(Item { id: id.to_owned(), label: Some(String::new()), shape: None, arrow: None, span })?;
self.d.blocks[i].kind = Kind::Group { columns: None, children: Vec::new() };
self.stack.push(i);
} else if let Some(rest) = word(s, "classDef") {
self.styles.class_def(rest)?;
} else if let Some(rest) = word(s, "class") {
self.styles.assign_classes(rest)?;
} else if let Some(rest) = word(s, "style") {
self.styles.style(rest)?;
} else if self.edges(s).is_none() {
self.items(s)?;
}
Some(())
}
/// `a --> b -- "label" --> c`, read whole first so a line that isn't one adds nothing.
fn edges(&mut self, s: &str) -> Option<()> {
let mut c = Cur::new(s);
let mut refs = vec![item(&mut c)?];
let mut links = Vec::new();
loop {
c.skip_ws();
if c.done() {
break;
}
links.push(link(&mut c)?);
c.skip_ws();
refs.push(item(&mut c)?);
}
if links.is_empty() {
return None;
}
let ends: Vec<usize> = refs.into_iter().map(|r| self.add(r)).collect::<Option<_>>()?;
for (l, w) in links.into_iter().zip(ends.windows(2)) {
self.budget()?;
self.d.edges.push(Edge { from: w[0], to: w[1], label: l.label, line: l.line, start: l.start, end: l.end, minlen: 1, style: EdgeStyle::default(), on_cluster: [None; 2] });
}
Some(())
}
/// `a b["label"]:2 space c`, read whole first.
fn items(&mut self, s: &str) -> Option<()> {
let mut c = Cur::new(s);
let mut items = Vec::new();
loop {
c.skip_ws();
if c.done() {
break;
}
items.push(item(&mut c)?);
}
for it in items {
self.add(it)?;
}
Some(())
}
/// A block placed in the open group, or the one `id` already names (taking a new label or shape).
fn add(&mut self, it: Item) -> Option<usize> {
if let Some(&i) = self.ids.get(&it.id) {
let b = &mut self.d.blocks[i];
if let Some(l) = it.label {
b.label = l;
}
if let Some(s) = it.shape {
b.shape = s;
}
return Some(i);
}
self.budget()?;
let kind = match it.arrow {
_ if it.id == "space" => Kind::Space,
Some(p) => Kind::Arrow(p),
None => Kind::Node,
};
let label = it.label.unwrap_or_else(|| it.id.clone());
let i = self.d.blocks.len();
if kind != Kind::Space && !it.id.is_empty() {
self.ids.insert(it.id.clone(), i);
}
self.d.blocks.push(Block { id: it.id, label, shape: it.shape.unwrap_or(NodeShape::Rect), span: it.span, kind, style: NodeStyle::default() });
let g = self.group();
if let Kind::Group { children, .. } = &mut self.d.blocks[g].kind {
children.push(i);
}
Some(i)
}
}
/// `id`, `id["label"]`, `id(round)`, `id<["label"]>(right)`, each with an optional `:span`.
fn item(c: &mut Cur) -> Option<Item> {
let id = ident(c)?;
let (mut label, mut shape_of, mut arrow) = (None, None, None);
if c.eat("<[") {
let end = c.rest().find("]>")?;
label = Some(clean_quoted(&c.rest()[..end]));
c.i += end + 2;
let dir = c.rest().strip_prefix('(').and_then(|r| r.find(')').map(|e| &r[..e]))?;
c.i += dir.len() + 2;
arrow = Some(match dir.trim() {
"right" => Point::Right,
"left" => Point::Left,
"up" => Point::Up,
"down" => Point::Down,
"x" => Point::X,
"y" => Point::Y,
_ => return None,
});
} else if let Some((l, s)) = shape(c) {
(label, shape_of) = (l, Some(s));
}
let mut span = 1;
if c.peek() == Some(':') && c.peek2().is_some_and(|d| d.is_ascii_digit()) {
c.bump();
let start = c.i;
while c.peek().is_some_and(|d| d.is_ascii_digit()) {
c.bump();
}
span = c.s[start..c.i].parse::<usize>().ok()?.clamp(1, 24);
}
Some(Item { id, label, shape: shape_of, arrow, span })
}
const GAP: f32 = 10.0;
const PAD: f32 = 10.0;
/// The gap between rows when edges run between blocks, so an arrow and its label show.
const EDGE_GAP: f32 = 40.0;
/// Each group's rows: the children in it with the column each starts at.
fn rows(d: &BlockDiagram, g: usize) -> (usize, Vec<Vec<(usize, usize)>>) {
let Kind::Group { columns, children } = &d.blocks[g].kind else { return (1, Vec::new()) };
let cols = columns.unwrap_or_else(|| children.iter().map(|&k| d.blocks[k].span).sum::<usize>()).max(1);
let mut out: Vec<Vec<(usize, usize)>> = vec![Vec::new()];
let mut at = 0;
for &k in children {
let span = d.blocks[k].span.min(cols);
if at > 0 && at + span > cols {
out.push(Vec::new());
at = 0;
}
if let Some(row) = out.last_mut() {
row.push((k, at));
}
at += span;
}
(cols, out)
}
struct Layout<'a> {
d: &'a BlockDiagram,
labels: Vec<Measured>,
natural: Vec<[f32; 2]>,
rects: Vec<[f32; 4]>,
/// The gap between rows.
row_gap: f32,
}
impl Layout<'_> {
fn pad(g: usize) -> f32 {
if g == 0 { 0.0 } else { PAD }
}
fn measure(&mut self, i: usize) -> [f32; 2] {
let m = &self.labels[i];
let size = match &self.d.blocks[i].kind {
Kind::Space => [0.0, 0.0],
Kind::Node => node_size(self.d.blocks[i].shape, m.size),
Kind::Arrow(Point::Up | Point::Down | Point::Y) => [m.size[0] + 40.0, m.size[1] + 56.0],
Kind::Arrow(_) => [m.size[0] + 64.0, m.size[1] + 36.0],
Kind::Group { .. } => {
let (cols, rows) = rows(self.d, i);
let mut cell: f32 = 0.0;
let mut height = 0.0;
for row in &rows {
let mut tall: f32 = 0.0;
for &(k, _) in row {
let s = self.measure(k);
let span = self.d.blocks[k].span.min(cols) as f32;
cell = cell.max((s[0] - (span - 1.0) * GAP) / span);
tall = tall.max(s[1]);
}
height += tall;
}
let pad = Self::pad(i);
[cols as f32 * cell + (cols as f32 - 1.0) * GAP + 2.0 * pad, height + (rows.len() as f32 - 1.0).max(0.0) * self.row_gap + 2.0 * pad]
}
};
self.natural[i] = size;
size
}
fn place(&mut self, i: usize, r: [f32; 4]) {
self.rects[i] = r;
if !matches!(self.d.blocks[i].kind, Kind::Group { .. }) {
return;
}
let (cols, rows) = rows(self.d, i);
let pad = Self::pad(i);
let cell = (r[2] - 2.0 * pad - (cols as f32 - 1.0) * GAP) / cols as f32;
let mut y = r[1] + pad + (r[3] - self.natural[i][1]).max(0.0) / 2.0;
for row in rows {
let tall = row.iter().map(|&(k, _)| self.natural[k][1]).fold(0.0, f32::max);
for (k, at) in row {
let span = self.d.blocks[k].span.min(cols) as f32;
let x = r[0] + pad + at as f32 * (cell + GAP);
self.place(k, [x, y, span * cell + (span - 1.0) * GAP, tall]);
}
y += tall + self.row_gap;
}
}
/// Where block `i` is drawn: its centre and size.
fn frame(&self, i: usize) -> ([f32; 2], [f32; 2]) {
let [x, y, w, h] = self.rects[i];
let n = self.natural[i];
let size = match self.d.blocks[i].kind {
Kind::Group { .. } => [w, h],
Kind::Arrow(_) => n,
_ if matches!(self.d.blocks[i].shape, NodeShape::Circle | NodeShape::DoubleCircle) => n,
_ => [w, n[1]],
};
([x + w / 2.0, y + h / 2.0], size)
}
}
pub(crate) fn draw(d: &BlockDiagram, paint: &DiagramStyle) -> Option<Scene> {
let n = d.blocks.len();
let mut l = Layout { d, labels: d.blocks.iter().map(|b| measure_wrap(&b.label, paint.font, 180.0)).collect(), natural: vec![[0.0; 2]; n], rects: vec![[0.0; 4]; n], row_gap: if d.edges.is_empty() { GAP } else { EDGE_GAP } };
let [w, h] = l.measure(0);
l.place(0, [0.0, 0.0, w, h]);
let mut c = Canvas::default();
let group_border = crate::canvas::group_border(paint);
for i in 1..n {
if matches!(d.blocks[i].kind, Kind::Group { .. }) {
let [x, y, w, h] = l.rects[i];
let fill = d.blocks[i].style.fill.map_or(paint.cluster_fill, |_| d.blocks[i].style.resolve(paint).0);
c.shape(rounded_rect(x, y, x + w, y + h, 6.0), fill, group_border, 1.0);
}
}
let edge_font = crate::chart::small(paint);
for e in &d.edges {
let ((ca, sa), (cb, sb)) = (l.frame(e.from), l.frame(e.to));
let outline = |i: usize| if matches!(d.blocks[i].kind, Kind::Node) { d.blocks[i].shape } else { NodeShape::Rect };
let (pa, pb) = (boundary(outline(e.from), ca, sa, cb), boundary(outline(e.to), cb, sb, ca));
let u = unit(pa, pb);
let (a, b) = ([pa[0] + u[0] * inset(e.start), pa[1] + u[1] * inset(e.start)], [pb[0] - u[0] * inset(e.end), pb[1] - u[1] * inset(e.end)]);
connector(&mut c, &[vec![a, b]], [(pa, [-u[0], -u[1]]), (pb, u)], e, paint);
if let Some(text) = &e.label {
let m = measure_wrap(text, edge_font, 160.0);
let mid = [(pa[0] + pb[0]) / 2.0, (pa[1] + pb[1]) / 2.0];
let s = label_box(&m);
c.fill(rounded_rect(mid[0] - s[0] / 2.0, mid[1] - s[1] / 2.0, mid[0] + s[0] / 2.0, mid[1] + s[1] / 2.0, 4.0), paint.surface);
c.label(&m, mid, edge_font, paint.text, Align::Center);
}
}
for (i, b) in d.blocks.iter().enumerate().skip(1) {
let (ctr, size) = l.frame(i);
let colors = b.style.resolve(paint);
match b.kind {
Kind::Node => shapes::draw(&mut c, b.shape, &l.labels[i], ctr, size, colors.into(), paint),
Kind::Arrow(p) => {
c.shape(arrow(p, ctr, size), colors.0, colors.1, 1.0);
c.label(&l.labels[i], ctr, paint.font, colors.2, Align::Center);
}
Kind::Space | Kind::Group { .. } => {}
}
}
c.finish_fit(paint)
}
/// A block arrow's outline: a shaft with a head at one end (or both, for `x` and `y`).
fn arrow(p: Point, ctr: [f32; 2], size: [f32; 2]) -> Vec<[f32; 2]> {
let upright = matches!(p, Point::Up | Point::Down | Point::Y);
let (len, thick) = if upright { (size[1], size[0]) } else { (size[0], size[1]) };
let (hl, ht) = (len / 2.0, thick / 2.0);
let head = (thick * 0.55).min(len * 0.4);
let shaft = ht * 0.62;
let both = matches!(p, Point::X | Point::Y);
let back = if both { -hl + head } else { -hl };
let mut pts = vec![[back, -shaft], [hl - head, -shaft], [hl - head, -ht], [hl, 0.0], [hl - head, ht], [hl - head, shaft], [back, shaft]];
if both {
pts.extend([[back, ht], [-hl, 0.0], [back, -ht]]);
}
let flip = matches!(p, Point::Left | Point::Up);
pts.into_iter()
.map(|[u, v]| {
let u = if flip { -u } else { u };
if upright { [ctr[0] + v, ctr[1] + u] } else { [ctr[0] + u, ctr[1] + v] }
})
.collect()
}
#[cfg(test)]
#[path = "block_tests.rs"]
mod tests;
@@ -0,0 +1,47 @@
use super::*;
fn blocks(src: &str) -> BlockDiagram {
match crate::parse(src).map(|p| p.diagram) {
Some(crate::Diagram::Block(b)) => b,
_ => panic!("not a block diagram: {src:?}"),
}
}
fn find<'a>(d: &'a BlockDiagram, id: &str) -> &'a Block {
d.blocks.iter().find(|b| b.id == id).unwrap()
}
#[test]
fn rows_spans_groups_and_arrows() {
let d = blocks(
"block-beta\n columns 3\n a[\"Front end\"] b:2\n space c((DB))\n block:back:2\n columns 2\n d e\n end\n f<[\"go\"]>(right)\n a --> b\n b -- \"calls\" --> c\n style a fill:#f96\n classDef hot stroke:#f00\n class c hot\n g[unclosed",
);
assert_eq!(d.blocks[0].kind, Kind::Group { columns: Some(3), children: vec![1, 2, 3, 4, 5, 8, 9] });
assert_eq!(find(&d, "a").label, "Front end");
assert_eq!(find(&d, "b").span, 2);
assert_eq!(d.blocks[3].kind, Kind::Space);
assert_eq!(find(&d, "c").shape, NodeShape::Circle);
assert_eq!(find(&d, "back").kind, Kind::Group { columns: Some(2), children: vec![6, 7] });
assert_eq!(find(&d, "f").kind, Kind::Arrow(Point::Right));
assert_eq!(find(&d, "g").label, "unclosed", "an unclosed shape keeps its text");
assert_eq!(d.edges.len(), 2);
assert_eq!(d.edges[1].label.as_deref(), Some("calls"));
assert!(find(&d, "a").style.fill.is_some() && find(&d, "c").style.stroke.is_some());
assert!(crate::parse("block-beta\n columns 2").is_none());
let deep = format!("block-beta\n{}x\n", "block\n".repeat(MAX_DEPTH + 1));
assert!(crate::parse(&deep).is_none());
let budget = format!("block-beta\n{}", (0..MAX_ITEMS).map(|i| format!("b{i}")).collect::<Vec<_>>().join(" "));
assert!(crate::parse(&budget).is_none());
}
#[test]
fn blocks_wrap_at_their_columns() {
let paint = DiagramStyle::neutral(false);
let s = crate::scene("block-beta\ncolumns 2\nOne Two\nThree", &paint, None).unwrap();
let at = |t: &str| s.labels.iter().find(|l| l.text == t).unwrap().at;
assert!(at("One")[0] < at("Two")[0] && (at("One")[1] - at("Two")[1]).abs() < 1.0);
assert!(at("Three")[1] > at("One")[1] + 10.0, "the third block starts a new row");
let auto = crate::scene("block\nOne Two Three", &paint, None).unwrap();
let ys: Vec<f32> = auto.labels.iter().map(|l| l.at[1]).collect();
assert!(ys.iter().all(|y| (y - ys[0]).abs() < 1.0), "without columns, one row");
}
+281
View File
@@ -0,0 +1,281 @@
//! C4 diagrams (`C4Context`, `C4Container`, `C4Component`, `C4Dynamic`, `C4Deployment`), laid
//! out on [`crate::layout::draw`]: people, systems, containers and components as cards (stores as
//! cylinders, queues on their side, external ones in grey), boundaries and deployment nodes as
//! nested frames, and relationships with their technology.
use std::collections::HashMap;
use rune::{Color, TextStyle, oklch};
use crate::canvas::{Scene, measure_wrap};
use crate::chart::{bold, ink, small};
use crate::layout::draw::{ClusterSpec, Dir, DrawNode, Edge, Head, Line, NodeShape, PERSON, draw_layered};
use crate::layout::layered::Spacing;
use crate::{DiagramStyle, EdgeStyle, Hover, MAX_DEPTH, MAX_ITEMS, clean_quoted, word};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Base {
Person,
System,
Container,
Component,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Store {
Plain,
Db,
Queue,
}
#[derive(Debug)]
pub(crate) struct Element {
pub base: Base,
pub store: Store,
pub external: bool,
pub label: String,
pub techn: String,
pub descr: String,
pub boundary: Option<usize>,
}
#[derive(Debug)]
pub(crate) struct Boundary {
pub title: String,
pub parent: Option<usize>,
}
#[derive(Debug, Default)]
pub(crate) struct C4 {
pub title: Option<String>,
pub elements: Vec<Element>,
pub boundaries: Vec<Boundary>,
pub edges: Vec<Edge>,
}
struct Rel {
from: String,
to: String,
label: String,
techn: String,
both: bool,
way: Way,
}
/// Which way a relationship's arrow points, and so which end the layout puts above.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Way {
Down,
/// `Rel_U`: toward `to`, which sits above.
Up,
/// `Rel_Back`: toward `from`.
Back,
}
pub(crate) fn parse(header: &str, body: &[&str]) -> Option<C4> {
let dynamic = header == "C4Dynamic";
let mut d = C4::default();
let mut ids: HashMap<String, usize> = HashMap::new();
let mut rels: Vec<Rel> = Vec::new();
let mut stack: Vec<usize> = Vec::new();
for &l in body {
if l.starts_with('}') {
stack.pop();
continue;
}
if let Some(rest) = word(l, "title") {
d.title = Some(clean_quoted(rest)).filter(|t| !t.is_empty());
continue;
}
let Some((open, close)) = l.find('(').zip(l.rfind(')')).filter(|(o, c)| o < c) else { continue };
let name = l[..open].trim();
let (args, named) = args(&l[open + 1..close]);
let arg = |i: usize| args.get(i).cloned().unwrap_or_default();
if let Some(kind) = boundary(name) {
if stack.len() >= MAX_DEPTH {
return None;
}
let ty = args.get(2).cloned().filter(|t| !t.is_empty()).or_else(|| kind.map(str::to_owned));
let label = args.get(1).or(args.first()).cloned().unwrap_or_default();
let title = match ty {
Some(t) => format!("{label}\n[{t}]"),
None => label,
};
d.boundaries.push(Boundary { title, parent: stack.last().copied() });
if l[close + 1..].trim_start().starts_with('{') {
stack.push(d.boundaries.len() - 1);
}
} else if let Some((base, store, external)) = element(name) {
let Some(alias) = args.first().filter(|a| !a.is_empty()) else { continue };
let (techn, descr) = if matches!(base, Base::Container | Base::Component) { (arg(2), arg(3)) } else { (String::new(), arg(2)) };
let techn = named.get("techn").cloned().unwrap_or(techn);
let descr = named.get("descr").cloned().unwrap_or(descr);
ids.insert(alias.clone(), d.elements.len());
d.elements.push(Element { base, store, external, label: arg(1), techn, descr, boundary: stack.last().copied() });
} else if let Some((both, way, indexed)) = relation(name) {
let a = if indexed { &args[args.len().min(1)..] } else { &args[..] };
let get = |i: usize| a.get(i).cloned().unwrap_or_default();
let techn = named.get("techn").cloned().unwrap_or_else(|| get(3));
rels.push(Rel { from: get(0), to: get(1), label: get(2), techn, both, way });
}
if d.elements.len() + d.boundaries.len() + rels.len() > MAX_ITEMS {
return None;
}
}
let mut n = 0;
for r in rels {
let (Some(&a), Some(&b)) = (ids.get(&r.from), ids.get(&r.to)) else { continue };
n += 1;
let mut label = if dynamic { format!("{n}: {}", r.label) } else { r.label };
if !r.techn.is_empty() {
label = format!("{label}\n[{}]", r.techn);
}
let other = if r.both { Head::Arrow } else { Head::None };
let (from, to, start, end) = match r.way {
Way::Down => (a, b, other, Head::Arrow),
Way::Up => (b, a, Head::Arrow, other),
Way::Back => (a, b, Head::Arrow, other),
};
let label = Some(label).filter(|l| !l.trim().is_empty());
d.edges.push(Edge { from, to, label, line: Line::Solid, start, end, minlen: 1, style: EdgeStyle::default(), on_cluster: [None; 2] });
}
(!d.elements.is_empty()).then_some(d)
}
/// Positional arguments, unquoted, and `$name="value"` ones by name.
fn args(s: &str) -> (Vec<String>, HashMap<String, String>) {
let (mut parts, mut cur, mut quoted) = (Vec::new(), String::new(), false);
for ch in s.chars() {
match ch {
'"' => {
quoted = !quoted;
cur.push(ch);
}
',' if !quoted => parts.push(std::mem::take(&mut cur)),
_ => cur.push(ch),
}
}
parts.push(cur);
let (mut pos, mut named) = (Vec::new(), HashMap::new());
for p in parts {
let p = p.trim();
match p.strip_prefix('$').and_then(|r| r.split_once('=')) {
Some((k, v)) => {
named.insert(k.trim().to_owned(), clean_quoted(v));
}
None if !p.starts_with('$') => pos.push(clean_quoted(p)),
None => {}
}
}
(pos, named)
}
/// A boundary function, with the type it shows when none is given.
fn boundary(name: &str) -> Option<Option<&'static str>> {
Some(match name {
"Boundary" | "Deployment_Node" | "Node" | "Node_L" | "Node_R" => None,
"Enterprise_Boundary" => Some("Enterprise"),
"System_Boundary" => Some("System"),
"Container_Boundary" => Some("Container"),
_ => return None,
})
}
/// `Person`, `SystemDb_Ext`, `ContainerQueue`, …
fn element(name: &str) -> Option<(Base, Store, bool)> {
let (name, external) = name.strip_suffix("_Ext").map_or((name, false), |n| (n, true));
let (base, rest) = [("Person", Base::Person), ("System", Base::System), ("Container", Base::Container), ("Component", Base::Component)]
.into_iter()
.find_map(|(w, b)| name.strip_prefix(w).map(|r| (b, r)))?;
let store = match rest {
"" => Store::Plain,
"Db" if base != Base::Person => Store::Db,
"Queue" if base != Base::Person => Store::Queue,
_ => return None,
};
Some((base, store, external))
}
/// `Rel`, `BiRel`, `Rel_Back`, `Rel_U`, `RelIndex`, …: whether it points both ways, which way,
/// and whether an index comes first.
fn relation(name: &str) -> Option<(bool, Way, bool)> {
let (both, rest) = match name.strip_prefix("BiRel") {
Some(r) => (true, r),
None => (false, name.strip_prefix("Rel")?),
};
match rest {
"Index" => Some((both, Way::Down, true)),
"_Back" => Some((both, Way::Back, false)),
"_U" | "_Up" => Some((both, Way::Up, false)),
"" | "_D" | "_Down" | "_L" | "_Left" | "_R" | "_Right" | "_Neighbor" => Some((both, Way::Down, false)),
_ => None,
}
}
/// `«external_system_db»` and the like.
fn stereotype(e: &Element) -> String {
let base = match e.base {
Base::Person => "person",
Base::System => "system",
Base::Container => "container",
Base::Component => "component",
};
let store = match e.store {
Store::Plain => "",
Store::Db => "_db",
Store::Queue => "_queue",
};
format!("«{}{base}{store}»", if e.external { "external_" } else { "" })
}
/// C4's blues, deepest for people; external elements in grey.
fn fill(e: &Element) -> Color {
let l = match (e.base, e.external) {
(Base::Person, true) => 0.46,
(_, true) => 0.64,
(Base::Person, false) => 0.36,
(Base::System, false) => 0.48,
(Base::Container, false) => 0.6,
(Base::Component, false) => 0.76,
};
if e.external { oklch(l, 0.0, 0.0) } else { oklch(l, 0.11 - (l - 0.36) * 0.12, 252.0) }
}
const SPACING: Spacing = Spacing { node: 44.0, rank: 64.0, cluster: 20.0 };
pub(crate) fn draw(d: &C4, paint: &DiagramStyle, hover: Option<(Hover, Color)>) -> Option<Scene> {
let note = small(paint);
let fonts: [TextStyle; 3] = [TextStyle { italic: true, ..small(paint) }, bold(paint.font), TextStyle { italic: true, ..note }];
let nodes: Vec<DrawNode> = d
.elements
.iter()
.map(|e| {
let techn = (!e.techn.is_empty()).then(|| format!("[{}]", e.techn)).unwrap_or_default();
let lines: Vec<_> = [(stereotype(e), fonts[0]), (e.label.clone(), fonts[1]), (techn, fonts[2]), (e.descr.clone(), note)]
.into_iter()
.filter(|(t, _)| !t.is_empty())
.map(|(t, f)| (measure_wrap(&t, f, 190.0), f))
.collect();
let shape = match e.store {
Store::Plain => NodeShape::Round,
Store::Db => NodeShape::Cylinder,
Store::Queue => NodeShape::HCylinder,
};
let w = lines.iter().map(|l| l.0.size[0]).fold(0.0, f32::max) + if shape == NodeShape::HCylinder { 52.0 } else { 32.0 };
let person = e.base == Base::Person;
let mut h = lines.iter().map(|l| l.0.size[1] + 3.0).sum::<f32>() + 22.0 + if person { PERSON } else { 0.0 };
if shape == NodeShape::Cylinder {
h += 3.0 * crate::canvas::shape::rim(w.max(150.0));
}
let f = fill(e);
let border = oklch((f.to_oklab()[0] - 0.1).max(0.2), 0.06, 252.0);
DrawNode::Card { shape, lines, size: [w.max(150.0), h.max(64.0)], cluster: e.boundary, colors: [f, border, ink(f)], person }
})
.collect();
let clusters: Vec<ClusterSpec> = d.boundaries.iter().map(|b| ClusterSpec { title: b.title.clone(), parent: b.parent }).collect();
draw_layered(Dir::Down, &nodes, &d.edges, &clusters, &SPACING, paint, hover)
}
#[cfg(test)]
#[path = "c4_tests.rs"]
mod tests;
@@ -0,0 +1,68 @@
use super::*;
fn c4(src: &str) -> C4 {
match crate::parse(src).map(|p| p.diagram) {
Some(crate::Diagram::C4(c)) => c,
_ => panic!("not a C4 diagram: {src:?}"),
}
}
#[test]
fn elements_boundaries_and_relationships() {
let d = c4(r#"C4Context
title System Context diagram for Internet Banking System
Enterprise_Boundary(b0, "BankBoundary0") {
Person(customerA, "Banking Customer A", "A customer of the bank, with personal bank accounts.")
System(SystemAA, "Internet Banking System", "Allows customers to view information.", $tags="v1.0")
Boundary(b1, "BankBoundary", "boundary") {
SystemDb_Ext(SystemE, "Mainframe Banking System", "Stores all of the core banking information.")
}
}
ContainerQueue(q, "Events", "Kafka", "Domain events")
Person_Ext(other, "Visitor")
Rel(customerA, SystemAA, "Uses")
BiRel(SystemAA, SystemE, "Uses", "XML/HTTPS")
Rel_Back(q, SystemAA, "Feeds")
Rel_U(other, customerA, "Asks")
Rel(customerA, nobody, "Lost")
UpdateLayoutConfig($c4ShapeInRow="3", $c4BoundaryInRow="1")"#);
assert_eq!(d.title.as_deref(), Some("System Context diagram for Internet Banking System"));
let labels: Vec<&str> = d.elements.iter().map(|e| e.label.as_str()).collect();
assert_eq!(labels, ["Banking Customer A", "Internet Banking System", "Mainframe Banking System", "Events", "Visitor"]);
assert_eq!(d.boundaries.len(), 2);
assert_eq!((d.boundaries[0].title.as_str(), d.boundaries[1].parent), ("BankBoundary0\n[Enterprise]", Some(0)));
assert_eq!((d.elements[0].boundary, d.elements[2].boundary, d.elements[3].boundary), (Some(0), Some(1), None));
assert_eq!((d.elements[2].store, d.elements[2].external), (Store::Db, true));
assert_eq!((d.elements[3].techn.as_str(), d.elements[3].descr.as_str()), ("Kafka", "Domain events"));
assert_eq!(stereotype(&d.elements[2]), "«external_system_db»");
assert_eq!(d.edges.len(), 4, "a relationship to an unknown alias is skipped");
assert_eq!(d.edges[1].label.as_deref(), Some("Uses\n[XML/HTTPS]"));
assert_eq!((d.edges[1].start, d.edges[1].end), (Head::Arrow, Head::Arrow));
assert_eq!((d.edges[2].from, d.edges[2].start, d.edges[2].end), (3, Head::Arrow, Head::None), "`Rel_Back` points at its first alias");
assert_eq!((d.edges[3].from, d.edges[3].to, d.edges[3].start), (0, 4, Head::Arrow), "`Rel_U` puts its target above");
assert!(crate::parse("C4Context\n title Empty").is_none());
}
#[test]
fn dynamic_diagrams_number_their_steps() {
let d = c4("C4Dynamic\n Container(a, \"App\")\n ContainerDb(b, \"DB\")\n RelIndex(1, a, b, \"Reads\")\n Rel(b, a, \"Rows\")");
let labels: Vec<_> = d.edges.iter().map(|e| e.label.clone().unwrap()).collect();
assert_eq!(labels, ["1: Reads", "2: Rows"]);
let deep = format!("C4Deployment\n{}Node(x, \"X\")", "Deployment_Node(n, \"N\") {\n".repeat(MAX_DEPTH + 1));
assert!(crate::parse(&deep).is_none());
}
#[test]
fn draws_cards_inside_their_frames() {
let s = crate::scene(
"C4Container\nSystem_Boundary(s, \"Shop\") {\nContainer(web, \"Web\", \"Rust\", \"Serves pages\")\n}\nPerson(u, \"User\")\nRel(u, web, \"Visits\", \"HTTPS\")",
&DiagramStyle::neutral(true),
None,
)
.unwrap();
let at = |t: &str| s.labels.iter().find(|l| l.text == t).unwrap_or_else(|| panic!("{t}")).at;
for t in ["«container»", "[Rust]", "Serves pages", "«person»", "Shop\n[System]", "Visits\n[HTTPS]"] {
at(t);
}
assert!(at("User")[1] < at("Web")[1], "the person comes first");
}
+412
View File
@@ -0,0 +1,412 @@
//! UML class and Rust struct/trait diagrams (`classDiagram`), laid out on [`crate::layout::draw`].
use std::collections::HashMap;
use rune::Color;
use super::lenient::{Lenient, Reader};
use crate::canvas::Scene;
use crate::layout::draw::{ClusterSpec, Dir, DrawNode, Edge, Head, Line, class_box, draw_layered};
use crate::layout::layered::Spacing;
use crate::{DiagramStyle, EdgeStyle, Hover, MAX_ITEMS, NodeStyle, StyleSheet, clean, clean_quoted, statements};
#[derive(Debug)]
pub(crate) struct ClassNode {
#[cfg_attr(not(test), allow(dead_code, reason = "tests check parsing by id"))]
pub id: String,
pub label: String,
pub stereo: Option<String>,
pub fields: Vec<String>,
pub methods: Vec<String>,
pub namespace: Option<usize>,
pub style: NodeStyle,
}
#[derive(Debug)]
pub(crate) struct Namespace {
pub title: String,
}
#[derive(Debug)]
pub(crate) struct ClassDiagram {
pub title: Option<String>,
pub dir: Dir,
pub classes: Vec<ClassNode>,
pub edges: Vec<Edge>,
pub namespaces: Vec<Namespace>,
}
/// Relationship tokens, longest first: `(token, start_head, end_head, line)`.
const RELS: &[(&str, Head, Head, Line)] = &[
("<|..", Head::OpenTriangle, Head::None, Line::Dotted),
("..|>", Head::None, Head::OpenTriangle, Line::Dotted),
("<|--", Head::OpenTriangle, Head::None, Line::Solid),
("--|>", Head::None, Head::OpenTriangle, Line::Solid),
("*--", Head::DiamondFilled, Head::None, Line::Solid),
("--*", Head::None, Head::DiamondFilled, Line::Solid),
("o--", Head::DiamondOpen, Head::None, Line::Solid),
("--o", Head::None, Head::DiamondOpen, Line::Solid),
("<-->", Head::Arrow, Head::Arrow, Line::Solid),
("<..>", Head::Arrow, Head::Arrow, Line::Dotted),
("-->", Head::None, Head::Arrow, Line::Solid),
("<--", Head::Arrow, Head::None, Line::Solid),
("..>", Head::None, Head::Arrow, Line::Dotted),
("<..", Head::Arrow, Head::None, Line::Dotted),
("--", Head::None, Head::None, Line::Solid),
("..", Head::None, Head::None, Line::Dotted),
];
pub(crate) fn parse(header: &str, body: &[&str]) -> Option<ClassDiagram> {
let mut p = Parser {
d: ClassDiagram { title: None, dir: Dir::Down, classes: Vec::new(), edges: Vec::new(), namespaces: Vec::new() },
ids: HashMap::new(),
active_class: None,
active_ns: None,
styles: StyleSheet::default(),
members: 0,
over: false,
};
let mut reader = Reader::default();
for line in std::iter::once(header).chain(body.iter().copied()) {
for stmt in statements(line) {
reader.read(&mut p, stmt)?;
}
}
for (id, &idx) in &p.ids {
p.d.classes[idx].style = p.styles.get(id);
}
(!p.d.classes.is_empty()).then_some(p.d)
}
struct Parser {
d: ClassDiagram,
ids: HashMap<String, usize>,
active_class: Option<usize>,
active_ns: Option<usize>,
styles: StyleSheet,
members: usize,
/// Set once the source goes past [`MAX_ITEMS`] (or four times that in members).
over: bool,
}
impl Lenient for Parser {
type Mark = (usize, usize);
fn mark(&self) -> (usize, usize) {
(self.d.classes.len(), self.d.edges.len())
}
fn undo(&mut self, (classes, edges): (usize, usize)) {
self.d.classes.truncate(classes);
self.d.edges.truncate(edges);
self.ids.retain(|_, &mut i| i < classes);
}
fn read_statement(&mut self, s: &str) -> Option<()> {
self.statement(s)
}
fn over(&self) -> bool {
self.over
}
}
impl Parser {
fn budget(&mut self) -> Option<()> {
self.over |= self.d.classes.len() + self.d.edges.len() + self.d.namespaces.len() >= MAX_ITEMS;
(!self.over).then_some(())
}
fn statement(&mut self, s: &str) -> Option<()> {
if let Some(idx) = self.active_class {
if s == "}" {
self.active_class = None;
return Some(());
}
self.add_member(idx, s);
return (!self.over).then_some(());
}
if s == "}" {
self.active_ns.take()?;
return Some(());
}
let word = s.split(|c: char| c.is_whitespace() || c == ':').next().unwrap_or("");
match word {
"title" => {
let t = clean_quoted(s["title".len()..].trim());
if !t.is_empty() {
self.d.title = Some(t);
}
}
"direction" => {
let d = Dir::parse(s["direction".len()..].trim())?;
if self.d.edges.is_empty() {
self.d.dir = d;
}
}
"namespace" => {
if self.active_ns.is_some() {
return None;
}
let rest = s["namespace".len()..].trim().strip_suffix('{')?.trim();
self.budget()?;
self.d.namespaces.push(Namespace { title: clean_quoted(rest) });
self.active_ns = Some(self.d.namespaces.len() - 1);
}
"class" => self.class_decl(s["class".len()..].trim())?,
"note" | "Note" | "link" | "click" | "callback" | "accTitle" | "accDescr" => {}
"classDef" => {
let _ = self.styles.class_def(&s["classDef".len()..]);
}
"cssClass" => {
let rest = s["cssClass".len()..].trim();
if let Some((targets, cls)) = rest.rsplit_once(char::is_whitespace) {
let cls = cls.trim().trim_matches('"');
for id in targets.trim().trim_matches('"').split(',').map(str::trim) {
self.styles.add_class(id, cls);
}
}
}
"style" => {
let _ = self.styles.style(&s["style".len()..]);
}
_ if s.starts_with("<<") && s.contains(">>") => {
let end = s.find(">>")?;
let stereo = clean(&s[2..end]);
let id = s[end + 2..].trim();
let idx = self.ensure_class(id)?;
self.d.classes[idx].stereo = Some(stereo);
}
_ => {
if let Some(()) = self.try_relation(s) {
return Some(());
}
if let Some((lhs, member)) = s.split_once(':') {
let id = self.styles.strip_inline(lhs)?;
let idx = self.ensure_class(&id)?;
self.add_member(idx, member.trim());
return (!self.over).then_some(());
}
return None;
}
}
Some(())
}
fn class_decl(&mut self, rest: &str) -> Option<()> {
let opens = rest.ends_with('{');
let core = if opens { rest[..rest.len() - 1].trim() } else { rest };
let (core, inline_stereo) = if let Some(at) = core.find("<<") {
let end = core[at + 2..].find(">>")?;
let st = clean(&core[at + 2..at + 2 + end]);
(core[..at].trim(), Some(st))
} else {
(core, None)
};
let core = self.styles.strip_inline(core)?;
let (id, label) = if let Some(b) = core.find('[')
&& core.ends_with(']')
{
(core[..b].trim(), Some(clean_quoted(&core[b + 1..core.len() - 1])))
} else if let Some((id, alias)) = core.split_once(" as ") {
(id.trim(), Some(clean_quoted(alias)))
} else {
(core.as_str(), None)
};
// `class A,B` declares multiple empty classes on one line.
if !opens && label.is_none() && id.contains(',') {
for part in id.split(',').map(str::trim).filter(|p| !p.is_empty()) {
let idx = self.ensure_class(part)?;
if let Some(st) = &inline_stereo {
self.d.classes[idx].stereo = Some(st.clone());
}
}
return Some(());
}
let idx = self.ensure_class(id)?;
if let Some(l) = label {
self.d.classes[idx].label = l;
}
if let Some(st) = inline_stereo {
self.d.classes[idx].stereo = Some(st);
}
if opens {
self.active_class = Some(idx);
}
Some(())
}
fn add_member(&mut self, idx: usize, raw: &str) {
let t = raw.trim();
if t.is_empty() {
return;
}
if let Some(st) = t.strip_prefix("<<").and_then(|r| r.strip_suffix(">>")) {
self.d.classes[idx].stereo = Some(clean(st));
return;
}
self.members += 1;
self.over |= self.members > MAX_ITEMS * 4;
let cleaned = clean(&tilde_generics(t));
if cleaned.contains('(') && cleaned.contains(')') {
self.d.classes[idx].methods.push(cleaned);
} else {
self.d.classes[idx].fields.push(cleaned);
}
}
fn try_relation(&mut self, s: &str) -> Option<()> {
let (lhs_rel, label_part) = match find_colon_outside_quotes(s) {
Some(at) => (&s[..at], Some(clean_quoted(&s[at + 1..]))),
None => (s, None),
};
let (pos, &(tok, start_h, end_h, line)) = find_rel(lhs_rel)?;
let (left_id, left_card) = parse_side(lhs_rel[..pos].trim(), true)?;
let (right_id, right_card) = parse_side(lhs_rel[pos + tok.len()..].trim(), false)?;
let left_id = self.styles.strip_inline(&left_id)?;
let right_id = self.styles.strip_inline(&right_id)?;
let from = self.ensure_class(&left_id)?;
let to = self.ensure_class(&right_id)?;
self.budget()?;
let mut parts = Vec::new();
if let Some(lc) = left_card.filter(|c| !c.is_empty()) {
parts.push(lc);
}
if let Some(lbl) = label_part.filter(|c| !c.is_empty()) {
parts.push(lbl);
}
if let Some(rc) = right_card.filter(|c| !c.is_empty()) {
parts.push(rc);
}
let label = (!parts.is_empty()).then(|| parts.join(" · "));
// Inheritance `<|--` puts the base class at the top and the derived class below it.
let (from, to, start, end) = if start_h == Head::OpenTriangle && end_h == Head::None {
(from, to, start_h, end_h)
} else if end_h == Head::OpenTriangle && start_h == Head::None {
(to, from, Head::OpenTriangle, Head::None)
} else {
(from, to, start_h, end_h)
};
self.d.edges.push(Edge { from, to, label, line, start, end, minlen: 1, style: EdgeStyle::default(), on_cluster: [None; 2] });
Some(())
}
fn ensure_class(&mut self, raw: &str) -> Option<usize> {
let (id, generic) = match raw.find('~') {
Some(at) if raw.ends_with('~') && at > 0 => (&raw[..at], Some(&raw[at + 1..raw.len() - 1])),
_ => (raw, None),
};
let id = id.trim().trim_matches('`');
if !valid_class_id(id) {
return None;
}
let ns = self.active_ns;
if let Some(&idx) = self.ids.get(id) {
if self.d.classes[idx].namespace.is_none() {
self.d.classes[idx].namespace = ns;
}
if let Some(g) = generic {
self.d.classes[idx].label = format!("{id}<{g}>");
}
return Some(idx);
}
self.budget()?;
let label = match generic {
Some(g) => format!("{id}<{g}>"),
None => id.to_owned(),
};
self.d.classes.push(ClassNode {
id: id.to_owned(),
label,
stereo: None,
fields: Vec::new(),
methods: Vec::new(),
namespace: ns,
style: NodeStyle::default(),
});
let idx = self.d.classes.len() - 1;
self.ids.insert(id.to_owned(), idx);
Some(idx)
}
}
fn valid_class_id(s: &str) -> bool {
!s.is_empty() && s.chars().all(|c| c.is_alphanumeric() || matches!(c, '_' | '-' | '.'))
}
fn tilde_generics(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut open = false;
for ch in s.chars() {
if ch == '~' {
out.push(if open { '>' } else { '<' });
open = !open;
} else {
out.push(ch);
}
}
out
}
fn find_colon_outside_quotes(s: &str) -> Option<usize> {
let mut quoted = false;
for (i, ch) in s.char_indices() {
if ch == '"' {
quoted = !quoted;
} else if ch == ':' && !quoted && s.as_bytes().get(i + 1) != Some(&b':') && i.checked_sub(1).and_then(|p| s.as_bytes().get(p)) != Some(&b':') {
return Some(i);
}
}
None
}
fn find_rel(s: &str) -> Option<(usize, &'static (&'static str, Head, Head, Line))> {
let mut quoted = false;
for (i, ch) in s.char_indices() {
if ch == '"' {
quoted = !quoted;
continue;
}
if quoted {
continue;
}
if let Some(rel) = RELS.iter().find(|r| s[i..].starts_with(r.0)) {
// Avoid matching a single `-` inside a hyphenated identifier like `rune-kit`:
// `--` only counts as a relation when whitespace or a quote borders it.
let prev = s[..i].chars().next_back();
let next = s[i + rel.0.len()..].chars().next();
if rel.0 == "--" && prev.is_some_and(|c| c.is_alphanumeric()) && next.is_some_and(|c| c.is_alphanumeric()) {
continue;
}
return Some((i, rel));
}
}
None
}
fn parse_side(s: &str, left: bool) -> Option<(String, Option<String>)> {
let s = s.trim();
if s.is_empty() {
return None;
}
if left && s.ends_with('"') {
let without_end = &s[..s.len() - 1];
let q = without_end.rfind('"')?;
let card = clean(&without_end[q + 1..]);
return Some((without_end[..q].trim().to_owned(), Some(card)));
}
if !left && let Some(rest) = s.strip_prefix('"') {
let q = rest.find('"')?;
let card = clean(&rest[..q]);
return Some((rest[q + 1..].trim().to_owned(), Some(card)));
}
Some((s.to_owned(), None))
}
const SPACING: Spacing = Spacing { node: 38.0, rank: 48.0, cluster: 16.0 };
pub(crate) fn draw(d: &ClassDiagram, paint: &DiagramStyle, hover: Option<(Hover, Color)>) -> Option<Scene> {
let nodes: Vec<DrawNode> = d.classes.iter().map(|c| class_box(c.stereo.as_deref(), &c.label, &c.fields, &c.methods, c.namespace, c.style, paint)).collect();
let clusters: Vec<ClusterSpec> = d.namespaces.iter().map(|n| ClusterSpec { title: n.title.clone(), parent: None }).collect();
draw_layered(d.dir, &nodes, &d.edges, &clusters, &SPACING, paint, hover)
}
#[cfg(test)]
#[path = "class_tests.rs"]
mod tests;
@@ -0,0 +1,80 @@
use super::*;
fn cls(src: &str) -> ClassDiagram {
match crate::parse(src).map(|p| p.diagram) {
Some(crate::Diagram::Class(c)) => c,
_ => panic!("not a class diagram: {src:?}"),
}
}
#[test]
fn classes_members_stereotypes_namespaces_and_relations() {
let c = cls(
"classDiagram\n\
direction LR\n\
namespace core {\n\
class Runtime~S~ {\n\
<<struct>>\n\
+S state\n\
+Scene motion\n\
+frame(dt: f64)\n\
+update(f)\n\
}\n\
class El {\n\
+key(k)\n\
+child(el)\n\
}\n\
}\n\
Runtime \"1\" *-- \"*\" El : builds\n\
Widget <|.. Button : implements\n\
style Runtime fill:#dcf5dc",
);
assert_eq!(c.dir, Dir::Right);
assert_eq!(c.namespaces.len(), 1);
assert_eq!(c.namespaces[0].title, "core");
let rt = c.classes.iter().find(|n| n.id == "Runtime").unwrap();
assert_eq!(rt.label, "Runtime<S>");
assert_eq!(rt.stereo.as_deref(), Some("struct"));
assert_eq!(rt.fields.len(), 2);
assert_eq!(rt.methods.len(), 2);
assert!(rt.style.fill.is_some());
assert_eq!(c.edges.len(), 2);
assert_eq!(c.edges[0].start, Head::DiamondFilled);
assert_eq!(c.edges[1].start, Head::OpenTriangle);
let paint = DiagramStyle::neutral(true);
assert!(draw(&c, &paint, None).is_some());
}
#[test]
fn only_sources_where_nothing_reads_are_rejected() {
for src in ["classDiagram", "classDiagram\n}", "classDiagram\njust garbage words here"] {
assert!(crate::parse(src).is_none(), "{src:?}");
}
}
#[test]
fn a_statement_that_does_not_read_is_skipped_with_its_body() {
let c = cls("classDiagram\nclass Open {\n +x");
assert_eq!(c.classes[0].fields, ["+x"], "an open class body closes at the end");
let c = cls("classDiagram\njust garbage words here\nclass Bad<<x {\n +y\n}\nA --> B");
let ids: Vec<&str> = c.classes.iter().map(|k| k.id.as_str()).collect();
assert_eq!((ids, c.edges.len()), (vec!["A", "B"], 1));
}
#[test]
fn a_skipped_block_skips_the_blocks_inside_it() {
// Namespaces don't nest: `inner` is skipped whole, class body included, and its `}` doesn't
// close `outer`.
let c = cls("classDiagram\nnamespace outer {\n namespace inner {\n class Hidden {\n +x\n }\n }\n class Kept\n}");
let ids: Vec<&str> = c.classes.iter().map(|k| k.id.as_str()).collect();
assert_eq!(ids, ["Kept"]);
assert_eq!(c.classes[0].namespace, Some(0), "still inside outer");
}
#[test]
fn every_prefix_draws_or_falls_back_without_panicking() {
crate::tests::assert_prefixes_never_panic(
"classDiagram\n class A {\n +i32 x\n +run()\n }\n A --> B : calls",
false,
);
}
+375
View File
@@ -0,0 +1,375 @@
//! Entity-relationship diagrams (`erDiagram`), laid out on [`crate::layout::draw`]: entities as
//! attribute tables, relationships in crow's-foot notation.
use std::collections::HashMap;
use rune::{Color, TextStyle};
use super::lenient::{Lenient, Reader};
use crate::canvas::{Measured, Scene, measure_wrap};
use crate::layout::draw::{Dir, DrawNode, ENTITY_PAD, Edge, Head, Line, draw_layered, entity_row_h};
use crate::layout::layered::Spacing;
use crate::{DiagramStyle, EdgeStyle, Hover, MAX_ITEMS, NodeStyle, StyleSheet, clean, clean_quoted, statements};
#[derive(Debug)]
pub(crate) struct Entity {
#[cfg_attr(not(test), allow(dead_code, reason = "tests check parsing by id"))]
pub id: String,
pub label: String,
pub attrs: Vec<Attr>,
pub style: NodeStyle,
}
/// `type name PK, FK "comment"`.
#[derive(Debug, Default, PartialEq)]
pub(crate) struct Attr {
pub ty: String,
pub name: String,
pub keys: String,
pub comment: String,
}
#[derive(Debug)]
pub(crate) struct ErDiagram {
pub title: Option<String>,
pub dir: Dir,
pub entities: Vec<Entity>,
pub edges: Vec<Edge>,
}
pub(crate) fn parse(header: &str, body: &[&str]) -> Option<ErDiagram> {
let mut p = Parser {
d: ErDiagram { title: None, dir: Dir::Down, entities: Vec::new(), edges: Vec::new() },
ids: HashMap::new(),
open: None,
styles: StyleSheet::default(),
attrs: 0,
over: false,
};
let mut reader = Reader::default();
for line in std::iter::once(header).chain(body.iter().copied()) {
for stmt in statements(line) {
reader.read(&mut p, stmt)?;
}
}
for (id, &idx) in &p.ids {
p.d.entities[idx].style = p.styles.get(id);
}
(!p.d.entities.is_empty()).then_some(p.d)
}
struct Parser {
d: ErDiagram,
ids: HashMap<String, usize>,
/// The entity whose `{ … }` attribute block is open.
open: Option<usize>,
styles: StyleSheet,
attrs: usize,
over: bool,
}
impl Lenient for Parser {
type Mark = (usize, usize);
fn mark(&self) -> (usize, usize) {
(self.d.entities.len(), self.d.edges.len())
}
fn undo(&mut self, (entities, edges): (usize, usize)) {
self.d.entities.truncate(entities);
self.d.edges.truncate(edges);
self.ids.retain(|_, &mut i| i < entities);
}
fn read_statement(&mut self, s: &str) -> Option<()> {
self.statement(s)
}
fn over(&self) -> bool {
self.over
}
}
impl Parser {
fn budget(&mut self) -> Option<()> {
self.over |= self.d.entities.len() + self.d.edges.len() >= MAX_ITEMS || self.attrs > MAX_ITEMS * 4;
(!self.over).then_some(())
}
fn statement(&mut self, s: &str) -> Option<()> {
if let Some(idx) = self.open {
if s == "}" {
self.open = None;
return Some(());
}
let attr = parse_attr(s)?;
self.attrs += 1;
self.budget()?;
self.d.entities[idx].attrs.push(attr);
return Some(());
}
let word = s.split(|c: char| c.is_whitespace() || c == ':').next().unwrap_or("");
match word {
"title" => {
let t = clean_quoted(s["title".len()..].trim());
if !t.is_empty() {
self.d.title = Some(t);
}
return Some(());
}
"direction" => {
self.d.dir = Dir::parse(s["direction".len()..].trim())?;
return Some(());
}
"accTitle" | "accDescr" => return Some(()),
"classDef" => {
self.styles.class_def(&s["classDef".len()..])?;
return Some(());
}
"class" => {
let (ids, cls) = s["class".len()..].trim().rsplit_once(char::is_whitespace)?;
for id in ids.split(',').map(str::trim) {
self.styles.add_class(id, cls.trim());
}
return Some(());
}
"style" => {
self.styles.style(&s["style".len()..])?;
return Some(());
}
_ => {}
}
if self.relation(s).is_some() {
return Some(());
}
// `NAME`, `NAME["Alias"]`, `"Name with spaces"`, optionally opening `{ … }`.
let (head, block) = match s.find('{') {
Some(at) => (s[..at].trim(), Some(s[at + 1..].trim())),
None => (s, None),
};
let idx = self.entity(head)?;
match block {
None => {}
Some("") => self.open = Some(idx),
Some(rest) => {
// `NAME { string id }` on one line.
let inner = rest.strip_suffix('}')?.trim();
if !inner.is_empty() {
let attr = parse_attr(inner)?;
self.attrs += 1;
self.budget()?;
self.d.entities[idx].attrs.push(attr);
}
}
}
Some(())
}
fn relation(&mut self, s: &str) -> Option<()> {
let (lhs, label) = match colon_outside_quotes(s) {
Some(at) => (s[..at].trim(), Some(clean_quoted(&s[at + 1..]))),
None => (s.trim(), None),
};
let (a, start, line, end, b) = symbolic(lhs).or_else(|| worded(lhs))?;
let from = self.entity(a)?;
let to = self.entity(b)?;
self.budget()?;
let label = label.filter(|l| !l.is_empty());
self.d.edges.push(Edge { from, to, label, line, start, end, minlen: 1, style: EdgeStyle::default(), on_cluster: [None; 2] });
Some(())
}
fn entity(&mut self, raw: &str) -> Option<usize> {
let (raw, class) = match raw.split_once(":::") {
Some((id, cls)) => (id.trim(), Some(cls.trim())),
None => (raw.trim(), None),
};
let (id, alias) = match raw.find('[') {
Some(at) if raw.ends_with(']') && at > 0 => (raw[..at].trim(), Some(clean_quoted(&raw[at + 1..raw.len() - 1]))),
_ => (raw, None),
};
let id = match id.strip_prefix('"').and_then(|r| r.strip_suffix('"')) {
Some(q) if !q.is_empty() && !q.contains('"') => q,
_ if valid_id(id) => id,
_ => return None,
};
if let Some(cls) = class {
self.styles.add_class(id, cls);
}
let idx = match self.ids.get(id) {
Some(&i) => i,
None => {
self.budget()?;
self.d.entities.push(Entity { id: id.to_owned(), label: clean(id), attrs: Vec::new(), style: NodeStyle::default() });
self.ids.insert(id.to_owned(), self.d.entities.len() - 1);
self.d.entities.len() - 1
}
};
if let Some(a) = alias.filter(|a| !a.is_empty()) {
self.d.entities[idx].label = a;
}
Some(idx)
}
}
fn valid_id(s: &str) -> bool {
!s.is_empty() && s.chars().all(|c| c.is_alphanumeric() || matches!(c, '_' | '-' | '.' | '*'))
}
/// `A ||--o{ B`: two marks either side of `--` (identifying) or `..` (not).
fn symbolic(s: &str) -> Option<(&str, Head, Line, Head, &str)> {
let b = s.as_bytes();
for i in 2..b.len().saturating_sub(3) {
let line = match &b[i..i + 2] {
b"--" => Line::Solid,
b".." => Line::Dotted,
_ => continue,
};
let left = match &b[i - 2..i] {
b"||" => Head::OnlyOne,
b"|o" => Head::ZeroOrOne,
b"}|" => Head::OneOrMore,
b"}o" => Head::ZeroOrMore,
_ => continue,
};
let right = match &b[i + 2..i + 4] {
b"||" => Head::OnlyOne,
b"o|" => Head::ZeroOrOne,
b"|{" => Head::OneOrMore,
b"o{" => Head::ZeroOrMore,
_ => continue,
};
let (a, z) = (s[..i - 2].trim(), s[i + 4..].trim());
if a.is_empty() || z.is_empty() {
return None;
}
return Some((a, left, line, right, z));
}
None
}
/// `CAR only one to zero or more DRIVER`, with `optionally to` for a dotted line.
fn worded(s: &str) -> Option<(&str, Head, Line, Head, &str)> {
let (a, rest) = first_token(s)?;
let (rest, z) = last_token(rest)?;
let words = rest.trim();
let (left, line, right) = if let Some((l, r)) = words.split_once(" optionally to ") {
(l, Line::Dotted, r)
} else {
let (l, r) = words.split_once(" to ")?;
(l, Line::Solid, r)
};
Some((a, card(left.trim())?, line, card(right.trim())?, z))
}
fn card(s: &str) -> Option<Head> {
Some(match s.to_ascii_lowercase().as_str() {
"only one" | "1" | "one" | "exactly one" => Head::OnlyOne,
"zero or one" | "one or zero" => Head::ZeroOrOne,
"one or more" | "one or many" | "many(1)" | "1+" => Head::OneOrMore,
"zero or more" | "zero or many" | "many(0)" | "0+" | "many" => Head::ZeroOrMore,
_ => return None,
})
}
fn first_token(s: &str) -> Option<(&str, &str)> {
let s = s.trim();
if let Some(rest) = s.strip_prefix('"') {
let end = rest.find('"')? + 2;
return Some((&s[..end], &s[end..]));
}
let end = s.find(char::is_whitespace)?;
Some((&s[..end], &s[end..]))
}
fn last_token(s: &str) -> Option<(&str, &str)> {
let s = s.trim();
if let Some(rest) = s.strip_suffix('"') {
let start = rest.rfind('"')?;
return Some((&s[..start], &s[start..]));
}
let start = s.rfind(char::is_whitespace)? + 1;
Some((&s[..start], &s[start..]))
}
fn colon_outside_quotes(s: &str) -> Option<usize> {
let mut quoted = false;
for (i, ch) in s.char_indices() {
match ch {
'"' => quoted = !quoted,
':' if !quoted && !s[i..].starts_with(":::") && !s[..i].ends_with(':') => return Some(i),
_ => {}
}
}
None
}
/// `type name [PK|FK|UK[, …]] ["comment"]`.
fn parse_attr(s: &str) -> Option<Attr> {
let (body, comment) = match s.find('"') {
Some(at) => (s[..at].trim(), clean_quoted(&s[at..])),
None => (s.trim(), String::new()),
};
let mut words = body.split_whitespace();
let ty = words.next()?;
let name = words.next()?;
let mut keys = Vec::new();
for w in words.flat_map(|w| w.split(',')).map(str::trim).filter(|w| !w.is_empty()) {
match w {
"PK" | "FK" | "UK" => keys.push(w),
_ => return None,
}
}
Some(Attr { ty: generics(ty), name: name.to_owned(), keys: keys.join(", "), comment })
}
/// `list~string~` as `list<string>`.
fn generics(s: &str) -> String {
let mut open = false;
s.chars()
.map(|c| match c {
'~' => {
open = !open;
if open { '<' } else { '>' }
}
c => c,
})
.collect()
}
const SPACING: Spacing = Spacing { node: 40.0, rank: 52.0, cluster: 16.0 };
pub(crate) fn draw(d: &ErDiagram, paint: &DiagramStyle, hover: Option<(Hover, Color)>) -> Option<Scene> {
let head_font = TextStyle { weight: 600.0, ..paint.font };
let row_font = TextStyle { size: paint.font.size - 1.0, line_height: paint.font.line_height - 2.0, ..paint.font };
let nodes: Vec<DrawNode> = d
.entities
.iter()
.map(|e| {
let name = measure_wrap(&e.label, head_font, 220.0);
let rows: Vec<Vec<Measured>> = e
.attrs
.iter()
.map(|a| [&a.ty, &a.name, &a.keys, &a.comment].iter().map(|t| measure_wrap(t, row_font, 180.0)).collect())
.collect();
// A column nobody fills takes no room.
let mut cols = vec![0.0f32; 4];
for row in &rows {
for (w, m) in cols.iter_mut().zip(row) {
if !m.text.is_empty() {
*w = w.max(m.size[0] + ENTITY_PAD[0] * 2.0);
}
}
}
let table: f32 = cols.iter().sum();
let w = table.max(name.size[0] + 28.0).max(90.0);
// The last filled column takes up any slack.
if let Some(last) = cols.iter_mut().rev().find(|w| **w > 0.0) {
*last += w - table;
}
let h = name.size[1] + ENTITY_PAD[1] * 2.0 + rows.iter().map(|r| entity_row_h(r)).sum::<f32>();
DrawNode::Entity { name, rows, cols, size: [w, h.max(36.0)], style: e.style }
})
.collect();
draw_layered(d.dir, &nodes, &d.edges, &[], &SPACING, paint, hover)
}
#[cfg(test)]
#[path = "er_tests.rs"]
mod tests;
@@ -0,0 +1,83 @@
use super::*;
fn er(src: &str) -> ErDiagram {
match crate::parse(src).map(|p| p.diagram) {
Some(crate::Diagram::Er(d)) => d,
_ => panic!("not an ER diagram: {src:?}"),
}
}
fn ends(d: &ErDiagram, i: usize) -> (&str, Head, Line, Head, &str) {
let e = &d.edges[i];
(&d.entities[e.from].id, e.start, e.line, e.end, &d.entities[e.to].id)
}
#[test]
fn entities_attributes_and_crows_feet() {
let d = er("erDiagram\n\
CUSTOMER ||--o{ ORDER : places\n\
ORDER ||--|{ LINE-ITEM : contains\n\
CUSTOMER }|..|{ DELIVERY-ADDRESS : uses\n\
PERSON |o--o| SEAT : \"sits in\"\n\
CUSTOMER {\n\
string name\n\
string custNumber PK \"the key\"\n\
list~string~ tags\n\
int orderId FK, UK\n\
}\n\
p[\"A person\"] { string first }");
assert_eq!(d.dir, Dir::Down);
assert_eq!(ends(&d, 0), ("CUSTOMER", Head::OnlyOne, Line::Solid, Head::ZeroOrMore, "ORDER"));
assert_eq!(ends(&d, 1), ("ORDER", Head::OnlyOne, Line::Solid, Head::OneOrMore, "LINE-ITEM"));
assert_eq!(ends(&d, 2), ("CUSTOMER", Head::OneOrMore, Line::Dotted, Head::OneOrMore, "DELIVERY-ADDRESS"));
assert_eq!(ends(&d, 3), ("PERSON", Head::ZeroOrOne, Line::Solid, Head::ZeroOrOne, "SEAT"));
assert_eq!(d.edges[3].label.as_deref(), Some("sits in"));
let c = d.entities.iter().find(|e| e.id == "CUSTOMER").unwrap();
assert_eq!(c.attrs.len(), 4);
assert_eq!(c.attrs[1], Attr { ty: "string".into(), name: "custNumber".into(), keys: "PK".into(), comment: "the key".into() });
assert_eq!(c.attrs[2].ty, "list<string>");
assert_eq!(c.attrs[3].keys, "FK, UK");
let p = d.entities.iter().find(|e| e.id == "p").unwrap();
assert_eq!((p.label.as_str(), p.attrs.len()), ("A person", 1));
}
#[test]
fn worded_cardinalities_and_direction() {
let d = er("erDiagram\n\
direction LR\n\
CAR 1 to zero or more NAMED-DRIVER : allows\n\
PERSON many(0) optionally to 1+ \"Club House\" : joins");
assert_eq!(d.dir, Dir::Right);
assert_eq!(ends(&d, 0), ("CAR", Head::OnlyOne, Line::Solid, Head::ZeroOrMore, "NAMED-DRIVER"));
assert_eq!(ends(&d, 1), ("PERSON", Head::ZeroOrMore, Line::Dotted, Head::OneOrMore, "Club House"));
}
#[test]
fn bad_lines_and_blocks_are_skipped() {
let d = er("erDiagram\n\
A ||--o{ B : ok\n\
this is not a relation\n\
C ??--?? D : nope\n\
E bad name {\n\
string x\n\
}\n\
B {\n\
string fine\n\
not-an-attribute\n\
}");
assert_eq!(d.entities.iter().map(|e| e.id.as_str()).collect::<Vec<_>>(), ["A", "B"]);
assert_eq!(d.entities[1].attrs.len(), 1);
assert!(crate::parse("erDiagram\n nothing here at all").is_none());
}
#[test]
fn draws_tables_and_feet() {
let paint = DiagramStyle::neutral(false);
let s = crate::scene("erDiagram\nCUSTOMER ||--o{ ORDER : places\nCUSTOMER {\n string name PK\n}", &paint, None).unwrap();
let texts: Vec<&str> = s.labels.iter().map(|l| l.text.as_str()).collect();
for t in ["CUSTOMER", "ORDER", "places", "string", "name", "PK"] {
assert!(texts.contains(&t), "{t} in {texts:?}");
}
let budget = format!("erDiagram\n{}", (0..MAX_ITEMS).map(|i| format!("E{i} ||--o{{ F{i} : r")).collect::<Vec<_>>().join("\n"));
assert!(crate::parse(&budget).is_none(), "past the bounds stays source");
}
@@ -0,0 +1,709 @@
//! Flowcharts: the parser for `graph`/`flowchart` sources and their drawing on [`crate::layout::draw`].
use std::collections::{HashMap, HashSet};
use rune::Color;
use crate::canvas::parts::Names;
use crate::canvas::{Canvas, Scene, measure_balanced};
use crate::layout::draw::{ClusterSpec, Dir, DrawNode, Edge, Head, Line, NodeShape, layered_canvas, node_size};
use crate::layout::layered::{MAX_MINLEN, Spacing};
use crate::{
Cur, DiagramStyle, EdgeStyle, Hover, MAX_DEPTH, MAX_ITEMS, NodeStyle, StyleSheet, clean, clean_quoted,
parse_edge_style_props, statements,
};
#[derive(Debug)]
pub(crate) struct Node {
pub id: String,
pub label: String,
pub shape: NodeShape,
pub cluster: Option<usize>,
pub style: NodeStyle,
pub explicit_shape: bool,
}
#[derive(Debug)]
pub(crate) struct Subgraph {
pub id: Option<String>,
pub title: String,
pub parent: Option<usize>,
}
#[derive(Debug)]
pub(crate) struct Flowchart {
pub title: Option<String>,
pub dir: Dir,
pub nodes: Vec<Node>,
pub edges: Vec<Edge>,
pub subgraphs: Vec<Subgraph>,
}
/// `header` is what follows `graph`/`flowchart` on its line; `body` the remaining lines.
pub(crate) fn parse(header: &str, body: &[&str]) -> Option<Flowchart> {
let (dir, rest) = header.trim_start().split_once(|c: char| c.is_whitespace() || c == ';').unwrap_or((header.trim(), ""));
// A direction it doesn't know reads top-down.
let dir = Dir::parse(dir).unwrap_or(Dir::Down);
let mut p = Parser {
f: Flowchart { title: None, dir, nodes: Vec::new(), edges: Vec::new(), subgraphs: Vec::new() },
ids: HashMap::new(),
stack: Vec::new(),
styles: StyleSheet::default(),
default_edge_style: EdgeStyle::default(),
edge_styles: HashMap::new(),
edge_ids: HashSet::new(),
over: false,
};
// A statement that doesn't read is skipped; one past the bounds leaves the whole diagram as source.
for line in std::iter::once(rest).chain(body.iter().copied()) {
for stmt in statements(line) {
if p.statement(stmt).is_none() && p.over {
return None;
}
}
}
for (id, &idx) in &p.ids {
p.f.nodes[idx].style = p.styles.get(id);
}
for (i, e) in p.f.edges.iter_mut().enumerate() {
let mut st = p.default_edge_style;
if let Some(&es) = p.edge_styles.get(&i) {
st = st.merge(es);
}
e.style = st;
}
resolve_subgraph_endpoints(&mut p.f);
(!p.f.nodes.is_empty()).then_some(p.f)
}
/// Redirects edges targeting a `subgraph id` placeholder onto that subgraph's first/last member,
/// which ranks the edge, and marks that end to stop on the subgraph's border. An edge from inside
/// the subgraph to itself keeps the member.
fn resolve_subgraph_endpoints(f: &mut Flowchart) {
let mut redirects: HashMap<usize, (usize, usize, usize)> = HashMap::new();
for (sg_idx, sg) in f.subgraphs.iter().enumerate() {
let Some(id) = &sg.id else { continue };
let Some(node_idx) = f.nodes.iter().position(|n| &n.id == id && !n.explicit_shape) else { continue };
let members: Vec<usize> = (0..f.nodes.len())
.filter(|&i| i != node_idx && in_cluster(i, sg_idx, &f.nodes, &f.subgraphs))
.collect();
if let (Some(&first), Some(&last)) = (members.first(), members.last()) {
redirects.insert(node_idx, (first, last, sg_idx));
}
}
if redirects.is_empty() {
return;
}
for e in &mut f.edges {
let (from, to) = (e.from, e.to);
let inside = |v: usize, sg: usize| match redirects.get(&v) {
Some(r) => std::iter::successors(Some(r.2), |&s| f.subgraphs[s].parent).take(f.subgraphs.len() + 1).any(|s| s == sg),
None => in_cluster(v, sg, &f.nodes, &f.subgraphs),
};
if let Some(&(_, last, sg)) = redirects.get(&from) {
e.from = last;
e.on_cluster[0] = (!inside(to, sg)).then_some(sg);
}
if let Some(&(first, _, sg)) = redirects.get(&to) {
e.to = first;
e.on_cluster[1] = (!inside(from, sg)).then_some(sg);
}
}
let mut keep = Vec::with_capacity(f.nodes.len());
let mut remap = vec![0usize; f.nodes.len()];
for i in 0..f.nodes.len() {
if !redirects.contains_key(&i) {
remap[i] = keep.len();
keep.push(i);
}
}
let mut old = std::mem::take(&mut f.nodes).into_iter().enumerate().collect::<HashMap<_, _>>();
f.nodes = keep.into_iter().filter_map(|i| old.remove(&i)).collect();
for e in &mut f.edges {
e.from = remap[e.from];
e.to = remap[e.to];
}
}
fn in_cluster(node_idx: usize, target: usize, nodes: &[Node], subgraphs: &[Subgraph]) -> bool {
let mut cur = nodes[node_idx].cluster;
let mut steps = 0;
while let Some(c) = cur {
if c == target {
return true;
}
cur = subgraphs[c].parent;
steps += 1;
if steps > subgraphs.len() {
break;
}
}
false
}
struct Parser {
f: Flowchart,
ids: HashMap<String, usize>,
stack: Vec<usize>,
styles: StyleSheet,
default_edge_style: EdgeStyle,
edge_styles: HashMap<usize, EdgeStyle>,
edge_ids: HashSet<String>,
/// Set once the source goes past [`MAX_ITEMS`] or [`MAX_DEPTH`].
over: bool,
}
pub(crate) struct Link {
pub id: Option<String>,
pub line: Line,
pub start: Head,
pub end: Head,
pub minlen: usize,
pub label: Option<String>,
}
impl Parser {
fn budget(&mut self) -> Option<()> {
self.over |= self.f.nodes.len() + self.f.edges.len() + self.f.subgraphs.len() >= MAX_ITEMS;
(!self.over).then_some(())
}
fn statement(&mut self, s: &str) -> Option<()> {
let word = s.split(|c: char| c.is_whitespace() || c == ':').next().unwrap_or("");
match word {
"subgraph" => {
let rest = s["subgraph".len()..].trim();
let (sg_id, title) = match rest.find('[') {
Some(i) if rest.ends_with(']') => {
let raw_id = rest[..i].trim();
let id = (!raw_id.is_empty()).then(|| raw_id.to_owned());
(id, clean_quoted(&rest[i + 1..rest.len() - 1]))
}
_ => {
let id = (!rest.starts_with('"') && !rest.contains(char::is_whitespace) && !rest.is_empty()).then(|| rest.to_owned());
(id, clean_quoted(rest))
}
};
self.budget()?;
if self.stack.len() >= MAX_DEPTH {
self.over = true;
return None;
}
self.f.subgraphs.push(Subgraph { id: sg_id, title, parent: self.stack.last().copied() });
self.stack.push(self.f.subgraphs.len() - 1);
}
"end" if s == "end" => {
self.stack.pop()?;
}
"title" => {
let t = clean_quoted(s["title".len()..].trim());
if !t.is_empty() {
self.f.title = Some(t);
}
}
"direction" => {
let rest = s["direction".len()..].trim();
if self.stack.is_empty() && self.f.edges.is_empty()
&& let Some(d) = Dir::parse(rest)
{
self.f.dir = d;
}
}
"classDef" => {
let _ = self.styles.class_def(&s["classDef".len()..]);
}
"class" => {
let _ = self.styles.assign_classes(&s["class".len()..]);
}
"style" => {
let _ = self.styles.style(&s["style".len()..]);
}
"linkStyle" => {
let rest = s["linkStyle".len()..].trim();
if let Some((targets, props)) = rest.split_once(char::is_whitespace) {
let st = parse_edge_style_props(props);
for tok in targets.split(',').map(str::trim) {
if tok == "default" {
self.default_edge_style = self.default_edge_style.merge(st);
} else if let Ok(idx) = tok.parse::<usize>() {
let cur = self.edge_styles.get(&idx).copied().unwrap_or_default();
self.edge_styles.insert(idx, cur.merge(st));
}
}
}
}
"click" | "accTitle" | "accDescr" => {}
_ => self.chain(s)?,
}
Some(())
}
/// `A --> B & C -.-> D`, read whole before anything is added, so a chain that doesn't read
/// leaves no stray nodes behind.
fn chain(&mut self, s: &str) -> Option<()> {
let mut c = Cur::new(s);
// `e1@{ animate: true }` sets how a named edge moves, which a still drawing leaves out.
if let Some((id, _)) = s.split_once("@{")
&& self.edge_ids.contains(id.trim())
{
return Some(());
}
let mut groups = vec![group(&mut c)?];
let mut links = Vec::new();
loop {
c.skip_ws();
if c.done() {
break;
}
links.push(link(&mut c)?);
c.skip_ws();
groups.push(group(&mut c)?);
}
let groups: Vec<Vec<usize>> = groups.into_iter().map(|g| g.into_iter().map(|n| self.node(n)).collect()).collect::<Option<_>>()?;
self.edge_ids.extend(links.iter().filter_map(|l| l.id.clone()));
for (link, pair) in links.iter().zip(groups.windows(2)) {
for &from in &pair[0] {
for &to in &pair[1] {
self.budget()?;
self.f.edges.push(Edge {
from,
to,
label: link.label.clone(),
line: link.line,
start: link.start,
end: link.end,
minlen: link.minlen,
style: EdgeStyle::default(),
on_cluster: [None; 2],
});
}
}
}
Some(())
}
fn node(&mut self, r: NodeRef) -> Option<usize> {
let NodeRef { id, shape, class } = r;
if let Some(cls) = class {
self.styles.add_class(&id, &cls);
}
let cluster = self.stack.last().copied();
let i = match self.ids.get(&id) {
Some(&i) => i,
None => {
self.budget()?;
self.f.nodes.push(Node {
label: id.clone(),
id: id.clone(),
shape: NodeShape::Rect,
cluster,
style: NodeStyle::default(),
explicit_shape: false,
});
self.ids.insert(id, self.f.nodes.len() - 1);
self.f.nodes.len() - 1
}
};
let n = &mut self.f.nodes[i];
if n.cluster.is_none() {
n.cluster = cluster;
}
if let Some((label, shape)) = shape {
if let Some(l) = label {
n.label = l;
}
n.shape = shape;
n.explicit_shape = true;
}
Some(i)
}
}
/// A node as written in a chain: its id, its shape and label if given, and a `:::class`.
struct NodeRef {
id: String,
shape: Option<(Option<String>, NodeShape)>,
class: Option<String>,
}
fn group(c: &mut Cur) -> Option<Vec<NodeRef>> {
let mut v = vec![node_ref(c)?];
loop {
c.skip_ws();
if !c.eat("&") {
return Some(v);
}
c.skip_ws();
v.push(node_ref(c)?);
}
}
fn node_ref(c: &mut Cur) -> Option<NodeRef> {
let id = ident(c)?;
let shape = shape(c);
let class = if c.eat(":::") { Some(ident(c)?) } else { None };
Some(NodeRef { id, shape, class })
}
pub(crate) fn ident(c: &mut Cur) -> Option<String> {
let start = c.i;
while let Some(ch) = c.peek() {
let word = |ch: char| ch.is_alphanumeric() || ch == '_';
if word(ch) || (ch == '-' && c.i > start && c.peek2().is_some_and(word)) {
c.bump();
} else {
break;
}
}
(c.i > start).then(|| c.s[start..c.i].to_owned())
}
const SHAPES: &[(&str, &str, NodeShape)] = &[
("(((", ")))", NodeShape::DoubleCircle),
("([", "])", NodeShape::Stadium),
("[[", "]]", NodeShape::Subroutine),
("[(", ")]", NodeShape::Cylinder),
("((", "))", NodeShape::Circle),
("{{", "}}", NodeShape::Hexagon),
(">", "]", NodeShape::Asymmetric),
("[", "]", NodeShape::Rect),
("(", ")", NodeShape::Round),
("{", "}", NodeShape::Diamond),
];
fn find_close(s: &str, open: &str, close: &str) -> Option<usize> {
let nested = open.len() == 1 && close.len() == 1 && open != ">";
let (mut depth, mut quoted, mut escaped) = (1usize, false, false);
let mut i = 0;
while i < s.len() {
let rest = &s[i..];
let ch = rest.chars().next()?;
if escaped {
escaped = false;
i += ch.len_utf8();
continue;
}
if quoted {
match ch {
'\\' => escaped = true,
'"' => quoted = false,
_ => {}
}
i += ch.len_utf8();
continue;
}
if ch == '"' {
quoted = true;
i += 1;
continue;
}
if rest.starts_with(close) {
depth -= 1;
if depth == 0 {
return Some(i);
}
i += close.len();
continue;
}
if nested && rest.starts_with(open) {
depth += 1;
i += open.len();
continue;
}
i += ch.len_utf8();
}
None
}
fn find_quote_end(s: &str) -> Option<(String, usize)> {
let mut out = String::new();
let mut escaped = false;
for (i, ch) in s.char_indices() {
if escaped {
out.push(ch);
escaped = false;
continue;
}
match ch {
'\\' => escaped = true,
'"' => return Some((out, i + 1)),
_ => out.push(ch),
}
}
None
}
fn find_unquoted(s: &str, needle: &str) -> Option<usize> {
let (mut quoted, mut escaped) = (false, false);
for (i, ch) in s.char_indices() {
if escaped {
escaped = false;
continue;
}
if quoted {
match ch {
'\\' => escaped = true,
'"' => quoted = false,
_ => {}
}
continue;
}
if ch == '"' {
quoted = true;
continue;
}
if s[i..].starts_with(needle) {
return Some(i);
}
}
None
}
/// Mermaid v11 `@{ shape: cyl, label: "Postgres" }` node metadata. Shapes it doesn't know, and
/// parts it can't read, leave a plain rectangle.
fn parse_at_shape(c: &mut Cur) -> Option<(Option<String>, NodeShape)> {
c.eat("@{");
let end = find_close(c.rest(), "{", "}")?;
let inner = &c.rest()[..end];
let mut kind = NodeShape::Rect;
let mut label = None;
for (k, v) in split_top_commas(inner).into_iter().filter_map(|part| part.split_once(':')) {
let v = v.trim();
match k.trim() {
"shape" => kind = NodeShape::named(&v.trim_matches('"').to_ascii_lowercase()).unwrap_or(NodeShape::Rect),
"label" => label = Some(clean_quoted(v)),
// Icons and images can't be fetched, so they draw as their frame with the label.
"form" if kind == NodeShape::Rect => {
kind = match v.trim_matches('"') {
"circle" => NodeShape::Circle,
"rounded" => NodeShape::Round,
_ => NodeShape::Rect,
}
}
_ => {}
}
}
c.i += end + 1;
Some((label, kind))
}
fn split_top_commas(s: &str) -> Vec<&str> {
let mut out = Vec::new();
let (mut start, mut quoted, mut escaped) = (0, false, false);
for (i, ch) in s.char_indices() {
if escaped {
escaped = false;
continue;
}
match ch {
'\\' if quoted => escaped = true,
'"' => quoted = !quoted,
',' if !quoted => {
let seg = s[start..i].trim();
if !seg.is_empty() {
out.push(seg);
}
start = i + 1;
}
_ => {}
}
}
let tail = s[start..].trim();
if !tail.is_empty() {
out.push(tail);
}
out
}
/// A node's bracketed label and shape, `None` when it has none. An opener without its closer
/// reads as a plain rectangle holding the text as written, so `[/route]` is the label `/route`.
pub(crate) fn shape(c: &mut Cur) -> Option<(Option<String>, NodeShape)> {
let start = c.i;
if !c.rest().starts_with("@{") && !matches!(c.peek()?, '[' | '(' | '{' | '>') {
return None;
}
exact_shape(c).or_else(|| {
c.i = start;
Some(loose_shape(c))
})
}
fn exact_shape(c: &mut Cur) -> Option<(Option<String>, NodeShape)> {
if c.rest().starts_with("@{") {
return parse_at_shape(c);
}
for open in ["[/", "[\\"] {
if c.eat(open) {
let end = find_close(c.rest(), "[", "]")?;
let inner = &c.rest()[..end];
let close = inner.chars().last().filter(|&ch| ch == '/' || ch == '\\')?;
let label = clean_quoted(&inner[..inner.len() - 1]);
c.i += end + 1;
let kind = match (open, close) {
("[/", '/') => NodeShape::LeanRight,
("[/", _) => NodeShape::TrapBottom,
(_, '/') => NodeShape::TrapTop,
_ => NodeShape::LeanLeft,
};
return Some((Some(label), kind));
}
}
let &(open, close, kind) = SHAPES.iter().find(|(open, ..)| c.rest().starts_with(open))?;
c.eat(open);
c.skip_ws();
let label = if c.peek() == Some('"') {
c.bump();
let (label, used) = find_quote_end(c.rest())?;
c.i += used;
c.skip_ws();
if !c.eat(close) {
return None;
}
label
} else {
let end = find_close(c.rest(), open, close)?;
let label = c.rest()[..end].to_owned();
c.i += end + close.len();
label
};
Some((Some(clean(&label)), kind))
}
/// A rectangle from the opener's first bracket to its match, or to the end of the statement.
fn loose_shape(c: &mut Cur) -> (Option<String>, NodeShape) {
let rest = c.rest();
let at = rest.starts_with("@{");
let (open, close) = match rest.chars().next() {
Some('(') => ("(", ")"),
Some('{') => ("{", "}"),
Some('>') => (">", "]"),
_ if at => ("{", "}"),
_ => ("[", "]"),
};
let skip = if at { 2 } else { 1 };
let body = &rest[skip..];
let (text, used) = find_close(body, open, close).map_or((body, rest.len()), |e| (&body[..e], skip + e + 1));
c.i += used;
let label = clean_quoted(text);
((!at && !label.is_empty()).then_some(label), NodeShape::Rect)
}
fn run(c: &mut Cur) -> String {
let start = c.i;
while c.peek().is_some_and(|ch| matches!(ch, '-' | '=' | '.' | '~')) {
c.bump();
}
c.s[start..c.i].to_owned()
}
fn end_head(c: &mut Cur) -> Head {
match c.peek() {
Some('>') => {
c.bump();
Head::Arrow
}
Some(ch @ ('o' | 'x')) if c.peek2().is_none_or(|n| n.is_whitespace() || n == '|') => {
c.bump();
if ch == 'o' { Head::Circle } else { Head::Cross }
}
_ => Head::None,
}
}
pub(crate) fn link(c: &mut Cur) -> Option<Link> {
// A v11 edge id, `A e1@--> B`, names the edge for a later `e1@{ … }`.
let save = c.i;
let id = ident(c).filter(|_| c.eat("@") && matches!(c.peek(), Some('-' | '=' | '.' | '~' | '<' | 'o' | 'x')));
if id.is_none() {
c.i = save;
}
let start = if c.eat("<") {
Head::Arrow
} else if matches!(c.peek(), Some('o' | 'x')) && matches!(c.peek2(), Some('-' | '=')) {
let ch = c.peek();
c.bump();
if ch == Some('o') { Head::Circle } else { Head::Cross }
} else {
Head::None
};
let first = run(c);
if first.len() < 2 {
return None;
}
let mut end = end_head(c);
let mut body = first.clone();
let mut label = None;
if end == Head::None && matches!(first.as_str(), "--" | "==" | "-.") {
let close = if first == "-." { ".-" } else { &first[..] };
let at = find_unquoted(c.rest(), close)?;
let text = clean_quoted(&c.rest()[..at]);
if text.is_empty() {
return None;
}
label = Some(text);
c.i += at;
body = run(c);
end = end_head(c);
}
let line = if body.contains('~') {
Line::Invisible
} else if body.contains('=') {
Line::Thick
} else if body.contains('.') {
Line::Dotted
} else {
Line::Solid
};
let minlen = match line {
Line::Dotted => body.matches('.').count(),
_ => {
let n = body.chars().filter(|&ch| ch == '-' || ch == '=' || ch == '~').count();
if end == Head::None { n.saturating_sub(2) } else { n.saturating_sub(1) }
}
}
.clamp(1, MAX_MINLEN);
let save = c.i;
c.skip_ws();
if c.eat("|") {
let at = find_unquoted(c.rest(), "|")?;
let text = clean_quoted(&c.rest()[..at]);
c.i += at + 1;
label = (!text.is_empty()).then_some(text).or(label);
} else {
c.i = save;
}
Some(Link { id, line, start, end, minlen, label })
}
const SPACING: Spacing = Spacing { node: 36.0, rank: 44.0, cluster: 14.0 };
pub(crate) fn draw(f: &Flowchart, paint: &DiagramStyle, hover: Option<(Hover, Color)>) -> Option<Scene> {
draw_canvas(f, paint, hover)?.finish_fit(paint)
}
/// `f` drawn at full size, before [`Canvas::finish`].
pub(crate) fn draw_canvas(f: &Flowchart, paint: &DiagramStyle, hover: Option<(Hover, Color)>) -> Option<Canvas> {
let nodes: Vec<DrawNode> = f
.nodes
.iter()
.map(|n| {
let label = measure_balanced(&n.label, paint.font);
DrawNode::Shape { shape: n.shape, size: node_size(n.shape, label.size), label, cluster: n.cluster, style: n.style }
})
.collect();
let clusters: Vec<ClusterSpec> = f.subgraphs.iter().map(|s| ClusterSpec { title: s.title.clone(), parent: s.parent }).collect();
let names = names(f);
let mut c = layered_canvas(f.dir, &nodes, &names.nodes, &f.edges, &clusters, &SPACING, paint, hover)?;
c.names = names;
Some(c)
}
/// Nodes and subgraphs by id, edges by their ends.
fn names(f: &Flowchart) -> Names {
let frames = f.subgraphs.iter().enumerate().map(|(i, s)| s.id.clone().unwrap_or_else(|| format!("#{i}"))).collect();
Names::new(f.nodes.iter().map(|n| n.id.clone()).collect(), &f.edges, frames)
}
#[cfg(test)]
#[path = "flowchart_tests.rs"]
mod tests;
@@ -0,0 +1,316 @@
use super::*;
use crate::DiagramStyle;
use crate::canvas::dist;
use crate::layout::draw::boundary;
fn flow(src: &str) -> Flowchart {
match crate::parse(src).map(|p| p.diagram) {
Some(crate::Diagram::Flowchart(f)) => f,
_ => panic!("not a flowchart: {src:?}"),
}
}
fn edges(f: &Flowchart) -> Vec<(&str, &str)> {
f.edges.iter().map(|e| (f.nodes[e.from].id.as_str(), f.nodes[e.to].id.as_str())).collect()
}
#[test]
fn directions_shapes_and_labels() {
let f = flow(
"flowchart LR\n A[Start] --> B(Round)\n B --> C([Stadium]) --> D[[Sub]]\n D --> E[(Database)] & F((Circle))\n F --> G>Flag] --> H{Decide?} --> I{{Hex}}\n I --> J[/Lean/] --> K[/Trap\\]\n K --> L[\\Back\\] --> M[\\Top/] --> N(((Stop)))",
);
assert_eq!(f.dir, Dir::Right);
let shapes: Vec<(&str, &str, NodeShape)> = f.nodes.iter().map(|n| (n.id.as_str(), n.label.as_str(), n.shape)).collect();
assert_eq!(
shapes,
vec![
("A", "Start", NodeShape::Rect),
("B", "Round", NodeShape::Round),
("C", "Stadium", NodeShape::Stadium),
("D", "Sub", NodeShape::Subroutine),
("E", "Database", NodeShape::Cylinder),
("F", "Circle", NodeShape::Circle),
("G", "Flag", NodeShape::Asymmetric),
("H", "Decide?", NodeShape::Diamond),
("I", "Hex", NodeShape::Hexagon),
("J", "Lean", NodeShape::LeanRight),
("K", "Trap", NodeShape::TrapBottom),
("L", "Back", NodeShape::LeanLeft),
("M", "Top", NodeShape::TrapTop),
("N", "Stop", NodeShape::DoubleCircle),
]
);
assert_eq!(edges(&f)[3..5], [("D", "E"), ("D", "F")], "`&` fans out");
}
#[test]
fn v11_at_shapes_subgraph_endpoints_and_link_styles() {
let f = flow(
"flowchart TD\n\
App[Viewer] --> core\n\
subgraph core [Rune Core]\n\
El[El tree] --> Store@{ shape: cyl, label: \"AnimationStore\" }\n\
end\n\
core --> GPU@{ shape: hex, label: \"wgpu\" }\n\
linkStyle 0 stroke:#22c55e,stroke-width:2px",
);
assert_eq!(f.nodes.len(), 4, "placeholder node for `core` was redirected and removed");
assert_eq!(edges(&f), [("App", "El"), ("El", "Store"), ("Store", "GPU")]);
let store = f.nodes.iter().find(|n| n.id == "Store").unwrap();
assert_eq!((store.shape, store.label.as_str()), (NodeShape::Cylinder, "AnimationStore"));
assert!(f.edges[0].style.stroke.is_some());
assert_eq!(f.edges[0].style.width, Some(2.0));
}
#[test]
fn every_v11_shape_name_reads_and_draws() {
let names = [
("rect", NodeShape::Rect),
("event", NodeShape::Round),
("pill", NodeShape::Stadium),
("subproc", NodeShape::Subroutine),
("db", NodeShape::Cylinder),
("circ", NodeShape::Circle),
("dbl-circ", NodeShape::DoubleCircle),
("odd", NodeShape::Asymmetric),
("question", NodeShape::Diamond),
("prepare", NodeShape::Hexagon),
("in-out", NodeShape::LeanRight),
("out-in", NodeShape::LeanLeft),
("priority", NodeShape::TrapBottom),
("manual", NodeShape::TrapTop),
("start", NodeShape::SmallCircle),
("junction", NodeShape::FilledCircle),
("stop", NodeShape::FramedCircle),
("summary", NodeShape::CrossedCircle),
("bang", NodeShape::Bang),
("cloud", NodeShape::Cloud),
("card", NodeShape::Card),
("collate", NodeShape::Hourglass),
("com-link", NodeShape::Bolt),
("comment", NodeShape::BraceLeft),
("brace-r", NodeShape::BraceRight),
("braces", NodeShape::Braces),
("delay", NodeShape::Delay),
("das", NodeShape::HCylinder),
("disk", NodeShape::LinedCylinder),
("display", NodeShape::CurvedTrapezoid),
("div-proc", NodeShape::DividedRect),
("document", NodeShape::Document),
("lin-doc", NodeShape::LinedDocument),
("docs", NodeShape::Documents),
("tag-doc", NodeShape::TaggedDocument),
("extract", NodeShape::Triangle),
("manual-file", NodeShape::FlippedTriangle),
("join", NodeShape::Fork),
("internal-storage", NodeShape::WindowPane),
("shaded-process", NodeShape::LinedRect),
("loop-limit", NodeShape::NotchedPentagon),
("manual-input", NodeShape::SlopedRect),
("processes", NodeShape::StackedRect),
("paper-tape", NodeShape::Flag),
("stored-data", NodeShape::BowRect),
("tag-rect", NodeShape::TaggedRect),
("text", NodeShape::Text),
];
let mut src = String::from("flowchart TD\n");
for (i, (name, _)) in names.iter().enumerate() {
src += &format!(" n{i}@{{ shape: {name}, label: \"Step {i}\" }}\n");
if i > 0 {
src += &format!(" n{} --> n{i}\n", i - 1);
}
}
let f = flow(&src);
let got: Vec<NodeShape> = f.nodes.iter().map(|n| n.shape).collect();
let want: Vec<NodeShape> = names.iter().map(|&(_, s)| s).collect();
assert_eq!(got, want);
assert!(f.nodes.iter().all(|n| n.label.starts_with("Step ")));
assert!(crate::scene(&src, &DiagramStyle::neutral(false), None).is_some());
}
#[test]
fn icons_and_images_draw_as_their_frame() {
let f = flow("flowchart TD\n A@{ icon: \"fa:user\", form: \"circle\", label: \"User\" }\n B@{ img: \"https://example.com/a.png\", label: \"Pic\" }\n A --> B");
let nodes: Vec<(&str, NodeShape)> = f.nodes.iter().map(|n| (n.label.as_str(), n.shape)).collect();
assert_eq!(nodes, [("User", NodeShape::Circle), ("Pic", NodeShape::Rect)]);
}
#[test]
fn named_edges_and_their_settings_add_no_nodes() {
let f = flow("flowchart LR\n A e1@--> B\n B e2@-.-> C\n e1@{ animate: true }\n e2@{ animation: fast }");
assert_eq!(edges(&f), [("A", "B"), ("B", "C")]);
assert_eq!(f.edges[1].line, Line::Dotted);
assert_eq!(f.nodes.len(), 3);
}
#[test]
fn link_styles_heads_lengths_and_labels() {
let f = flow(
"graph TD\nA --> B\nA --- C\nA -.-> D\nA ==> E\nA -- yes --> F\nA -->|no| G\nA <--> H\nA --o I\nA --x J\nA ---> K\nA -. maybe .-> L\nA == sure ==> M\nA ~~~ N\nA-->O;O-->P",
);
let e = |to: &str| f.edges.iter().find(|e| f.nodes[e.to].id == to).expect(to);
assert_eq!((e("B").line, e("B").end, e("B").minlen), (Line::Solid, Head::Arrow, 1));
assert_eq!((e("C").line, e("C").end), (Line::Solid, Head::None));
assert_eq!((e("D").line, e("D").end), (Line::Dotted, Head::Arrow));
assert_eq!((e("E").line, e("E").end), (Line::Thick, Head::Arrow));
assert_eq!(e("F").label.as_deref(), Some("yes"));
assert_eq!(e("G").label.as_deref(), Some("no"));
assert_eq!((e("H").start, e("H").end), (Head::Arrow, Head::Arrow));
assert_eq!(e("I").end, Head::Circle);
assert_eq!(e("J").end, Head::Cross);
assert_eq!(e("K").minlen, 2);
assert_eq!((e("L").line, e("L").label.as_deref()), (Line::Dotted, Some("maybe")));
assert_eq!((e("M").line, e("M").label.as_deref()), (Line::Thick, Some("sure")));
assert_eq!(e("N").line, Line::Invisible);
assert_eq!(e("P").from, f.nodes.iter().position(|n| n.id == "O").unwrap(), "`;` separates statements");
}
#[test]
fn quoted_edge_labels_nested_brackets_and_styles() {
let f = flow(
"flowchart LR\n\
A[Audio] --> B[Parakeet writes text<br/>'went to the capuchin']\n\
B --> C{Any word that looks<br/>or sounds like a term?}\n\
C -- no --> F[Paste as is]\n\
C -- \"capuchin ≈ Cappuccino\" --> D[Score the same audio twice:<br/>as 'capuchin' and as 'Cappuccino']\n\
D --> E(Call fn(x)) --> G[items[0]]\n\
G -->|\"a | b\"| F\n\
style D fill:#dcf5dc",
);
let to_d = f.edges.iter().find(|e| f.nodes[e.to].id == "D").unwrap();
assert_eq!(to_d.label.as_deref(), Some("capuchin ≈ Cappuccino"));
let to_f = f.edges.iter().rfind(|e| f.nodes[e.to].id == "F").unwrap();
assert_eq!(to_f.label.as_deref(), Some("a | b"));
assert_eq!(f.nodes.iter().find(|n| n.id == "E").unwrap().label, "Call fn(x)");
assert_eq!(f.nodes.iter().find(|n| n.id == "G").unwrap().label, "items[0]");
assert!(f.nodes.iter().find(|n| n.id == "D").unwrap().style.fill.is_some());
}
#[test]
fn subgraphs_nest_and_claim_nodes() {
let f = flow(
"graph TB\n c1-->a2\n subgraph one [The first]\n a1-->a2\n subgraph inner\n x1\n end\n end\n subgraph \"two\"\n b1-->b2\n end\n classDef hot fill:#f00\n class a1 hot\n style b1 fill:#0f0\n click b2 callback\n a1:::hot --> b1",
);
let titles: Vec<&str> = f.subgraphs.iter().map(|s| s.title.as_str()).collect();
assert_eq!(titles, ["The first", "inner", "two"]);
assert_eq!(f.subgraphs[1].parent, Some(0));
let cluster = |id: &str| f.nodes.iter().find(|n| n.id == id).unwrap().cluster;
assert_eq!(cluster("c1"), None);
assert_eq!(cluster("a2"), Some(0), "first used outside, then inside");
assert_eq!(cluster("x1"), Some(1));
assert_eq!(cluster("b2"), Some(2));
assert!(f.nodes.iter().find(|n| n.id == "a1").unwrap().style.fill.is_some());
assert!(f.nodes.iter().find(|n| n.id == "b1").unwrap().style.fill.is_some());
}
#[test]
fn quoted_labels_breaks_and_dashed_ids() {
let f = flow("graph TD\n web-server[\"Web (edge) server\"] --> db[(\"Postgres<br/>primary\")]");
assert_eq!(f.nodes[0].id, "web-server");
assert_eq!(f.nodes[0].label, "Web (edge) server");
assert_eq!(f.nodes[1].label, "Postgres\nprimary");
}
#[test]
fn only_sources_where_nothing_reads_are_rejected() {
for src in ["graph TD", "graph TD\nend", "graph TD\n-->", "graph LR\n this is not valid", "graph TD\n%% just a comment", "notADiagram\nA --> B"] {
assert!(crate::parse(src).is_none(), "{src:?}");
}
}
#[test]
fn an_unclosed_shape_is_a_rectangle_with_its_text_as_written() {
// Mermaid itself rejects `[/…]` without its `/]`; we draw it as a plain rectangle on purpose,
// so one stray slash doesn't turn the whole chart back into source.
let src = "flowchart LR\n A[List + count] --> B[/items split view]\n B --> C[Details]\n C --> D[Pause / Resume / Delete]";
let f = flow(src);
let nodes: Vec<(&str, &str, NodeShape)> = f.nodes.iter().map(|n| (n.id.as_str(), n.label.as_str(), n.shape)).collect();
assert_eq!(
nodes,
[
("A", "List + count", NodeShape::Rect),
("B", "/items split view", NodeShape::Rect),
("C", "Details", NodeShape::Rect),
("D", "Pause / Resume / Delete", NodeShape::Rect),
]
);
assert_eq!(edges(&f), [("A", "B"), ("B", "C"), ("C", "D")]);
assert!(crate::scene(src, &DiagramStyle::neutral(true), None).is_some(), "the whole chart draws, no fallback");
let label = |src: &str| flow(src).nodes[0].label.clone();
assert_eq!(label("graph TD\nA[\\back slash]"), "\\back slash");
assert_eq!(label("graph TD\nA(open round"), "open round");
assert_eq!(label("graph TD\nA[unclosed --> B"), "unclosed --> B");
assert_eq!(label("flowchart TD\n A{\"quote never closes} --> B"), "\"quote never closes} --> B");
assert_eq!(flow("graph TD\nA@{ shape: not_a_shape } --> B").nodes[0].shape, NodeShape::Rect);
assert_eq!(flow("graph TD\nA@{ unclosed --> B").nodes[0].label, "A");
}
#[test]
fn punctuation_in_labels_is_plain_text() {
// `->` inside a cylinder is its label, not an edge; `_`, `*`, `+` and `.` are plain text; and
// the unclosed `[/…]` (which Mermaid itself rejects) is a rectangle on purpose.
let src = "flowchart LR\n a[setting.some_name] --> b[run_* + /go]\n c[(store -> row)] --> d[Item.Worker]\n d --> e[/api/v2/item]";
let f = flow(src);
let nodes: Vec<(&str, &str, NodeShape)> = f.nodes.iter().map(|n| (n.id.as_str(), n.label.as_str(), n.shape)).collect();
assert_eq!(
nodes,
[
("a", "setting.some_name", NodeShape::Rect),
("b", "run_* + /go", NodeShape::Rect),
("c", "store -> row", NodeShape::Cylinder),
("d", "Item.Worker", NodeShape::Rect),
("e", "/api/v2/item", NodeShape::Rect),
]
);
assert_eq!(edges(&f), [("a", "b"), ("c", "d"), ("d", "e")]);
assert!(crate::scene(src, &DiagramStyle::neutral(false), None).is_some(), "the whole chart draws, no fallback");
}
#[test]
fn a_statement_that_does_not_read_is_skipped() {
for (src, want) in [
("graph XY\nA-->B", vec![("A", "B")]),
("graph TD\nA -- --> B\nC --> D", vec![("C", "D")]),
("graph TD\nA -->|unclosed B\nC --> D", vec![("C", "D")]),
("graph TD\nA - B\nC --> D", vec![("C", "D")]),
("graph TD\nsubgraph open\n A --> B", vec![("A", "B")]),
("graph TD\nend\nA --> B\nend", vec![("A", "B")]),
("graph TD\nA --> \nC --> D", vec![("C", "D")]),
] {
let f = flow(src);
assert_eq!(edges(&f), want, "{src:?}");
let ids: Vec<&str> = f.nodes.iter().map(|n| n.id.as_str()).collect();
let mut used: Vec<&str> = want.iter().flat_map(|&(a, b)| [a, b]).collect();
used.dedup();
if !want.is_empty() {
assert_eq!(ids, used, "a statement that fails adds no nodes: {src:?}");
}
}
}
#[test]
fn going_past_the_bounds_still_rejects() {
let deep = (0..=crate::MAX_DEPTH).map(|d| format!("subgraph s{d}\nA{d}")).collect::<Vec<_>>().join("\n");
assert!(crate::parse(&format!("graph TD\n{deep}")).is_none());
let wide = (0..crate::MAX_ITEMS).map(|i| format!("N{i} --> M{i}")).collect::<Vec<_>>().join("\n");
assert!(crate::parse(&format!("graph TD\n{wide}")).is_none());
}
#[test]
fn every_prefix_of_a_source_parses_or_falls_back_without_panicking() {
crate::tests::assert_prefixes_never_panic(
"flowchart TD\n A[Start] -->|go| B{Ok?}\n B -- yes --> C([Done])\n B -.->|no| A\n subgraph s [Group]\n C --> D[(Store)]\n end",
false,
);
}
#[test]
fn boundary_points_sit_on_the_outline() {
let c = [0.0, 0.0];
assert_eq!(boundary(NodeShape::Rect, c, [100.0, 40.0], [0.0, 100.0]), [0.0, 20.0]);
assert_eq!(boundary(NodeShape::Rect, c, [100.0, 40.0], [100.0, 0.0]), [50.0, 0.0]);
let d = boundary(NodeShape::Diamond, c, [100.0, 40.0], [100.0, 40.0]);
assert!((d[0].abs() / 50.0 + d[1].abs() / 20.0 - 1.0).abs() < 1e-4);
let e = boundary(NodeShape::Circle, c, [40.0, 40.0], [30.0, 40.0]);
assert!((dist(c, e) - 20.0).abs() < 1e-4);
}
@@ -0,0 +1,52 @@
//! The lenient statement rule the block diagrams (class, ER, state) share: a statement that
//! doesn't read is undone and skipped, along with any `{ … }` body it opened, and one past the
//! size bounds leaves the whole diagram as source.
/// A diagram parser the [`Reader`] drives.
pub(crate) trait Lenient {
/// How much of the diagram is built, to undo a statement that doesn't read back to.
type Mark;
fn mark(&self) -> Self::Mark;
fn undo(&mut self, mark: Self::Mark);
/// Reads one statement; `None` when it doesn't read.
fn read_statement(&mut self, s: &str) -> Option<()>;
/// Past the size bounds.
fn over(&self) -> bool;
}
/// Feeds statements to a [`Lenient`] parser.
#[derive(Debug, Default)]
pub(crate) struct Reader {
/// How many `{ … }` bodies deep the skip is: one opened by a statement that didn't read,
/// and any opened inside it. 0 while reading.
skipping: usize,
}
impl Reader {
/// Reads `s` into `p`. `None` once `p` is past its bounds, so the diagram stays source.
pub(crate) fn read<P: Lenient>(&mut self, p: &mut P, s: &str) -> Option<()> {
if self.skipping > 0 {
if s == "}" {
self.skipping -= 1;
} else if s.ends_with('{') {
self.skipping += 1;
}
return Some(());
}
let mark = p.mark();
if p.read_statement(s).is_none() {
if p.over() {
return None;
}
p.undo(mark);
if s.ends_with('{') {
self.skipping = 1;
}
}
Some(())
}
}
#[cfg(test)]
#[path = "lenient_tests.rs"]
mod tests;
@@ -0,0 +1,44 @@
use super::{Lenient, Reader};
/// Keeps statements that are words; anything else doesn't read, after adding a junk item.
#[derive(Default)]
struct Words {
items: Vec<String>,
limit: usize,
}
impl Lenient for Words {
type Mark = usize;
fn mark(&self) -> usize {
self.items.len()
}
fn undo(&mut self, mark: usize) {
self.items.truncate(mark);
}
fn read_statement(&mut self, s: &str) -> Option<()> {
self.items.push(s.to_owned());
(s.chars().all(|c| c.is_alphanumeric() || c == '{' || c == '}' || c == ' ') && !s.starts_with('!')).then_some(())
}
fn over(&self) -> bool {
self.limit > 0 && self.items.len() > self.limit
}
}
fn read(src: &[&str], limit: usize) -> Option<Vec<String>> {
let (mut r, mut p) = (Reader::default(), Words { limit, ..Words::default() });
for s in src {
r.read(&mut p, s)?;
}
Some(p.items)
}
#[test]
fn an_unreadable_statement_is_undone_with_its_body_and_the_bodies_inside_it() {
let src = ["a", "!bad {", "inner {", "x", "}", "y", "}", "b", "!also bad", "c"];
assert_eq!(read(&src, 0).unwrap(), ["a", "b", "c"]);
}
#[test]
fn past_the_bounds_the_whole_diagram_stays_source() {
assert!(read(&["a", "b", "!c", "d"], 2).is_none());
}
+11
View File
@@ -0,0 +1,11 @@
//! Node-and-edge graph diagrams: flowcharts, state, class, entity-relationship, C4,
//! requirement and block diagrams, with lenient `{ … }` block recovery.
pub(crate) mod block;
pub(crate) mod c4;
pub(crate) mod class;
pub(crate) mod er;
pub(crate) mod flowchart;
mod lenient;
pub(crate) mod requirement;
pub(crate) mod state;
@@ -0,0 +1,160 @@
//! Requirement diagrams (`requirementDiagram`), laid out on [`crate::layout::draw`]: requirements
//! and elements as boxes of their fields, joined by `contains`, `satisfies` and the other
//! relationships.
use std::collections::HashMap;
use rune::Color;
use crate::canvas::Scene;
use crate::layout::draw::{Dir, DrawNode, Edge, Head, Line, class_box, draw_layered};
use crate::layout::layered::Spacing;
use crate::{DiagramStyle, EdgeStyle, Hover, MAX_ITEMS, NodeStyle, StyleSheet, clean_quoted, parse_style_props, word};
#[derive(Debug)]
pub(crate) struct Req {
pub name: String,
/// "Requirement", "Functional Requirement", "Element", …; empty for a name only ever related.
pub kind: String,
/// `Key: value` rows.
pub fields: Vec<String>,
pub style: NodeStyle,
}
#[derive(Debug)]
pub(crate) struct Requirements {
pub dir: Dir,
pub nodes: Vec<Req>,
pub edges: Vec<Edge>,
}
const KINDS: [(&str, &str); 7] = [
("requirement", "Requirement"),
("functionalRequirement", "Functional Requirement"),
("interfaceRequirement", "Interface Requirement"),
("performanceRequirement", "Performance Requirement"),
("physicalRequirement", "Physical Requirement"),
("designConstraint", "Design Constraint"),
("element", "Element"),
];
const RELATIONS: [&str; 7] = ["contains", "copies", "derives", "satisfies", "verifies", "refines", "traces"];
pub(crate) fn parse(body: &[&str]) -> Option<Requirements> {
let mut d = Requirements { dir: Dir::Down, nodes: Vec::new(), edges: Vec::new() };
let mut ids: HashMap<String, usize> = HashMap::new();
let mut styles = StyleSheet::default();
let mut open: Option<usize> = None;
for &l in body {
if let Some(i) = open {
let (l, closes) = l.strip_suffix('}').map_or((l, false), |r| (r.trim(), true));
if let Some((k, v)) = l.split_once(':') {
let v = clean_quoted(v);
let row = match k.trim().to_ascii_lowercase().as_str() {
"id" => Some(format!("ID: {v}")),
"text" => Some(format!("Text: {v}")),
"risk" => Some(format!("Risk: {}", title_case(&v))),
"verifymethod" => Some(format!("Verification: {}", title_case(&v))),
"type" => Some(format!("Type: {v}")),
"docref" => Some(format!("Doc Ref: {v}")),
_ => None,
};
d.nodes[i].fields.extend(row);
}
if closes {
open = None;
}
continue;
}
if let Some(rest) = word(l, "direction") {
d.dir = Dir::parse(rest).unwrap_or(d.dir);
} else if let Some(rest) = word(l, "classDef") {
let _ = styles.class_def(rest);
} else if let Some(rest) = word(l, "class") {
if let Some((names, class)) = rest.split_once(char::is_whitespace) {
for n in names.split(',') {
styles.add_class(&clean_quoted(n), class.trim());
}
}
} else if let Some(rest) = word(l, "style") {
if let Some((names, props)) = rest.split_once(char::is_whitespace) {
let st = parse_style_props(props);
for n in names.split(',') {
styles.add_style(&clean_quoted(n), st);
}
}
} else if let Some((kind, rest)) = KINDS.iter().find_map(|(w, k)| word(l, w).map(|r| (*k, r))) {
let Some(name) = rest.strip_suffix('{').map(str::trim).filter(|n| !n.is_empty()) else { continue };
let i = node(&mut d, &mut ids, &mut styles, name);
d.nodes[i].kind = kind.to_owned();
open = Some(i);
} else if let Some((from, rel, to)) = relation(l) {
let (a, b) = (node(&mut d, &mut ids, &mut styles, from), node(&mut d, &mut ids, &mut styles, to));
let contains = rel == "contains";
d.edges.push(Edge {
from: a,
to: b,
label: Some(format!("«{rel}»")),
line: if contains { Line::Solid } else { Line::Dotted },
start: if contains { Head::Contains } else { Head::None },
end: if contains { Head::None } else { Head::Arrow },
minlen: 1,
style: EdgeStyle::default(),
on_cluster: [None; 2],
});
}
if d.nodes.len() + d.edges.len() > MAX_ITEMS {
return None;
}
}
for (name, i) in ids {
d.nodes[i].style = styles.get(&name);
}
(!d.nodes.is_empty()).then_some(d)
}
/// The node `name` (`"quoted"`, maybe with a `:::class`) names, added if it's new.
fn node(d: &mut Requirements, ids: &mut HashMap<String, usize>, styles: &mut StyleSheet, name: &str) -> usize {
let (name, class) = name.split_once(":::").map_or((name, None), |(n, c)| (n, Some(c.trim())));
let name = clean_quoted(name);
let i = *ids.entry(name.clone()).or_insert_with(|| {
d.nodes.push(Req { name, kind: String::new(), fields: Vec::new(), style: NodeStyle::default() });
d.nodes.len() - 1
});
if let Some(c) = class {
styles.add_class(&d.nodes[i].name, c);
}
i
}
/// `a - satisfies -> b`, or `b <- satisfies - a`: the source, the relationship and the target.
fn relation(l: &str) -> Option<(&str, &'static str, &str)> {
let (from, mid, to) = if let Some((left, to)) = l.split_once("->") {
let (from, mid) = left.rsplit_once('-')?;
(from, mid, to)
} else {
let (to, right) = l.split_once("<-")?;
let (mid, from) = right.split_once('-')?;
(from, mid, to)
};
let rel = RELATIONS.iter().find(|r| r.eq_ignore_ascii_case(mid.trim()))?;
let (from, to) = (from.trim(), to.trim());
(!from.is_empty() && !to.is_empty()).then_some((from, rel, to))
}
fn title_case(s: &str) -> String {
let mut c = s.chars();
c.next().map_or_else(String::new, |f| f.to_uppercase().chain(c.flat_map(char::to_lowercase)).collect())
}
const SPACING: Spacing = Spacing { node: 40.0, rank: 56.0, cluster: 16.0 };
pub(crate) fn draw(d: &Requirements, paint: &DiagramStyle, hover: Option<(Hover, Color)>) -> Option<Scene> {
let nodes: Vec<DrawNode> =
d.nodes.iter().map(|r| class_box((!r.kind.is_empty()).then_some(r.kind.as_str()), &r.name, &r.fields, &[], None, r.style, paint)).collect();
draw_layered(d.dir, &nodes, &d.edges, &[], &SPACING, paint, hover)
}
#[cfg(test)]
#[path = "requirement_tests.rs"]
mod tests;
@@ -0,0 +1,36 @@
use super::*;
fn reqs(src: &str) -> Requirements {
match crate::parse(src).map(|p| p.diagram) {
Some(crate::Diagram::Requirement(r)) => r,
_ => panic!("not a requirement diagram: {src:?}"),
}
}
#[test]
fn blocks_fields_and_relationships() {
let d = reqs(
"requirementDiagram\n direction LR\n requirement test_req {\n id: 1\n text: the test text.\n risk: high\n verifymethod: test\n }\n functionalRequirement \"Fast start\":::hot {\n id: 1.1\n risk: LOW }\n element test_entity {\n type: simulation\n docref: reqs/test_entity\n }\n test_entity - satisfies -> test_req\n test_req - contains -> \"Fast start\"\n test_req <- copies - other\n a - likes -> b\n classDef hot fill:#f96",
);
assert_eq!(d.dir, Dir::Right);
let names: Vec<&str> = d.nodes.iter().map(|n| n.name.as_str()).collect();
assert_eq!(names, ["test_req", "Fast start", "test_entity", "other"]);
assert_eq!(d.nodes[0].fields, ["ID: 1", "Text: the test text.", "Risk: High", "Verification: Test"]);
assert_eq!((d.nodes[1].kind.as_str(), d.nodes[1].fields.as_slice()), ("Functional Requirement", &["ID: 1.1".to_owned(), "Risk: Low".to_owned()][..]));
assert_eq!(d.nodes[2].fields, ["Type: simulation", "Doc Ref: reqs/test_entity"]);
assert_eq!(d.nodes[3].kind, "", "a name only related is a bare box");
assert!(d.nodes[1].style.fill.is_some());
assert_eq!(d.edges.len(), 3, "an unknown relationship is skipped");
assert_eq!((d.edges[0].from, d.edges[0].to, d.edges[0].label.as_deref()), (2, 0, Some("«satisfies»")));
assert_eq!((d.edges[1].start, d.edges[1].line), (Head::Contains, Line::Solid));
assert_eq!((d.edges[2].from, d.edges[2].to, d.edges[2].end), (3, 0, Head::Arrow), "`<-` points back");
assert!(crate::parse("requirementDiagram\n direction TB").is_none());
}
#[test]
fn draws_each_box_with_its_fields() {
let s = crate::scene("requirementDiagram\nrequirement r {\nid: 7\n}\nelement e {\ntype: code\n}\ne - verifies -> r", &DiagramStyle::neutral(false), None).unwrap();
for t in ["«Requirement»", "r", "ID: 7", "«Element»", "Type: code", "«verifies»"] {
assert!(s.labels.iter().any(|l| l.text == t), "{t}");
}
}
+566
View File
@@ -0,0 +1,566 @@
//! State diagrams (`stateDiagram` and `stateDiagram-v2`), laid out on [`crate::layout::draw`].
use std::collections::HashMap;
use rune::Color;
use super::lenient::{Lenient, Reader};
use crate::canvas::parts::Names;
use crate::canvas::{Measured, Scene, measure_balanced};
use crate::layout::draw::{ClusterSpec, Dir, DrawNode, Edge, Head, Line, NodeShape, layered_canvas, node_size};
use crate::layout::layered::Spacing;
use crate::{
DiagramStyle, EdgeStyle, Hover, MAX_DEPTH, MAX_ITEMS, NodeStyle, StyleSheet, clean_quoted, statements,
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum StateKind {
Normal,
Start,
End,
Choice,
Bar,
Note,
}
#[derive(Debug)]
pub(crate) struct StateNode {
pub id: String,
pub label: String,
pub desc: Vec<String>,
pub kind: StateKind,
pub cluster: Option<usize>,
pub style: NodeStyle,
}
#[derive(Debug)]
pub(crate) struct Composite {
pub title: String,
pub parent: Option<usize>,
/// One of a composite's concurrent regions, split by `--`.
pub region: bool,
}
#[derive(Debug)]
pub(crate) struct StateDiagram {
pub title: Option<String>,
pub dir: Dir,
pub states: Vec<StateNode>,
pub edges: Vec<Edge>,
pub composites: Vec<Composite>,
}
pub(crate) fn parse(header: &str, body: &[&str]) -> Option<StateDiagram> {
let mut p = Parser {
d: StateDiagram { title: None, dir: Dir::Down, states: Vec::new(), edges: Vec::new(), composites: Vec::new() },
ids: HashMap::new(),
composite_ids: HashMap::new(),
stack: Vec::new(),
mode: Mode::Reading,
pseudo_seq: 0,
styles: StyleSheet::default(),
over: false,
};
let mut reader = Reader::default();
for line in std::iter::once(header).chain(body.iter().copied()) {
if p.step(Event::Line(line), &mut reader).is_none() && p.over {
return None;
}
}
// A note left open closes at the end.
if p.step(Event::End, &mut reader).is_none() && p.over {
return None;
}
for (id, &idx) in &p.ids {
p.d.states[idx].style = p.styles.get(id);
}
p.resolve_composites();
(!p.d.states.is_empty()).then_some(p.d)
}
struct Parser {
d: StateDiagram,
ids: HashMap<String, usize>,
composite_ids: HashMap<String, usize>,
stack: Vec<usize>,
/// Whether the parser is reading statements or inside a multi-line note.
mode: Mode,
pseudo_seq: usize,
styles: StyleSheet,
/// Set once the source goes past [`MAX_ITEMS`] or [`MAX_DEPTH`].
over: bool,
}
/// Reading statements, or inside a note the source has not closed yet.
#[derive(Debug)]
enum Mode {
Reading,
/// A multi-line note being read: its state, side and lines so far.
InNote { target: String, side: Side, lines: Vec<String> },
}
/// One thing the parser steps through: a source line, or the end of the input.
#[derive(Clone, Copy, Debug)]
enum Event<'a> {
Line(&'a str),
End,
}
impl Lenient for Parser {
type Mark = (usize, usize);
fn mark(&self) -> (usize, usize) {
(self.d.states.len(), self.d.edges.len())
}
fn undo(&mut self, (states, edges): (usize, usize)) {
self.d.states.truncate(states);
self.d.edges.truncate(edges);
self.ids.retain(|_, &mut i| i < states);
}
fn read_statement(&mut self, s: &str) -> Option<()> {
self.statement(s)
}
fn over(&self) -> bool {
self.over
}
}
impl Parser {
fn budget(&mut self) -> Option<()> {
self.over |= self.d.states.len() + self.d.edges.len() + self.d.composites.len() >= MAX_ITEMS;
(!self.over).then_some(())
}
/// Steps one source line in whatever mode the parser is in, or closes a note left open at the
/// end of the input. `None` once the diagram is past its bounds.
fn step(&mut self, event: Event<'_>, reader: &mut Reader) -> Option<()> {
let mode = std::mem::replace(&mut self.mode, Mode::Reading);
match (mode, event) {
(Mode::Reading, Event::End) => Some(()),
(Mode::Reading, Event::Line(line)) => {
for stmt in statements(line) {
reader.read(self, stmt)?;
}
Some(())
}
(Mode::InNote { target, side, mut lines }, Event::Line(line)) => {
let line = line.trim();
if !line.eq_ignore_ascii_case("end note") {
lines.push(line.to_owned());
self.mode = Mode::InNote { target, side, lines };
return Some(());
}
self.add_note(&target, side, &lines.join("\n"))
}
(Mode::InNote { target, side, lines }, Event::End) => {
self.add_note(&target, side, &lines.join("\n"))
}
}
}
fn statement(&mut self, s: &str) -> Option<()> {
if s == "}" {
let top = self.stack.pop()?;
if self.d.composites[top].region {
self.stack.pop();
}
return Some(());
}
if s == "--" {
return self.divide();
}
let word = s.split(|c: char| c.is_whitespace() || c == ':').next().unwrap_or("");
match word {
"title" => {
let t = clean_quoted(s["title".len()..].trim());
if !t.is_empty() {
self.d.title = Some(t);
}
}
"direction" => {
let rest = s["direction".len()..].trim();
let dir = Dir::parse(rest)?;
if self.stack.is_empty() && self.d.edges.is_empty() {
self.d.dir = dir;
}
}
"note" | "Note" => self.note(s[word.len()..].trim())?,
"hide" | "accTitle" | "accDescr" => {}
"classDef" => {
let _ = self.styles.class_def(&s["classDef".len()..]);
}
"class" => {
let _ = self.styles.assign_classes(&s["class".len()..]);
}
"style" => {
let _ = self.styles.style(&s["style".len()..]);
}
"state" => self.state_decl(s["state".len()..].trim())?,
_ if s.contains("-->") => self.transition(s)?,
_ if s.contains(':') => self.description(s)?,
_ => {
if !valid_state_id(s) {
return None;
}
self.ensure_state(s)?;
}
}
Some(())
}
fn state_decl(&mut self, rest: &str) -> Option<()> {
let opens = rest.ends_with('{');
let core = if opens { rest[..rest.len() - 1].trim() } else { rest };
if let Some((id_part, stereo)) = core.split_once("<<") {
let stereo = stereo.strip_suffix(">>")?.trim().to_ascii_lowercase();
let kind = match stereo.as_str() {
"choice" => StateKind::Choice,
"fork" | "join" => StateKind::Bar,
_ => StateKind::Normal,
};
let id = id_part.trim();
if !valid_state_id(id) {
return None;
}
let idx = self.ensure_state(id)?;
self.d.states[idx].kind = kind;
return Some(());
}
let named = name_and_label(core).filter(|(id, _)| valid_state_id(id));
if opens {
self.budget()?;
if self.stack.len() >= MAX_DEPTH {
self.over = true;
return None;
}
// A composite whose name doesn't read still opens, so its `}` closes it and not its parent.
let title = named.as_ref().map_or_else(|| clean_quoted(core), |(_, l)| l.clone());
self.d.composites.push(Composite { title, parent: self.stack.last().copied(), region: false });
let cid = self.d.composites.len() - 1;
if let Some((id, _)) = named {
self.composite_ids.insert(id.to_owned(), cid);
}
self.stack.push(cid);
} else {
let (id, label) = named?;
let idx = self.ensure_state(id)?;
self.d.states[idx].label = label;
}
Some(())
}
fn transition(&mut self, s: &str) -> Option<()> {
let arrow = s.find("-->")?;
let left_raw = s[..arrow].trim();
let after = s[arrow + 3..].trim();
let (right_raw, label) = match after.split_once(':') {
Some((r, l)) => {
let text = clean_quoted(l);
(r.trim(), (!text.is_empty()).then_some(text))
}
None => (after, None),
};
let from = self.endpoint(left_raw, true)?;
let to = self.endpoint(right_raw, false)?;
self.budget()?;
self.d.edges.push(Edge {
from: from[0],
to: to[0],
label,
line: Line::Solid,
start: Head::None,
end: Head::Arrow,
minlen: 1,
style: EdgeStyle::default(),
on_cluster: [None; 2],
});
self.hold_regions(&from, &to);
Some(())
}
/// Invisible edges that keep a composite's other regions beside the one an edge is drawn to,
/// for edges that run forward in the source; a back edge (`retry --> Ready`) holds nothing, so
/// breaking its cycle can't flip a region below what follows the composite.
fn hold_regions(&mut self, from: &[usize], to: &[usize]) {
let forward = from.iter().max() < to.iter().min();
if !forward {
return;
}
let pairs = from[1..].iter().map(|&f| (f, to[0])).chain(to[1..].iter().map(|&t| (from[0], t)));
for (from, to) in pairs.collect::<Vec<_>>() {
if self.budget().is_none() {
return;
}
self.d.edges.push(Edge {
from,
to,
label: None,
line: Line::Invisible,
start: Head::None,
end: Head::None,
minlen: 1,
style: EdgeStyle::default(),
on_cluster: [None; 2],
});
}
}
/// Where an edge meets composite `cid`: it enters at the first state of each region and leaves
/// from the last, the first region's being the one drawn.
fn composite_ends(&self, cid: usize, leaving: bool) -> Vec<usize> {
let regions: Vec<usize> = (0..self.d.composites.len()).filter(|&r| self.d.composites[r].region && self.d.composites[r].parent == Some(cid)).collect();
let scopes = if regions.is_empty() { vec![cid] } else { regions };
let pick = |scope: usize| {
let mut members = (0..self.d.states.len()).filter(|&i| self.d.states[i].kind != StateKind::Note && self.within(self.d.states[i].cluster, scope));
if leaving { members.filter(|&i| self.d.states[i].kind != StateKind::Start).last() } else { members.next() }
};
scopes.into_iter().filter_map(pick).collect()
}
fn description(&mut self, s: &str) -> Option<()> {
let (id, desc) = s.split_once(':')?;
let id = self.styles.strip_inline(id)?;
if !valid_state_id(&id) {
return None;
}
let idx = self.ensure_state(&id)?;
let text = clean_quoted(desc);
if !text.is_empty() {
self.d.states[idx].desc.push(text);
}
Some(())
}
fn endpoint(&mut self, raw: &str, is_start: bool) -> Option<Vec<usize>> {
if raw == "[*]" {
self.budget()?;
self.pseudo_seq += 1;
let scope = self.stack.last().copied();
let key = format!("__pseudo_{}_{}_{:?}", if is_start { "start" } else { "end" }, self.pseudo_seq, scope);
let kind = if is_start { StateKind::Start } else { StateKind::End };
self.d.states.push(StateNode { id: key, label: String::new(), desc: Vec::new(), kind, cluster: scope, style: NodeStyle::default() });
return Some(vec![self.d.states.len() - 1]);
}
let id = self.styles.strip_inline(raw)?;
if !valid_state_id(&id) {
return None;
}
if let Some(&cid) = self.composite_ids.get(&id) {
let ends = self.composite_ends(cid, is_start);
if !ends.is_empty() {
return Some(ends);
}
}
Some(vec![self.ensure_state(&id)?])
}
/// A state named before its composite was declared (`[*] --> Busy`, then `state Busy {`) is
/// that composite: its edges move onto the composite as if named after it, and it goes.
fn resolve_composites(&mut self) {
let mut moves: HashMap<usize, (Vec<usize>, Vec<usize>)> = HashMap::new();
for (id, &cid) in &self.composite_ids {
let Some(&at) = self.ids.get(id) else { continue };
if self.within(self.d.states[at].cluster, cid) {
continue;
}
let (enter, leave) = (self.composite_ends(cid, false), self.composite_ends(cid, true));
if !enter.is_empty() && !leave.is_empty() {
moves.insert(at, (enter, leave));
}
}
if moves.is_empty() {
return;
}
for e in 0..self.d.edges.len() {
let (from, to) = (self.d.edges[e].from, self.d.edges[e].to);
let from = moves.get(&from).map_or_else(|| vec![from], |m| m.1.clone());
let to = moves.get(&to).map_or_else(|| vec![to], |m| m.0.clone());
(self.d.edges[e].from, self.d.edges[e].to) = (from[0], to[0]);
self.hold_regions(&from, &to);
}
let mut remap = Vec::with_capacity(self.d.states.len());
let mut kept = 0;
for i in 0..self.d.states.len() {
remap.push(kept);
kept += usize::from(!moves.contains_key(&i));
}
for e in &mut self.d.edges {
(e.from, e.to) = (remap[e.from], remap[e.to]);
}
let mut i = 0;
self.d.states.retain(|_| {
i += 1;
!moves.contains_key(&(i - 1))
});
self.ids.clear();
}
/// Whether `cluster` is composite `cid` or sits inside it.
fn within(&self, mut cluster: Option<usize>, cid: usize) -> bool {
for _ in 0..=MAX_DEPTH {
match cluster {
Some(c) if c == cid => return true,
Some(c) => cluster = self.d.composites[c].parent,
None => return false,
}
}
false
}
/// `--` inside a composite: what came before becomes its first region, and a new one opens.
fn divide(&mut self) -> Option<()> {
let &top = self.stack.last()?;
let parent = if self.d.composites[top].region {
self.stack.pop();
self.d.composites[top].parent?
} else {
let first = self.region(top)?;
for st in &mut self.d.states {
if st.cluster == Some(top) {
st.cluster = Some(first);
}
}
for (i, c) in self.d.composites.iter_mut().enumerate() {
if i != first && c.parent == Some(top) {
c.parent = Some(first);
}
}
top
};
let next = self.region(parent)?;
self.stack.push(next);
Some(())
}
fn region(&mut self, parent: usize) -> Option<usize> {
self.budget()?;
if self.stack.len() >= MAX_DEPTH {
self.over = true;
return None;
}
self.d.composites.push(Composite { title: String::new(), parent: Some(parent), region: true });
Some(self.d.composites.len() - 1)
}
/// `right of A : text` on one line, or `left of A` opening a note that `end note` closes.
fn note(&mut self, rest: &str) -> Option<()> {
let (place, text) = rest.split_once(':').map_or((rest, None), |(p, t)| (p.trim(), Some(t)));
let lower = place.to_ascii_lowercase();
let (side, target) = if let Some(t) = lower.strip_prefix("right of ") {
(Side::Right, &place[place.len() - t.len()..])
} else if let Some(t) = lower.strip_prefix("left of ") {
(Side::Left, &place[place.len() - t.len()..])
} else {
return None;
};
let target = target.trim();
if !valid_state_id(target) {
return None;
}
match text {
Some(t) => self.add_note(target, side, &clean_quoted(t)),
None => {
self.mode = Mode::InNote { target: target.to_owned(), side, lines: Vec::new() };
Some(())
}
}
}
/// A note beside `target`, joined to it by a dotted line.
fn add_note(&mut self, target: &str, side: Side, text: &str) -> Option<()> {
let at = self.ensure_state(target)?;
self.budget()?;
let cluster = self.d.states[at].cluster;
let id = format!("__note_{}", self.d.states.len());
self.d.states.push(StateNode { id, label: text.to_owned(), desc: Vec::new(), kind: StateKind::Note, cluster, style: NodeStyle::default() });
let note = self.d.states.len() - 1;
let (from, to) = if side == Side::Left { (note, at) } else { (at, note) };
self.budget()?;
self.d.edges.push(Edge { from, to, label: None, line: Line::Dotted, start: Head::None, end: Head::None, minlen: 1, style: EdgeStyle::default(), on_cluster: [None; 2] });
Some(())
}
fn ensure_state(&mut self, id: &str) -> Option<usize> {
let cluster = self.stack.last().copied();
if let Some(&i) = self.ids.get(id) {
if self.d.states[i].cluster.is_none() {
self.d.states[i].cluster = cluster;
}
return Some(i);
}
self.budget()?;
self.d.states.push(StateNode {
id: id.to_owned(),
label: id.to_owned(),
desc: Vec::new(),
kind: StateKind::Normal,
cluster,
style: NodeStyle::default(),
});
let idx = self.d.states.len() - 1;
self.ids.insert(id.to_owned(), idx);
Some(idx)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Side {
Left,
Right,
}
/// `"Label" as id`, `Label as id` or a bare `id`.
fn name_and_label(core: &str) -> Option<(&str, String)> {
if let Some(after_q) = core.strip_prefix('"') {
let end_q = after_q.find('"')?;
let label = clean_quoted(&core[..end_q + 2]);
let id = after_q[end_q + 1..].trim().strip_prefix("as ")?.trim();
Some((id, label))
} else if let Some((label, id)) = core.split_once(" as ") {
Some((id.trim(), clean_quoted(label)))
} else {
Some((core.trim(), clean_quoted(core)))
}
}
fn valid_state_id(s: &str) -> bool {
!s.is_empty() && s.chars().all(|c| c.is_alphanumeric() || matches!(c, '_' | '-' | '.'))
}
const SPACING: Spacing = Spacing { node: 34.0, rank: 42.0, cluster: 14.0 };
pub(crate) fn draw(d: &StateDiagram, paint: &DiagramStyle, hover: Option<(Hover, Color)>) -> Option<Scene> {
let nodes: Vec<DrawNode> = d
.states
.iter()
.map(|s| match s.kind {
StateKind::Start => DrawNode::Start { cluster: s.cluster },
StateKind::End => DrawNode::End { cluster: s.cluster },
StateKind::Bar => DrawNode::Bar { cluster: s.cluster },
StateKind::Choice => DrawNode::Shape {
shape: NodeShape::Diamond,
label: Measured::default(),
size: [28.0, 28.0],
cluster: s.cluster,
style: s.style,
},
StateKind::Note => {
let label = measure_balanced(&s.label, paint.font);
DrawNode::Shape { shape: NodeShape::Note, size: node_size(NodeShape::Note, label.size), label, cluster: s.cluster, style: s.style }
}
StateKind::Normal => {
let full = if s.desc.is_empty() { s.label.clone() } else { format!("{}\n{}", s.label, s.desc.join("\n")) };
let label = measure_balanced(&full, paint.font);
DrawNode::Shape { shape: NodeShape::Round, size: node_size(NodeShape::Round, label.size), label, cluster: s.cluster, style: s.style }
}
})
.collect();
let clusters: Vec<ClusterSpec> = d.composites.iter().map(|c| ClusterSpec { title: c.title.clone(), parent: c.parent }).collect();
let names = Names::new(d.states.iter().map(|s| s.id.clone()).collect(), &d.edges, Vec::new());
let mut c = layered_canvas(d.dir, &nodes, &names.nodes, &d.edges, &clusters, &SPACING, paint, hover)?;
c.names = names;
c.finish_fit(paint)
}
#[cfg(test)]
#[path = "state_tests.rs"]
mod tests;
@@ -0,0 +1,118 @@
use super::*;
fn state(src: &str) -> StateDiagram {
match crate::parse(src).map(|p| p.diagram) {
Some(crate::Diagram::State(s)) => s,
_ => panic!("not a state diagram: {src:?}"),
}
}
#[test]
fn transitions_pseudostates_descriptions_and_composites() {
let s = state(
"stateDiagram-v2\n\
direction LR\n\
[*] --> Queued\n\
state \"In flight\" as Working {\n\
Queued --> Applying : turn starts\n\
Applying --> Check\n\
state Check <<choice>>\n\
Check --> Applied : commit landed\n\
Check --> Unapplied : stalled\n\
}\n\
Applied : Card moves to Review\n\
Applied --> [*]",
);
assert_eq!(s.dir, Dir::Right);
assert_eq!(s.composites.len(), 1);
assert_eq!(s.composites[0].title, "In flight");
assert!(s.states.iter().any(|st| st.kind == StateKind::Start));
assert!(s.states.iter().any(|st| st.kind == StateKind::End));
assert!(s.states.iter().any(|st| st.id == "Check" && st.kind == StateKind::Choice));
assert_eq!(s.states.iter().find(|st| st.id == "Applied").unwrap().desc, vec!["Card moves to Review"]);
let paint = DiagramStyle::neutral(true);
assert!(draw(&s, &paint, None).is_some());
}
#[test]
fn notes_sit_beside_their_state_on_a_dotted_line() {
let s = state("stateDiagram-v2\n Idle --> Busy\n note right of Idle : waits here\n note left of Busy\n does the work\n then stops\n end note");
let notes: Vec<&str> = s.states.iter().filter(|st| st.kind == StateKind::Note).map(|st| st.label.as_str()).collect();
assert_eq!(notes, ["waits here", "does the work\nthen stops"]);
let dotted: Vec<(&str, &str)> =
s.edges.iter().filter(|e| e.line == Line::Dotted).map(|e| (s.states[e.from].id.as_str(), s.states[e.to].id.as_str())).collect();
assert_eq!(dotted.len(), 2);
assert_eq!(dotted[0].0, "Idle", "a right note follows its state");
assert_eq!(dotted[1].1, "Busy", "a left note comes before it");
assert!(s.edges.iter().filter(|e| e.line == Line::Dotted).all(|e| e.end == Head::None));
assert!(draw(&s, &DiagramStyle::neutral(false), None).is_some());
let open = state("stateDiagram-v2\nnote right of A\n never closed");
assert_eq!(open.states.iter().filter(|st| st.kind == StateKind::Note).count(), 1, "a note left open closes at the end");
}
#[test]
fn concurrent_regions_split_a_composite() {
let s = state(
"stateDiagram-v2\n [*] --> Active\n state Active {\n [*] --> NumOff\n NumOff --> NumOn\n --\n [*] --> CapsOff\n CapsOff --> CapsOn\n --\n [*] --> ScrollOff\n }\n Active --> Done",
);
let regions: Vec<usize> = (0..s.composites.len()).filter(|&i| s.composites[i].region).collect();
assert_eq!(regions.len(), 3);
assert!(regions.iter().all(|&r| s.composites[r].parent == Some(0)));
let region_of = |id: &str| s.states.iter().find(|st| st.id == id).unwrap().cluster;
assert_eq!(region_of("NumOn"), Some(regions[0]));
assert_eq!(region_of("CapsOn"), Some(regions[1]));
assert_eq!(region_of("ScrollOff"), Some(regions[2]));
assert_eq!(region_of("Done"), None, "the closing brace closes the region and the composite");
assert!(!s.states.iter().any(|st| st.id == "Active"), "the state named before its composite is the composite");
let id = |i: usize| s.states[i].id.as_str();
let edges = |line: Line| s.edges.iter().filter(move |e| e.line == line);
let drawn: Vec<(&str, &str)> = edges(Line::Solid).filter(|e| id(e.to) == "Done").map(|e| (id(e.from), id(e.to))).collect();
assert_eq!(drawn, [("NumOn", "Done")], "an edge out leaves from the first region's last state");
let held: Vec<(&str, &str)> = edges(Line::Invisible).filter(|e| id(e.to) == "Done").map(|e| (id(e.from), id(e.to))).collect();
assert_eq!(held, [("CapsOn", "Done"), ("ScrollOff", "Done")], "the other regions are held above it");
assert_eq!(edges(Line::Invisible).filter(|e| s.states[e.from].kind == StateKind::Start && s.states[e.from].cluster.is_none()).count(), 2);
assert!(draw(&s, &DiagramStyle::neutral(true), None).is_some());
let back = state("stateDiagram-v2\n [*] --> Busy\n state Busy {\n [*] --> A\n --\n [*] --> B\n }\n Busy --> Check\n Check --> Busy : retry");
let held = |s: &StateDiagram| s.edges.iter().filter(|e| e.line == Line::Invisible).count();
assert_eq!(held(&back), 2, "the entry and the exit hold the second region; the retry back into it holds nothing");
}
#[test]
fn fork_join_and_choice() {
let s = state("stateDiagram-v2\n state f <<fork>>\n state j <<join>>\n state c <<choice>>\n [*] --> f\n f --> A\n f --> B\n A --> j\n B --> j\n j --> c\n c --> [*]");
let kind = |id: &str| s.states.iter().find(|st| st.id == id).unwrap().kind;
assert_eq!((kind("f"), kind("j"), kind("c")), (StateKind::Bar, StateKind::Bar, StateKind::Choice));
assert!(draw(&s, &DiagramStyle::neutral(false), None).is_some());
}
#[test]
fn only_sources_where_nothing_reads_are_rejected() {
for src in ["stateDiagram-v2", "stateDiagram\n}", "stateDiagram-v2\n-->\n--"] {
assert!(crate::parse(src).is_none(), "{src:?}");
}
}
#[test]
fn a_statement_that_does_not_read_is_skipped() {
let s = state("stateDiagram-v2\nstate Open {\n A --> B");
assert_eq!((s.states.len(), s.edges.len(), s.composites.len()), (2, 1, 1), "an open composite closes at the end");
let s = state("stateDiagram-v2\ndirection diagonal\nA --> B");
assert_eq!((s.dir, s.edges.len()), (Dir::Down, 1));
let s = state("stateDiagram-v2\nstate \"no id\" {\n A --> B\n}\nC --> A");
assert_eq!(s.composites[0].title, "no id");
assert_eq!(s.states.iter().filter(|st| st.cluster.is_none()).count(), 1, "its closing brace closes the unnamed composite");
// A block opener that doesn't read is skipped with its body, so its `}` doesn't close the
// composite around it.
let s = state("stateDiagram-v2\nstate Outer {\n state Bad<<x {\n A --> B\n }\n C --> D\n}\nE --> F");
let cluster = |id: &str| s.states.iter().find(|st| st.id == id).map(|st| st.cluster);
assert_eq!(cluster("A"), None, "the skipped body adds nothing");
assert_eq!((cluster("C"), cluster("E")), (Some(Some(0)), Some(None)));
}
#[test]
fn every_prefix_draws_or_falls_back_without_panicking() {
crate::tests::assert_prefixes_never_panic(
"stateDiagram-v2\n [*] --> Idle\n Idle --> Busy : prompt\n Busy --> Idle : done\n Idle --> [*]",
false,
);
}
@@ -0,0 +1,228 @@
//! Edges on layered diagrams: each routed through [`Ctx`], broken where its label sits, with its
//! heads at both ends and a hover trace.
use rune::{Align, Color, TextStyle};
use super::draw::{Edge, Head, Line};
use super::route::{Ctx, Route};
use crate::canvas::parts::{Kind, Part};
use crate::canvas::{Canvas, Measured, arrowhead, diamond_head, ellipse, lerp, rounded_rect, smooth, unit};
use crate::{DiagramStyle, adapt_stroke};
/// An arrowhead's length past its line's width, about Mermaid's 8 px marker.
const ARROW: f32 = 7.0;
/// The room a label takes on its edge: its text with a little air, where the line breaks off.
pub(crate) fn label_box(m: &Measured) -> [f32; 2] {
[m.size[0] + 12.0, m.size[1] + 6.0]
}
/// A subgraph's title drawn from `at`, with a little air.
pub(crate) fn title_box(m: &Measured, at: [f32; 2]) -> [f32; 4] {
[at[0] - 4.0, at[1] - 4.0, at[0] + m.size[0] + 4.0, at[1] + m.size[1] + 4.0]
}
/// How far a head of kind `h` takes its end of the line back.
pub(crate) fn inset(h: Head) -> f32 {
match h {
Head::None => 0.0,
Head::Arrow => ARROW * 0.7,
Head::Circle => 8.0,
Head::Contains => 12.0,
Head::Cross => 4.0,
Head::OpenTriangle => 10.0,
Head::DiamondFilled | Head::DiamondOpen => 12.0,
Head::OnlyOne | Head::ZeroOrOne | Head::OneOrMore | Head::ZeroOrMore => 0.0,
}
}
/// The colour and width `e` draws in.
fn pen(e: &Edge, paint: &DiagramStyle) -> (Color, f32) {
let width = e.style.width.unwrap_or(match e.line {
Line::Thick => 2.5,
_ => 1.25,
});
let color = e.style.stroke.map_or(paint.line, |col| adapt_stroke(paint.line, col, paint.node_fill.to_oklab()[0] < 0.5));
(color, width)
}
/// Every edge routed through `ctx`, with its label in a gap in the line (on a pill of `backs[i]`
/// where it would cover a subgraph's border); each edge's drawing and label are kept as a trace
/// so hovering either node, the edge or its label lights them up. Where an edge still has to
/// cross text, another edge's label or a subgraph's title (`titles`), the line breaks around it
/// the way it does around its own label.
#[allow(clippy::too_many_arguments)]
pub(crate) fn edges(c: &mut Canvas, ctx: &Ctx, edges: &[Edge], labels: &[Option<Measured>], backs: &[Color], titles: &[[f32; 4]], flip: bool, font: TextStyle, paint: &DiagramStyle) {
let routes: Vec<Option<(Route, Option<[f32; 4]>)>> = (0..edges.len())
.map(|i| {
let e = &edges[i];
(ctx.placed.paths[i].len() > 1).then(|| {
let r = ctx.route(i, flip, [inset(e.start), inset(e.end)]);
let gap = labels[i].as_ref().zip(r.label).map(|(m, at)| {
let s = label_box(m);
[at[0] - s[0] / 2.0, at[1] - s[1] / 2.0, at[0] + s[0] / 2.0, at[1] + s[1] / 2.0]
});
(r, gap)
})
})
.collect();
for (i, e) in edges.iter().enumerate() {
c.part(Some(Part::Index(Kind::Edge, i)));
let start = c.ops.len();
let (color, _) = pen(e, paint);
let back = backs.get(i).copied().unwrap_or(paint.surface);
let mut lit_label = None;
match &routes[i] {
None => {
let s = labels[i].as_ref().map_or(0.0, |m| label_box(m)[0]);
let at = self_loop(c, e, ctx.screen(ctx.placed.centers[e.from]), ctx.sizes[e.from], paint);
if let Some(m) = &labels[i] {
let b = label_box(m);
lit_label = Some((c.labels.len(), [at[0], at[1] - b[1] / 2.0, at[0] + b[0], at[1] + b[1] / 2.0], back));
c.label(m, [at[0] + s / 2.0, at[1]], font, paint.muted, Align::Center);
}
}
Some((r, gap)) => {
let others = routes.iter().enumerate().filter(|&(j, _)| j != i).filter_map(|(_, o)| o.as_ref().and_then(|o| o.1));
let mut runs = vec![r.curve.clone()];
for rect in gap.iter().copied().chain(titles.iter().copied()).chain(others) {
runs = runs.iter().flat_map(|run| outside(run, rect)).collect();
}
connector(c, &runs, [(r.tip_start, r.dir_start), (r.tip_end, r.dir_end)], e, paint);
if let (Some(m), Some(at), Some(g)) = (&labels[i], r.label, *gap) {
// A label left on a subgraph's border hides it, as the line does around it.
if ctx.on_border(g) {
c.fill(rounded_rect(g[0], g[1], g[2], g[3], 4.0), back);
}
lit_label = Some((c.labels.len(), g, back));
c.label(m, at, font, paint.muted, Align::Center);
}
}
}
// A label with no text draws nothing, so nothing lights.
let lit_label = lit_label.filter(|l| l.0 < c.labels.len());
c.trace(e.from, e.to, start, color, lit_label);
}
c.part(None);
}
/// The runs of `curve` outside `rect` (`[x0, y0, x1, y1]`), cut where they cross its edge.
pub(crate) fn outside(curve: &[[f32; 2]], rect: [f32; 4]) -> Vec<Vec<[f32; 2]>> {
let mut runs: Vec<Vec<[f32; 2]>> = vec![Vec::new()];
for w in curve.windows(2) {
let (a, b) = (w[0], w[1]);
let run = runs.last_mut().unwrap();
if run.is_empty() {
run.push(a);
}
match inside_span(a, b, rect) {
None => run.push(b),
Some((t0, t1)) => {
if t0 > 0.0 {
run.push(lerp(a, b, t0));
}
let mut next = Vec::new();
if t1 < 1.0 {
next.extend([lerp(a, b, t1), b]);
}
runs.push(next);
}
}
}
runs.retain(|r| r.len() >= 2);
runs
}
/// The part of `a`→`b` inside `rect`, as a range of `t` (Liang–Barsky).
fn inside_span(a: [f32; 2], b: [f32; 2], rect: [f32; 4]) -> Option<(f32, f32)> {
let d = [b[0] - a[0], b[1] - a[1]];
let (mut t0, mut t1) = (0.0f32, 1.0f32);
for (p, q) in [(-d[0], a[0] - rect[0]), (d[0], rect[2] - a[0]), (-d[1], a[1] - rect[1]), (d[1], rect[3] - a[1])] {
if p.abs() < 1e-9 {
if q < 0.0 {
return None;
}
} else {
let r = q / p;
if p < 0.0 { t0 = t0.max(r) } else { t1 = t1.min(r) }
}
}
(t0 < t1).then_some((t0, t1))
}
/// Draws `e` along `runs` (its curve, broken where a label sits) with its heads at `tips`
/// (`[start, end]`, each a tip and the unit direction it points).
pub(crate) fn connector(c: &mut Canvas, runs: &[Vec<[f32; 2]>], tips: [([f32; 2], [f32; 2]); 2], e: &Edge, paint: &DiagramStyle) {
let (color, width) = pen(e, paint);
for run in runs {
match e.line {
Line::Invisible => return,
Line::Dotted => c.dashed(run, width, color, 3.0, 3.0),
_ => c.stroke(run.clone(), false, width, color),
}
}
head(c, e.end, tips[1].0, tips[1].1, width, color, paint);
head(c, e.start, tips[0].0, tips[0].1, width, color, paint);
}
fn head(c: &mut Canvas, h: Head, tip: [f32; 2], d: [f32; 2], width: f32, color: Color, paint: &DiagramStyle) {
let back = |by: f32| [tip[0] - d[0] * by, tip[1] - d[1] * by];
match h {
Head::None => {}
Head::Arrow => c.fill(arrowhead(tip, d, ARROW + width, 5.0 + width * 1.6), color),
Head::OpenTriangle => c.shape(arrowhead(tip, d, 10.0, 9.0), paint.node_fill, color, width),
Head::DiamondFilled => c.fill(diamond_head(tip, d, 12.0, 8.0), color),
Head::DiamondOpen => c.shape(diamond_head(tip, d, 12.0, 8.0), paint.node_fill, color, width),
Head::Circle => c.shape(ellipse(back(4.0), 4.0, 4.0), paint.node_fill, color, width),
Head::Contains => {
let (m, n) = (back(6.0), [-d[1], d[0]]);
c.shape(ellipse(m, 6.0, 6.0), paint.node_fill, color, width);
c.stroke(vec![back(0.0), back(12.0)], false, width, color);
c.stroke(vec![[m[0] + n[0] * 6.0, m[1] + n[1] * 6.0], [m[0] - n[0] * 6.0, m[1] - n[1] * 6.0]], false, width, color);
}
Head::Cross => {
let m = back(4.0);
let (a, b) = ([d[0] + d[1], d[1] - d[0]], [d[0] - d[1], d[1] + d[0]]);
let k = 3.5 / std::f32::consts::SQRT_2;
c.stroke(vec![[m[0] - a[0] * k, m[1] - a[1] * k], [m[0] + a[0] * k, m[1] + a[1] * k]], false, width, color);
c.stroke(vec![[m[0] - b[0] * k, m[1] - b[1] * k], [m[0] + b[0] * k, m[1] + b[1] * k]], false, width, color);
}
Head::OnlyOne | Head::ZeroOrOne | Head::OneOrMore | Head::ZeroOrMore => crow(c, h, tip, d, width, color, paint),
}
}
/// A crow's-foot cardinality at `tip`: a foot for many, a bar for one, a ring for zero, with the
/// inner mark (minimum) furthest from the entity.
fn crow(c: &mut Canvas, h: Head, tip: [f32; 2], d: [f32; 2], width: f32, color: Color, paint: &DiagramStyle) {
let back = |by: f32| [tip[0] - d[0] * by, tip[1] - d[1] * by];
let n = [-d[1], d[0]];
let bar = |c: &mut Canvas, at: [f32; 2]| c.stroke(vec![[at[0] + n[0] * 6.0, at[1] + n[1] * 6.0], [at[0] - n[0] * 6.0, at[1] - n[1] * 6.0]], false, width, color);
let many = matches!(h, Head::OneOrMore | Head::ZeroOrMore);
if many {
let heel = back(12.0);
for side in [1.0, -1.0] {
c.stroke(vec![heel, [tip[0] + n[0] * 6.5 * side, tip[1] + n[1] * 6.5 * side]], false, width, color);
}
} else {
bar(c, back(5.0));
}
let inner = if many { 16.0 } else { 10.0 };
match h {
Head::OnlyOne | Head::OneOrMore => bar(c, back(inner)),
_ => c.shape(ellipse(back(inner + 4.0), 4.0, 4.0), paint.surface, color, width),
}
}
/// A loop off the node's right side; returns the left middle of where its label goes.
fn self_loop(c: &mut Canvas, e: &Edge, ctr: [f32; 2], size: [f32; 2], paint: &DiagramStyle) -> [f32; 2] {
let x = ctr[0] + size[0] / 2.0;
let (a, b) = ([x, ctr[1] - size[1] / 4.0], [x, ctr[1] + size[1] / 4.0]);
let mut path = [a, [x + 18.0, a[1] - 4.0], [x + 26.0, ctr[1]], [x + 18.0, b[1] + 4.0], b];
let n = path.len();
let (dir_end, dir_start) = (unit(path[n - 2], path[n - 1]), unit(path[1], path[0]));
let (tip_end, tip_start) = (path[n - 1], path[0]);
path[n - 1] = [tip_end[0] - dir_end[0] * inset(e.end), tip_end[1] - dir_end[1] * inset(e.end)];
path[0] = [tip_start[0] - dir_start[0] * inset(e.start), tip_start[1] - dir_start[1] * inset(e.start)];
connector(c, &[smooth(&path)], [(tip_start, dir_start), (tip_end, dir_end)], e, paint);
[x + 30.0, ctr[1]]
}
+459
View File
@@ -0,0 +1,459 @@
//! Shared node geometry, connector arrows and scene rendering on top of [`super::layered`] for
//! flowcharts, state diagrams and class diagrams.
use rune::{Align, Color, TextStyle};
use super::connector::{self, label_box, title_box};
use super::layered::{GCluster, GEdge, Graph, Spacing, layout};
use super::route::Ctx;
use crate::canvas::parts::{Kind, Part};
use crate::canvas::shape;
pub(crate) use crate::canvas::shape::{NodeShape, boundary, node_size, outline};
use crate::canvas::{Canvas, Measured, Scene, ellipse, measure_balanced, measure_wrap, over_color, room, rounded_rect};
use crate::chart::small;
use crate::{DiagramStyle, EdgeStyle, Hover, NodeStyle};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Dir {
Down,
Up,
Right,
Left,
}
impl Dir {
pub(crate) fn parse(s: &str) -> Option<Self> {
match s {
"" | "TD" | "TB" => Some(Dir::Down),
"BT" => Some(Dir::Up),
"LR" => Some(Dir::Right),
"RL" => Some(Dir::Left),
_ => None,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Line {
Solid,
Dotted,
Thick,
Invisible,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Head {
None,
Arrow,
Circle,
Cross,
OpenTriangle,
DiamondFilled,
DiamondOpen,
/// Entity-relationship cardinalities, drawn in crow's-foot notation.
OnlyOne,
ZeroOrOne,
OneOrMore,
ZeroOrMore,
/// A circle with a cross: the container's end of a requirement's `contains`.
Contains,
}
#[derive(Debug)]
pub(crate) struct Edge {
pub from: usize,
pub to: usize,
pub label: Option<String>,
pub line: Line,
pub start: Head,
pub end: Head,
pub minlen: usize,
pub style: EdgeStyle,
/// `[start, end]`: the subgraph whose border that end stops on, when the source linked the
/// subgraph itself. Its node (`from` or `to`) is a member that ranks it.
pub on_cluster: [Option<usize>; 2],
}
/// How far a horizontal diagram may shrink to fit before it turns top-down instead.
const TURN_BELOW: f32 = 0.78;
/// The least room around a subgraph's title, at its sides and above it. The title is centred
/// in a band across the top of its box, as mermaid.js draws it.
const TITLE_INSET: [f32; 2] = [12.0, 7.0];
/// Subgraph titles wider than this wrap; shorter ones keep one line and widen their box.
const TITLE_WRAP: f32 = 420.0;
pub(crate) struct ClusterSpec {
pub title: String,
pub parent: Option<usize>,
}
pub(crate) enum DrawNode {
Shape {
shape: NodeShape,
label: Measured,
size: [f32; 2],
cluster: Option<usize>,
style: NodeStyle,
},
Start {
cluster: Option<usize>,
},
End {
cluster: Option<usize>,
},
Bar {
cluster: Option<usize>,
},
ClassBox {
stereo: Option<Measured>,
name: Measured,
fields: Vec<Measured>,
methods: Vec<Measured>,
size: [f32; 2],
cluster: Option<usize>,
style: NodeStyle,
},
/// An entity: its name over a table of attributes, one row each, in columns `cols` wide.
Entity {
name: Measured,
rows: Vec<Vec<Measured>>,
cols: Vec<f32>,
size: [f32; 2],
style: NodeStyle,
},
/// Lines of text, each in its own font, down a filled shape in `[fill, border, text]` (C4
/// elements), under a person glyph when `person`.
Card {
shape: NodeShape,
lines: Vec<(Measured, TextStyle)>,
size: [f32; 2],
cluster: Option<usize>,
colors: [Color; 3],
person: bool,
},
}
impl DrawNode {
fn size(&self) -> [f32; 2] {
match self {
DrawNode::Shape { size, .. } | DrawNode::ClassBox { size, .. } | DrawNode::Entity { size, .. } | DrawNode::Card { size, .. } => *size,
DrawNode::Start { .. } => [18.0, 18.0],
DrawNode::End { .. } => [22.0, 22.0],
DrawNode::Bar { .. } => [64.0, 8.0],
}
}
fn shape(&self) -> NodeShape {
match self {
DrawNode::Shape { shape, .. } | DrawNode::Card { shape, .. } => *shape,
DrawNode::Start { .. } | DrawNode::End { .. } => NodeShape::Circle,
DrawNode::Bar { .. } | DrawNode::ClassBox { .. } | DrawNode::Entity { .. } => NodeShape::Rect,
}
}
fn cluster(&self) -> Option<usize> {
match self {
DrawNode::Shape { cluster, .. }
| DrawNode::Start { cluster }
| DrawNode::End { cluster }
| DrawNode::Bar { cluster }
| DrawNode::ClassBox { cluster, .. }
| DrawNode::Card { cluster, .. } => *cluster,
DrawNode::Entity { .. } => None,
}
}
}
pub(crate) fn draw_layered(
dir: Dir,
nodes: &[DrawNode],
edges: &[Edge],
clusters: &[ClusterSpec],
spacing: &Spacing,
paint: &DiagramStyle,
hover: Option<(Hover, Color)>,
) -> Option<Scene> {
let canvas = layered_canvas(dir, nodes, &[], edges, clusters, spacing, paint, hover)?;
canvas.finish_fit(paint)
}
/// [`draw_layered`] at full size, before [`Canvas::finish`], with each node's name in `ids`
/// (empty: known by index) for a diagram streaming in to hold each node to where it was.
#[allow(clippy::too_many_arguments, reason = "one layered diagram's whole drawing")]
pub(crate) fn layered_canvas(
dir: Dir,
nodes: &[DrawNode],
ids: &[String],
edges: &[Edge],
clusters: &[ClusterSpec],
spacing: &Spacing,
paint: &DiagramStyle,
hover: Option<(Hover, Color)>,
) -> Option<Canvas> {
let edge_font = small(paint);
let labels: Vec<Option<Measured>> = edges.iter().map(|e| e.label.as_ref().map(|l| measure_balanced(l, edge_font))).collect();
let title_font = TextStyle { weight: 500.0, ..edge_font };
let titles: Vec<Measured> = clusters.iter().map(|c| measure_wrap(&c.title, title_font, TITLE_WRAP)).collect();
let fonts = Fonts { edge: edge_font, title: title_font };
let parts = Parts { nodes, ids, edges, clusters, labels: &labels, titles: &titles };
let mut canvas = draw_in(dir, &parts, fonts, spacing, paint, hover)?;
// The turn: a horizontal diagram that would shrink below `TURN_BELOW` of its size to fit
// the card is drawn top-down instead, when that comes out narrower.
// A diagram streaming in that has turned stays turned.
let stay = super::steady::turned();
if (stay || canvas.width() > room(paint) / TURN_BELOW) && matches!(dir, Dir::Right | Dir::Left) {
let down = draw_in(if dir == Dir::Right { Dir::Down } else { Dir::Up }, &parts, fonts, spacing, paint, hover)?;
if stay || down.width() < canvas.width() {
canvas = down;
canvas.turned = true;
}
}
super::steady::set_turned(canvas.turned);
Some(canvas)
}
#[derive(Clone, Copy)]
struct Fonts {
edge: TextStyle,
title: TextStyle,
}
struct Parts<'a> {
nodes: &'a [DrawNode],
ids: &'a [String],
edges: &'a [Edge],
clusters: &'a [ClusterSpec],
labels: &'a [Option<Measured>],
titles: &'a [Measured],
}
fn draw_in(dir: Dir, p: &Parts, fonts: Fonts, spacing: &Spacing, paint: &DiagramStyle, hover: Option<(Hover, Color)>) -> Option<Canvas> {
let Parts { nodes, ids, edges, clusters, labels, titles } = *p;
let across = matches!(dir, Dir::Right | Dir::Left);
let ax = |s: [f32; 2]| if across { [s[1], s[0]] } else { s };
let flip = matches!(dir, Dir::Up | Dir::Left);
let graph = Graph {
sizes: nodes.iter().map(|n| ax(n.size())).collect(),
edges: edges
.iter()
.zip(labels)
.map(|(e, l)| {
let (from, to) = if flip { (e.to, e.from) } else { (e.from, e.to) };
GEdge { from, to, label: l.as_ref().map(|m| ax(label_box(m))), minlen: e.minlen }
})
.collect(),
node_cluster: nodes.iter().map(DrawNode::cluster).collect(),
clusters: clusters
.iter()
.zip(titles)
.map(|(s, t)| {
// The title's height and inset, so the gap under it matches the padding on every other side.
let lead = if t.text.is_empty() { 0.0 } else { t.size[1] + TITLE_INSET[1] };
let min_w = if t.text.is_empty() { 0.0 } else { t.size[0] + 2.0 * TITLE_INSET[0] };
GCluster {
parent: s.parent,
lead: if across { [lead, 0.0] } else { [0.0, lead] },
min_span: if across { [0.0, min_w] } else { [min_w, 0.0] },
}
})
.collect(),
ids: ids.to_vec(),
};
let placed = layout(&graph, spacing)?;
let pt = |p: [f32; 2]| if across { [p[1], p[0]] } else { p };
let mut c = Canvas { hover, ..Canvas::default() };
let chain_of = |mut c_opt: Option<usize>| {
let mut v = Vec::new();
while let Some(i) = c_opt {
if v.len() > clusters.len() {
break;
}
v.push(i);
c_opt = clusters[i].parent;
}
v.reverse();
v
};
let cluster_border = crate::canvas::group_border(paint);
let mut title_boxes = Vec::new();
let mut order: Vec<usize> = (0..clusters.len()).collect();
order.sort_by_key(|&i| chain_of(Some(i)).len());
for i in order {
let b = placed.clusters[i];
if b == [0.0; 4] {
continue;
}
let (p0, p1) = (pt([b[0], b[1]]), pt([b[2], b[3]]));
c.part(Some(Part::Index(Kind::Frame, i)));
c.shape(rounded_rect(p0[0], p0[1], p1[0], p1[1], 6.0), paint.cluster_fill, cluster_border, 1.0);
let at = [(p0[0] + p1[0] - titles[i].size[0]) / 2.0, p0[1] + TITLE_INSET[1]];
c.label_at(&titles[i], at, fonts.title, paint.muted, Align::Center);
if !titles[i].text.is_empty() {
title_boxes.push(title_box(&titles[i], at));
}
}
let centers: Vec<[f32; 2]> = placed.centers.iter().map(|&p| pt(p)).collect();
let sizes: Vec<[f32; 2]> = nodes.iter().map(DrawNode::size).collect();
let ends = edges.iter().map(|e| (e.from, e.to)).collect();
let boxes = labels.iter().map(|l| l.as_ref().map(|m| ax(label_box(m)))).collect();
let on_cluster: Vec<[Option<usize>; 2]> = edges.iter().map(|e| e.on_cluster).collect();
let ctx = Ctx::new(&placed, &sizes, nodes.iter().map(DrawNode::shape).collect(), boxes, across, ends)
.titles(title_boxes.iter().copied())
.cluster_ends(&on_cluster)
.homes(nodes.iter().map(|n| chain_of(n.cluster())), &(0..clusters.len()).map(|c| chain_of(Some(c))).collect::<Vec<_>>())
.fanned(flip);
// A label pill takes the colour of the innermost subgraph holding both its ends.
let backs: Vec<Color> = edges
.iter()
.map(|e| {
let (ca, cb) = (chain_of(nodes[e.from].cluster()), chain_of(nodes[e.to].cluster()));
let common = ca.iter().zip(&cb).take_while(|(x, y)| x == y).count();
(0..common).fold(paint.surface, |bg, _| over_color(paint.cluster_fill, bg))
})
.collect();
connector::edges(&mut c, &ctx, edges, labels, &backs, &title_boxes, flip, fonts.edge, paint);
for (i, n) in nodes.iter().enumerate() {
c.region(i, outline(n.shape(), centers[i], n.size()));
c.part(Some(Part::Index(Kind::Node, i)));
draw_node(&mut c, n, centers[i], paint);
}
c.part(None);
Some(c)
}
fn draw_node(c: &mut Canvas, node: &DrawNode, ctr: [f32; 2], paint: &DiagramStyle) {
match node {
DrawNode::Start { .. } => c.fill(ellipse(ctr, 8.0, 8.0), paint.line),
DrawNode::End { .. } => {
c.shape(ellipse(ctr, 10.0, 10.0), paint.node_fill, paint.line, 1.5);
c.fill(ellipse(ctr, 5.5, 5.5), paint.line);
}
DrawNode::Bar { .. } => {
let s = node.size();
c.fill(rounded_rect(ctr[0] - s[0] / 2.0, ctr[1] - s[1] / 2.0, ctr[0] + s[0] / 2.0, ctr[1] + s[1] / 2.0, 2.0), paint.line);
}
DrawNode::Shape { shape, label, size, style, .. } => {
let (fill, border, text_color) = style.resolve(paint);
let start = c.ops.len();
shape::draw(c, *shape, label, ctr, *size, [fill, border, text_color], paint);
// `stroke-width` sets the outline, which every shape draws 1 pt wide.
if let Some(w) = style.width {
for op in &mut c.ops[start..] {
if let crate::canvas::Op::Stroke { width, .. } = op {
*width *= w;
}
}
}
}
DrawNode::ClassBox { stereo, name, fields, methods, size, style, .. } => {
let (fill, border, text_color) = style.resolve(paint);
let (x0, y0, x1, y1) = (ctr[0] - size[0] / 2.0, ctr[1] - size[1] / 2.0, ctr[0] + size[0] / 2.0, ctr[1] + size[1] / 2.0);
c.shape(rounded_rect(x0, y0, x1, y1, 4.0), fill, border, 1.0);
let head_font = TextStyle { weight: 600.0, ..paint.font };
let mem_font = TextStyle { size: paint.font.size - 1.0, line_height: paint.font.line_height - 2.0, ..paint.font };
let stereo_font = TextStyle { size: paint.font.size - 2.0, line_height: paint.font.line_height - 4.0, italic: true, ..paint.font };
let mut y = y0 + 8.0;
if let Some(st) = stereo {
c.label(st, [ctr[0], y + st.size[1] / 2.0], stereo_font, paint.muted, Align::Center);
y += st.size[1] + 2.0;
}
c.label(name, [ctr[0], y + name.size[1] / 2.0], head_font, text_color, Align::Center);
y += name.size[1] + 8.0;
for section in [fields, methods] {
if section.is_empty() {
continue;
}
c.stroke(vec![[x0, y], [x1, y]], false, 1.0, border);
y += 6.0;
for item in section {
c.label_at(item, [x0 + 12.0, y], mem_font, text_color, Align::Start);
y += item.size[1] + 3.0;
}
y += 3.0;
}
}
DrawNode::Card { shape, lines, size, colors, person, .. } => {
shape::draw(c, *shape, &Measured::default(), ctr, *size, *colors, paint);
let cap = if *shape == NodeShape::Cylinder { shape::rim(size[0]) } else { 0.0 };
let glyph = if *person { PERSON } else { 0.0 };
let total = glyph + lines.iter().map(|l| l.0.size[1] + 3.0).sum::<f32>() - 3.0;
let mut y = ctr[1] - total / 2.0 + cap / 2.0;
if *person {
c.fill(ellipse([ctr[0], y + 6.0], 6.0, 6.0), colors[2]);
c.fill(crate::canvas::arc([ctr[0], y + 23.0], 11.0, 8.5, 180.0, 360.0, 16), colors[2]);
y += glyph;
}
for (m, font) in lines {
c.label(m, [ctr[0], y + m.size[1] / 2.0], *font, colors[2], Align::Center);
y += m.size[1] + 3.0;
}
}
DrawNode::Entity { name, rows, cols, size, style } => {
let (fill, border, text_color) = style.resolve(paint);
let (x0, y0, x1, y1) = (ctr[0] - size[0] / 2.0, ctr[1] - size[1] / 2.0, ctr[0] + size[0] / 2.0, ctr[1] + size[1] / 2.0);
let head_font = TextStyle { weight: 600.0, ..paint.font };
let row_font = TextStyle { size: paint.font.size - 1.0, line_height: paint.font.line_height - 2.0, ..paint.font };
let head_h = name.size[1] + ENTITY_PAD[1] * 2.0;
c.shape(rounded_rect(x0, y0, x1, y1, 4.0), fill, border, 1.0);
c.label(name, [ctr[0], y0 + head_h / 2.0], head_font, text_color, Align::Center);
let mut y = y0 + head_h;
let stripe = text_color.alpha(0.035);
for (r, row) in rows.iter().enumerate() {
let h = entity_row_h(row);
if r % 2 == 1 {
c.fill(vec![[x0 + 0.5, y], [x1 - 0.5, y], [x1 - 0.5, y + h], [x0 + 0.5, y + h]], stripe);
}
c.stroke(vec![[x0, y], [x1, y]], false, if r == 0 { 1.0 } else { 0.5 }, if r == 0 { border } else { border.alpha(0.5) });
let mut x = x0;
for (i, (cell, w)) in row.iter().zip(cols).enumerate() {
// Keys are muted; comments, last, are muted and may run the rest of the width.
let color = if i >= 2 { paint.muted } else { text_color };
c.label_at(cell, [x + ENTITY_PAD[0], y + (h - cell.size[1]) / 2.0], row_font, color, Align::Start);
x += w;
}
y += h;
}
}
}
}
/// The room a [`DrawNode::Card`]'s person glyph takes above its text.
pub(crate) const PERSON: f32 = 30.0;
/// A box of a stereotype, a name and two sections of rows (class members, requirement fields).
pub(crate) fn class_box(stereo: Option<&str>, name: &str, fields: &[String], methods: &[String], cluster: Option<usize>, style: NodeStyle, paint: &DiagramStyle) -> DrawNode {
let head_font = TextStyle { weight: 600.0, ..paint.font };
let mem_font = TextStyle { size: paint.font.size - 1.0, line_height: paint.font.line_height - 2.0, ..paint.font };
let stereo_font = TextStyle { size: paint.font.size - 2.0, line_height: paint.font.line_height - 4.0, italic: true, ..paint.font };
let stereo = stereo.map(|s| measure_wrap(&format!("«{s}»"), stereo_font, 240.0));
let name = measure_wrap(name, head_font, 240.0);
let fields: Vec<Measured> = fields.iter().map(|f| measure_wrap(f, mem_font, 240.0)).collect();
let methods: Vec<Measured> = methods.iter().map(|m| measure_wrap(m, mem_font, 240.0)).collect();
let mut w = name.size[0].max(stereo.as_ref().map_or(0.0, |s| s.size[0]));
for m in fields.iter().chain(&methods) {
w = w.max(m.size[0]);
}
let w = (w + 26.0).max(84.0);
let mut h = 16.0 + name.size[1] + stereo.as_ref().map_or(0.0, |s| s.size[1] + 2.0);
for sec in [&fields, &methods] {
if !sec.is_empty() {
h += 9.0 + sec.iter().map(|m| m.size[1] + 3.0).sum::<f32>();
}
}
DrawNode::ClassBox { stereo, name, fields, methods, size: [w, h.max(38.0)], cluster, style }
}
/// An entity's padding inside each cell: `[across, down]`.
pub(crate) const ENTITY_PAD: [f32; 2] = [10.0, 5.0];
pub(crate) fn entity_row_h(row: &[Measured]) -> f32 {
row.iter().map(|m| m.size[1]).fold(0.0, f32::max) + ENTITY_PAD[1] * 2.0
}
#[cfg(test)]
#[path = "draw_tests.rs"]
mod tests;
@@ -0,0 +1,249 @@
use crate::DiagramStyle;
use crate::canvas::{Canvas, Label, Op, measure_balanced};
/// A subgraph with a long title, a link to the subgraph itself and two labelled exits.
const CHAT: &str = "flowchart LR\n subgraph Thing[\"The chat (task): has a history\"]\n H1[your point] --> H2[result 1] --> H3[your reply] --> H4[result 2]\n end\n H4 -->|\"newest turn is a question\"| N[Needs you]\n H4 -->|\"newest turn is a result you haven't read\"| R[Ready]\n Note[(Note: lasts, has versions)] -.linked.- Thing";
fn paint_at(dark: bool, max_width: f32) -> DiagramStyle {
DiagramStyle { max_width, ..DiagramStyle::neutral(dark) }
}
fn canvas(src: &str, paint: &DiagramStyle) -> Canvas {
let Some(crate::Parsed { diagram: crate::Diagram::Flowchart(f), .. }) = crate::parse(src) else { panic!("parses: {src}") };
crate::graph::flowchart::draw_canvas(&f, paint, Some((crate::Hover::Edges, paint.text))).expect("draws")
}
fn label<'a>(c: &'a Canvas, text: &str) -> &'a Label {
c.labels.iter().find(|l| l.text == text).unwrap_or_else(|| panic!("no label {text:?}"))
}
fn rect(l: &Label) -> [f32; 4] {
[l.at[0], l.at[1], l.at[0] + l.size[0], l.at[1] + l.size[1]]
}
/// The first cluster's box: clusters draw first.
fn cluster(c: &Canvas) -> [f32; 4] {
let Some(Op::Fill(pts, _)) = c.ops.first() else { panic!("a cluster first") };
pts.iter().fold([f32::MAX, f32::MAX, f32::MIN, f32::MIN], |b, p| [b[0].min(p[0]), b[1].min(p[1]), b[2].max(p[0]), b[3].max(p[1])])
}
/// Every open stroke: edges, never outlines.
fn lines(c: &Canvas) -> impl Iterator<Item = &Vec<[f32; 2]>> {
c.ops.iter().filter_map(|op| match op {
Op::Stroke { points, closed: false, .. } => Some(points),
_ => None,
})
}
fn hits(w: &[[f32; 2]], r: [f32; 4]) -> bool {
(0..=16).any(|k| {
let p = crate::canvas::lerp(w[0], w[1], k as f32 / 16.0);
p[0] > r[0] && p[0] < r[2] && p[1] > r[1] && p[1] < r[3]
})
}
#[test]
fn no_edge_crosses_a_subgraph_title() {
for dark in [false, true] {
for width in [680.0, 420.0, 2000.0] {
let paint = paint_at(dark, width);
let c = canvas(CHAT, &paint);
let title = rect(label(&c, "The chat (task): has a history"));
for l in lines(&c) {
assert!(!l.windows(2).any(|w| hits(w, title)), "an edge crosses the title {title:?} at width {width}: {l:?}");
}
}
}
}
/// Each subgraph's title has the top of its box to itself, as in mermaid.js: one line, centred,
/// and no node or edge inside its band.
#[test]
fn subgraph_titles_keep_a_band_of_their_own() {
let plan = include_str!("../../fixtures/plan.mmd");
let titles = ["Prep, done", "Stage 2: first pass on the new parser (the pilot)", "AST track: the new parser reads the old tool's syntax trees", "Stage 3: formatter on the new parser", "Key"];
for dir in ["LR", "TD"] {
let src = plan.replacen("flowchart LR", &format!("flowchart {dir}"), 1);
for width in [680.0, 4000.0] {
let c = canvas(&src, &paint_at(true, width));
let boxes: Vec<[f32; 4]> = c.ops.iter().filter_map(|op| match op {
Op::Fill(pts, _) if pts.len() > 8 => Some(pts.iter().fold([f32::MAX, f32::MAX, f32::MIN, f32::MIN], |b, p| [b[0].min(p[0]), b[1].min(p[1]), b[2].max(p[0]), b[3].max(p[1])])),
_ => None,
}).collect();
for t in titles {
let l = label(&c, t);
let r = rect(l);
let what = format!("{t:?} {dir} at width {width}: {r:?}");
assert!(!l.wrap, "one line: {what}");
let b = boxes.iter().filter(|b| b[0] <= r[0] && b[2] >= r[2] && b[1] <= r[1] && b[3] >= r[3]).min_by(|a, b| (a[2] - a[0]).total_cmp(&(b[2] - b[0]))).unwrap_or_else(|| panic!("in a box: {what}"));
assert!(((b[0] + b[2]) / 2.0 - (r[0] + r[2]) / 2.0).abs() < 0.5, "centred in {b:?}: {what}");
let band = [b[0], b[1], b[2], r[3]];
for n in c.labels.iter().filter(|n| !titles.contains(&n.text.as_str())) {
let o = rect(n);
assert!(o[0] >= band[2] || o[2] <= band[0] || o[1] >= band[3] || o[3] <= band[1], "{:?} is in the band of {what}", n.text);
}
for l in lines(&c) {
assert!(!l.windows(2).any(|w| hits(w, r)), "an edge crosses {what}: {l:?}");
}
}
}
}
}
/// Edges that share a node meet it side by side, in the order they come from, never on one point.
#[test]
fn edges_sharing_an_end_fan_out() {
let plan = include_str!("../../fixtures/plan.mmd");
for dir in ["LR", "TD"] {
let fan = format!("flowchart {dir}\n A[one source] --> C[where they meet]\n B[another source] --> C\n X[far] --> C\n C --> D[next]\n C --> E[and next]");
let srcs = [plan.replacen("flowchart LR", &format!("flowchart {dir}"), 1), fan];
for (src, width) in srcs.iter().flat_map(|s| [(s, 680.0), (s, 4000.0)]) {
let paint = paint_at(true, width);
let c = canvas(src, &paint);
let tips: Vec<[f32; 2]> = c.ops.iter().filter_map(|op| match op {
Op::Fill(p, col) if *col == paint.line && p.len() == 3 => Some(p[0]),
_ => None,
}).collect();
let starts: Vec<[f32; 2]> = lines(&c).map(|l| l[0]).collect();
for (what, pts, gap) in [("arrowheads", &tips, 11.5), ("edges leaving", &starts, 6.0)] {
for (a, p) in pts.iter().enumerate() {
for q in &pts[a + 1..] {
let d = crate::canvas::dist(*p, *q);
assert!(d >= gap, "{what} {p:?} and {q:?} are {d} apart in {dir} at width {width}: {}", src.lines().next().unwrap_or(""));
}
}
}
}
}
}
/// Edges whose ends both lie outside a subgraph go around its box, as dagre routes them, never
/// through it.
#[test]
fn edges_route_around_subgraphs_they_do_not_belong_to() {
let plan = include_str!("../../fixtures/plan.mmd");
let past = "flowchart TD\n A[start] --> B[finish]\n subgraph S[In between]\n M1[one] --> M2[two] --> M3[three]\n end\n A --> M1\n M3 --> B\n A --> C[aside] --> B";
for dir in ["LR", "TD"] {
let srcs = [plan.replacen("flowchart LR", &format!("flowchart {dir}"), 1), past.replacen("flowchart TD", &format!("flowchart {dir}"), 1)];
for (src, width) in srcs.iter().flat_map(|s| [(s, 680.0), (s, 4000.0)]) {
let Some(crate::Parsed { diagram: crate::Diagram::Flowchart(f), .. }) = crate::parse(src) else { panic!() };
let c = canvas(src, &paint_at(true, width));
let bounds = |pts: &[[f32; 2]]| pts.iter().fold([f32::MAX, f32::MAX, f32::MIN, f32::MIN], |b, p| [b[0].min(p[0]), b[1].min(p[1]), b[2].max(p[0]), b[3].max(p[1])]);
let within = |v: usize, k: usize| std::iter::successors(f.nodes[v].cluster, |&s| f.subgraphs[s].parent).any(|s| s == k);
let boxes: Vec<[f32; 4]> = c.ops.iter().filter_map(|op| match op {
Op::Fill(pts, _) if pts.len() > 8 => Some(bounds(pts)),
_ => None,
}).collect();
for k in 0..f.subgraphs.len() {
let members: Vec<[f32; 4]> = (0..f.nodes.len()).filter(|&v| within(v, k)).map(|v| bounds(&c.regions[v])).collect();
let Some(b) = boxes.iter().filter(|b| members.iter().all(|m| b[0] < m[0] - 4.0 && b[1] < m[1] - 4.0 && b[2] > m[2] + 4.0 && b[3] > m[3] + 4.0)).min_by(|a, b| ((a[2] - a[0]) * (a[3] - a[1])).total_cmp(&((b[2] - b[0]) * (b[3] - b[1])))) else { continue };
let inner = [b[0] + 1.5, b[1] + 1.5, b[2] - 1.5, b[3] - 1.5];
for t in &c.traces {
if within(t.ends.0, k) || within(t.ends.1, k) {
continue;
}
let into = t.line.iter().find(|p| p[0] > inner[0] && p[0] < inner[2] && p[1] > inner[1] && p[1] < inner[3]);
assert!(into.is_none(), "{} → {} runs through {:?} at {into:?}, {dir} at width {width}", f.nodes[t.ends.0].id, f.nodes[t.ends.1].id, f.subgraphs[k].title);
}
}
}
}
}
#[test]
fn an_edge_to_a_subgraph_stops_on_its_border() {
let paint = DiagramStyle::neutral(false);
let c = canvas(CHAT, &paint);
let b = cluster(&c);
let dashes: Vec<&Vec<[f32; 2]>> = c.ops.iter().filter_map(|op| match op {
Op::Stroke { points, cap: rune::LineCap::Butt, .. } => Some(points),
_ => None,
}).collect();
assert!(!dashes.is_empty(), "the dotted link draws");
let inner = [b[0] + 0.5, b[1] + 0.5, b[2] - 0.5, b[3] - 0.5];
for d in &dashes {
assert!(!d.iter().any(|p| p[0] > inner[0] && p[0] < inner[2] && p[1] > inner[1] && p[1] < inner[3]), "the link reaches inside the subgraph {b:?}: {d:?}");
}
let near = dashes.iter().flat_map(|d| d.iter()).map(|p| {
let dx = (b[0] - p[0]).max(p[0] - b[2]).max(0.0);
let dy = (b[1] - p[1]).max(p[1] - b[3]).max(0.0);
dx.max(dy)
});
assert!(near.fold(f32::MAX, f32::min) < 1.5, "the link ends on the border {b:?}");
}
/// How far below its title a subgraph's first node sits, for `dir`.
fn title_gap(dir: &str) -> f32 {
let paint = paint_at(false, 4000.0);
let c = canvas(&format!("flowchart {dir}\n subgraph S[A title]\n A[One] --> B[Two]\n end"), &paint);
let t = rect(label(&c, "A title"));
let top = c.regions.iter().flatten().map(|p| p[1]).fold(f32::MAX, f32::min);
top - t[3]
}
#[test]
fn a_subgraph_title_keeps_the_same_gap_above_its_nodes_either_way() {
let (down, right) = (title_gap("TD"), title_gap("LR"));
assert!((down - right).abs() < 0.5, "TD {down} vs LR {right}");
assert!((down - 14.0).abs() < 0.5, "the gap {down} is the flowchart's subgraph padding");
}
#[test]
fn edges_leave_a_subgraph_steeply() {
for width in [680.0, 2000.0] {
let paint = paint_at(false, width);
let c = canvas(CHAT, &paint);
let b = cluster(&c);
let turned = b[3] - b[1] > b[2] - b[0];
let mut crossings = 0;
for l in lines(&c) {
for w in l.windows(2) {
let (a, z) = (w[0], w[1]);
// The far border along the rank axis: the bottom when turned, else the right.
let (along, across, edge) = if turned { (1, 0, b[3]) } else { (0, 1, b[2]) };
if (a[along] - edge) * (z[along] - edge) < 0.0 && a[across] > b[across] && a[across] < b[across + 2] {
crossings += 1;
let slope = (z[across] - a[across]).abs() / (z[along] - a[along]).abs();
assert!(slope < 0.6, "an edge leaves the subgraph at slope {slope} (width {width})");
}
}
}
assert_eq!(crossings, 2, "both exits cross the border once (width {width})");
}
}
#[test]
fn wrapped_labels_balance_their_lines() {
let paint = DiagramStyle::neutral(false);
let m = measure_balanced("newest turn is a result you haven't read", paint.font);
let one = measure_balanced("newest", paint.font).size[1];
assert!(m.wrap && m.size[1] < one * 2.5, "two lines: {:?}", m.size);
assert!(m.size[0] < 160.0, "balanced, not one long line and a lone word: {}", m.size[0]);
}
#[test]
fn a_chart_that_fits_its_card_keeps_its_direction() {
let narrow = paint_at(false, 300.0);
let wide = paint_at(false, 2000.0);
let tall = |c: &Canvas| {
let b = cluster(c);
b[3] - b[1] > b[2] - b[0]
};
assert!(!tall(&canvas(CHAT, &wide)), "LR stays LR with room");
assert!(tall(&canvas(CHAT, &narrow)), "LR turns down when it can't fit");
}
#[test]
fn an_edge_runs_straight_through_its_label() {
for width in [420.0, 680.0, 2000.0] {
let c = canvas(CHAT, &paint_at(false, width));
for text in ["newest turn is a question", "newest turn is a result you haven't read"] {
let r = rect(label(&c, text));
let off = |p: [f32; 2]| (r[0] - p[0]).max(p[0] - r[2]).max(r[1] - p[1]).max(p[1] - r[3]);
let ends: Vec<[f32; 2]> = lines(&c).flat_map(|l| [l[0], l[l.len() - 1]]).filter(|&p| off(p) > -0.5 && off(p) < 10.0).collect();
assert_eq!(ends.len(), 2, "the line stops either side of {text:?} (width {width}): {ends:?}");
let (a, b) = (ends[0], ends[1]);
assert!((a[0] - b[0]).abs() < 1.0 || (a[1] - b[1]).abs() < 1.0, "the line jogs through {text:?} (width {width}): {a:?} to {b:?}");
}
}
}
@@ -0,0 +1,623 @@
//! A small layered (Sugiyama) layout for flowcharts and state diagrams, top to bottom: cycles
//! broken by reversing DFS back edges, longest-path ranks on a doubled scale (so edge labels
//! get a rank of their own), long edges split by dummy nodes, barycentre ordering sweeps that
//! keep subgraphs contiguous, and positions from alternating weighted isotonic regressions
//! toward each node's neighbours. Other directions transpose or mirror the result.
//!
//! Sized for the diagrams agents write (tens of nodes): every step is at most quadratic in a
//! layer's edges.
use super::order::{order_layers, positions};
use super::steady::{self, Memo};
/// The most ranks one edge asks to span (`minlen`); longer links draw this long.
pub const MAX_MINLEN: usize = 8;
/// The most points long edges may add before a graph is left unlaid (see [`layout`]).
const MAX_DUMMIES: usize = 3000;
/// What to lay out. Sizes are in the layout's own axes: `[along a layer, across layers]`.
pub struct Graph {
pub sizes: Vec<[f32; 2]>,
pub edges: Vec<GEdge>,
/// Each node's innermost cluster.
pub node_cluster: Vec<Option<usize>>,
pub clusters: Vec<GCluster>,
/// Each node's name, which a build of a diagram streaming in knows it by (empty: by index).
pub ids: Vec<String>,
}
pub struct GEdge {
pub from: usize,
pub to: usize,
/// The label's size (same axes as nodes).
pub label: Option<[f32; 2]>,
/// Ranks the edge spans at least (`-->` 1, `--->` 2, …).
pub minlen: usize,
}
pub struct GCluster {
pub parent: Option<usize>,
/// Extra room at the cluster's leading edge along each axis (`[along, across]`), for its title.
pub lead: [f32; 2],
/// Minimum span along the horizontal screen axis (`[min_along, min_across]`) so titles fit.
pub min_span: [f32; 2],
}
pub struct Spacing {
pub node: f32,
pub rank: f32,
pub cluster: f32,
}
/// Where everything went, in layout axes, with the origin at the top-left of the content.
pub struct Placed {
pub centers: Vec<[f32; 2]>,
/// Per edge: the points from its source's centre to its target's centre (in edge
/// direction), through dummy nodes.
pub paths: Vec<Vec<[f32; 2]>>,
pub labels: Vec<Option<[f32; 2]>>,
/// Per cluster: `[x0, y0, x1, y1]`.
pub clusters: Vec<[f32; 4]>,
}
#[derive(Clone, Copy, PartialEq)]
enum Kind {
Real(usize),
/// A point on edge `e`; `true` for the one carrying its label.
Dummy(usize, bool),
}
pub(super) struct LNode {
kind: Kind,
pub(super) rank: usize,
size: [f32; 2],
cluster: Option<usize>,
pub(super) preds: Vec<usize>,
pub(super) succs: Vec<usize>,
}
/// `None` when long edges would need more than [`MAX_DUMMIES`] points: such a chart is too
/// tangled to read at markdown width, and every later step grows with that count.
pub fn layout(g: &Graph, sp: &Spacing) -> Option<Placed> {
steady::layout(&g.ids, |held| place(g, sp, held))
}
/// [`layout`], holding to `held` while a diagram streams in (see [`steady`]).
fn place(g: &Graph, sp: &Spacing, held: Option<&Memo>) -> Option<(Placed, Memo)> {
let n = g.sizes.len();
let chain = |mut c: Option<usize>| {
let mut v = Vec::new();
while let Some(i) = c {
if v.len() > g.clusters.len() {
break;
}
v.push(i);
c = g.clusters[i].parent;
}
v.reverse();
v
};
let chains: Vec<Vec<usize>> = (0..g.clusters.len()).map(|c| chain(Some(c))).collect();
let chain_of = |c: Option<usize>| c.map_or(&[][..], |c| chains[c].as_slice());
// 1. Break cycles: edges back to a node on the DFS stack are reversed.
let mut out: Vec<Vec<usize>> = vec![Vec::new(); n];
for (i, e) in g.edges.iter().enumerate() {
if e.from != e.to {
out[e.from].push(i);
}
}
let mut reversed = vec![false; g.edges.len()];
let mut state = vec![0u8; n];
for root in 0..n {
if state[root] != 0 {
continue;
}
let mut stack = vec![(root, 0usize)];
state[root] = 1;
while let Some((v, k)) = stack.last_mut() {
let v = *v;
if let Some(&e) = out[v].get(*k) {
*k += 1;
let w = g.edges[e].to;
match state[w] {
0 => {
state[w] = 1;
stack.push((w, 0));
}
1 => reversed[e] = true,
_ => {}
}
} else {
state[v] = 2;
stack.pop();
}
}
}
let ends = |i: usize| {
let e = &g.edges[i];
if reversed[i] { (e.to, e.from) } else { (e.from, e.to) }
};
let live: Vec<usize> = (0..g.edges.len()).filter(|&i| g.edges[i].from != g.edges[i].to).collect();
// 2. Ranks, doubled: every edge spans at least two, so its label has a rank to itself.
let span = |i: usize| 2 * g.edges[i].minlen.clamp(1, MAX_MINLEN);
let mut indeg = vec![0usize; n];
let mut succ: Vec<Vec<usize>> = vec![Vec::new(); n];
let mut pred: Vec<Vec<usize>> = vec![Vec::new(); n];
for &i in &live {
let (a, b) = ends(i);
indeg[b] += 1;
succ[a].push(i);
pred[b].push(i);
}
let mut topo = Vec::with_capacity(n);
let mut ready: Vec<usize> = (0..n).filter(|&v| indeg[v] == 0).rev().collect();
while let Some(v) = ready.pop() {
topo.push(v);
for &i in succ[v].iter().rev() {
let b = ends(i).1;
indeg[b] -= 1;
if indeg[b] == 0 {
ready.push(b);
}
}
}
for v in 0..n {
if !topo.contains(&v) {
topo.push(v);
}
}
let mut rank = vec![0usize; n];
for &v in &topo {
for &i in &pred[v] {
rank[v] = rank[v].max(rank[ends(i).0] + span(i));
}
}
// Pull sources down next to their first successor, so a late root doesn't trail a long edge.
for &v in topo.iter().rev() {
if pred[v].is_empty() && !succ[v].is_empty() {
rank[v] = succ[v].iter().map(|&i| rank[ends(i).1] - span(i)).min().unwrap_or(rank[v]);
}
}
if let Some(m) = held {
for &v in &topo {
let floor = rank[v].max(m.rank.get(v).copied().unwrap_or(0));
rank[v] = pred[v].iter().map(|&i| rank[ends(i).0] + span(i)).fold(floor, usize::max);
}
}
// 3. The layered graph: real nodes, then one dummy per rank an edge crosses.
let dummies: usize = live
.iter()
.map(|&i| {
let (a, b) = ends(i);
rank[b].saturating_sub(rank[a] + 1)
})
.sum();
if dummies > MAX_DUMMIES {
return None;
}
let mut nodes: Vec<LNode> = (0..n)
.map(|v| LNode { kind: Kind::Real(v), rank: rank[v], size: g.sizes[v], cluster: g.node_cluster[v], preds: Vec::new(), succs: Vec::new() })
.collect();
let mut edge_chain: Vec<Vec<usize>> = vec![Vec::new(); g.edges.len()];
for &i in &live {
let (a, b) = ends(i);
let (ca, cb) = (chain_of(g.node_cluster[a]), chain_of(g.node_cluster[b]));
let common = ca.iter().zip(cb).take_while(|(x, y)| x == y).count();
let cluster = (common > 0).then(|| ca[common - 1]);
let mid = rank[a] + (rank[b] - rank[a]) / 2;
let mut prev = a;
let mut chain = vec![a];
for r in rank[a] + 1..rank[b] {
let label = g.edges[i].label.filter(|_| r == mid);
let id = nodes.len();
nodes.push(LNode {
kind: Kind::Dummy(i, label.is_some()),
rank: r,
size: label.unwrap_or([0.0, 0.0]),
cluster,
preds: vec![prev],
succs: Vec::new(),
});
nodes[prev].succs.push(id);
chain.push(id);
prev = id;
}
nodes[prev].succs.push(b);
nodes[b].preds.push(prev);
chain.push(b);
edge_chain[i] = chain;
}
let ranks = nodes.iter().map(|v| v.rank).max().map_or(0, |r| r + 1);
// 4. Order within layers: DFS for a start, then barycentre sweeps; keep the fewest crossings.
let node_chains: Vec<&[usize]> = nodes.iter().map(|v| chain_of(v.cluster)).collect();
let parents: Vec<Option<usize>> = g.clusters.iter().map(|c| c.parent).collect();
let layers = order_layers(&nodes, n, ranks, &node_chains, &parents, held);
// 5. Positions along layers: pack, then pull each node toward its neighbours.
let seps: Vec<Vec<f32>> = layers
.iter()
.map(|layer| {
layer
.windows(2)
.map(|w| {
let (a, b) = (&nodes[w[0]], &nodes[w[1]]);
let real = |v: &LNode| matches!(v.kind, Kind::Real(_) | Kind::Dummy(_, true));
let gap = if real(a) && real(b) { sp.node } else { sp.node / 2.0 };
let (ca, cb) = (node_chains[w[0]], node_chains[w[1]]);
let common = ca.iter().zip(cb).take_while(|(x, y)| x == y).count();
let closing = (ca.len() - common) as f32 * sp.cluster;
let opening: f32 = cb[common..].iter().map(|&c| sp.cluster + g.clusters[c].lead[0]).sum();
(a.size[0] + b.size[0]) / 2.0 + gap + closing + opening
})
.collect()
})
.collect();
let mut x = vec![0.0f32; nodes.len()];
for (layer, sep) in layers.iter().zip(&seps) {
let mut at = 0.0;
for (i, &v) in layer.iter().enumerate() {
if i > 0 {
at += sep[i - 1];
}
x[v] = at;
}
}
// Streaming in, a node laid out last time stays there unless new ones need the room, and
// then only moves on (see [`steady`]).
let floor = |v: usize| held.filter(|_| v < n).and_then(|m| m.along.get(v)?.as_ref());
let weight = |v: &LNode| match v.kind {
Kind::Real(_) => 1.0,
Kind::Dummy(..) => 4.0,
};
for it in 0..24 {
let (use_preds, use_succs) = match it % 3 {
0 => (true, false),
1 => (false, true),
_ => (true, true),
};
let order: Vec<usize> = if it % 2 == 0 { (0..ranks).collect() } else { (0..ranks).rev().collect() };
for r in order {
let layer = &layers[r];
let mut want = Vec::with_capacity(layer.len());
let mut w = Vec::with_capacity(layer.len());
for &v in layer {
let node = &nodes[v];
let mut nb: Vec<usize> = Vec::new();
if use_preds {
nb.extend(&node.preds);
}
if use_succs {
nb.extend(&node.succs);
}
let (aim, pull) = match floor(v) {
Some(&at) => (at, HOLD),
None if nb.is_empty() => (x[v], 0.1),
None => (nb.iter().map(|&u| x[u]).sum::<f32>() / nb.len() as f32, weight(node) * nb.len() as f32),
};
want.push(aim);
w.push(pull);
}
let placed = isotonic_above(want, w, &seps[r], layer.iter().map(|&v| floor(v).copied()));
for (&v, p) in layer.iter().zip(placed) {
x[v] = p;
}
}
}
// 6. Layer depths, with room at each cluster's top and bottom.
let mut first = vec![usize::MAX; g.clusters.len()];
let mut last = vec![0usize; g.clusters.len()];
for (v, node) in nodes.iter().enumerate().take(n) {
for &c in node_chains[v] {
first[c] = first[c].min(node.rank);
last[c] = last[c].max(node.rank);
}
}
let heights: Vec<f32> = layers.iter().map(|l| l.iter().map(|&v| nodes[v].size[1]).fold(0.0, f32::max)).collect();
let mut y = vec![0.0f32; ranks];
let mut at = 0.0;
for r in 0..ranks {
let opening: f32 = (0..g.clusters.len()).filter(|&c| first[c] == r).map(|c| sp.cluster + g.clusters[c].lead[1]).sum();
if r > 0 {
let closing = (0..g.clusters.len()).filter(|&c| last[c] == r - 1 && first[c] != usize::MAX).count() as f32 * sp.cluster;
at += heights[r - 1] / 2.0 + sp.rank / 2.0 + closing;
}
at += opening;
if r > 0 || opening > 0.0 {
at += heights[r] / 2.0;
} else {
at = heights[0] / 2.0;
}
y[r] = at;
}
// Upright bends: a rank gap that an edge crosses far sideways grows (by at most another rank
// gap) until the edge's S, from the near side of one end to the near side of the other, runs
// twice as far along the ranks as across them, so it leaves nodes and subgraph borders
// steeply instead of squeezed.
let drawn = |v: usize| matches!(nodes[v].kind, Kind::Real(_) | Kind::Dummy(_, true));
// How far a port can slide toward the other end: a node's ports spread across its middle.
let slide = |v: usize| if matches!(nodes[v].kind, Kind::Real(_)) { nodes[v].size[0] / 4.0 } else { 0.0 };
let base = y.clone();
let mut grown = 0.0;
for r in 1..ranks {
let mut need = 0.0f32;
for &v in layers[r].iter().filter(|&&v| drawn(v)) {
for &u in nodes[v].preds.iter().filter(|&&u| drawn(u)) {
let dx = (x[u] - x[v]).abs() - slide(u) - slide(v);
let dy = (base[r] - nodes[v].size[1] / 2.0) - (base[r - 1] + nodes[u].size[1] / 2.0);
need = need.max(2.0 * dx - dy);
}
}
grown += need.clamp(0.0, sp.rank);
y[r] += grown;
}
if let Some(m) = held {
let fresh = y.clone();
for r in 1..ranks {
let was = m.depth.get(r).zip(m.depth.get(r - 1)).map_or(0.0, |(b, a)| b - a);
y[r] = y[r - 1] + (fresh[r] - fresh[r - 1]).max(was);
}
}
// 7. Cluster boxes from their members (nested ones included).
let mut depth_order: Vec<usize> = (0..g.clusters.len()).collect();
depth_order.sort_by_key(|&c| std::cmp::Reverse(chains[c].len()));
let rect = |x: &[f32], v: usize| {
let (node, cx) = (&nodes[v], x[v]);
let cy = y[node.rank];
[cx - node.size[0] / 2.0, cy - node.size[1] / 2.0, cx + node.size[0] / 2.0, cy + node.size[1] / 2.0]
};
let boxes_of = |x: &[f32]| {
let mut boxes = vec![[f32::MAX, f32::MAX, f32::MIN, f32::MIN]; g.clusters.len()];
for (v, node) in nodes.iter().enumerate() {
if let (Kind::Real(_) | Kind::Dummy(_, true), Some(c)) = (node.kind, node.cluster) {
let (r, b) = (rect(x, v), &mut boxes[c]);
*b = [b[0].min(r[0]), b[1].min(r[1]), b[2].max(r[2]), b[3].max(r[3])];
}
}
for &c in &depth_order {
let b = boxes[c];
if b[0] > b[2] {
continue;
}
let lead = g.clusters[c].lead;
let min_span = g.clusters[c].min_span;
let mut padded = [b[0] - sp.cluster - lead[0], b[1] - sp.cluster - lead[1], b[2] + sp.cluster, b[3] + sp.cluster];
for axis in [0, 1] {
let cur = padded[axis + 2] - padded[axis];
if cur < min_span[axis] {
let extra = (min_span[axis] - cur) / 2.0;
padded[axis] -= extra;
padded[axis + 2] += extra;
}
}
boxes[c] = padded;
if let Some(p) = g.clusters[c].parent {
let pb = &mut boxes[p];
*pb = [pb[0].min(padded[0]), pb[1].min(padded[1]), pb[2].max(padded[2]), pb[3].max(padded[3])];
}
}
boxes
};
// 8. Push overlapping sibling clusters and loose nodes apart across layers.
let members: Vec<Vec<usize>> = (0..g.clusters.len()).map(|c| (0..nodes.len()).filter(|&v| node_chains[v].contains(&c)).collect()).collect();
let pos = positions(&layers, nodes.len());
#[derive(Clone, Copy)]
enum Item {
Cluster(usize),
Node(usize),
}
let item_nodes = |it: Item| match it {
Item::Cluster(c) => members[c].as_slice(),
Item::Node(v) => std::slice::from_ref(&layers[nodes[v].rank][pos[v]]),
};
let first_on_rank: Vec<std::collections::HashMap<usize, usize>> = members
.iter()
.map(|m| {
let mut at = std::collections::HashMap::new();
for &v in m {
at.entry(nodes[v].rank).or_insert(v);
}
at
})
.collect();
let on_rank = |it: Item, r: usize| match it {
Item::Cluster(c) => first_on_rank[c].get(&r).copied(),
Item::Node(v) => (nodes[v].rank == r).then_some(v),
};
let left_of = |a: Item, b: Item, ba: [f32; 4], bb: [f32; 4]| {
for &u in item_nodes(a) {
if let Some(w) = on_rank(b, nodes[u].rank) {
return pos[u] < pos[w];
}
}
ba[0] + ba[2] <= bb[0] + bb[2]
};
for _ in 0..12 {
let boxes = boxes_of(&x);
let mut items: Vec<(Option<usize>, Item, [f32; 4])> = (0..g.clusters.len())
.filter(|&c| boxes[c][0] <= boxes[c][2])
.map(|c| (g.clusters[c].parent, Item::Cluster(c), boxes[c]))
.collect();
items.extend((0..n).map(|v| (g.node_cluster[v], Item::Node(v), rect(&x, v))));
let mut shift = vec![0.0f32; nodes.len()];
let mut moved = false;
for i in 0..items.len() {
for j in i + 1..items.len() {
let ((pa, a, ba), (pb, b, bb)) = (items[i], items[j]);
if pa != pb || matches!((a, b), (Item::Node(_), Item::Node(_))) || ba[1] >= bb[3] || bb[1] >= ba[3] {
continue;
}
let ((l, bl), (r, br)) = if left_of(a, b, ba, bb) { ((a, ba), (b, bb)) } else { ((b, bb), (a, ba)) };
let d = bl[2] + sp.node / 2.0 - br[0];
if d > 0.5 {
// Streaming in, nodes only move on along their ranks, so the right one makes the room.
let (back, on) = if held.is_some() { (0.0, d) } else { (d / 2.0, d / 2.0) };
item_nodes(l).iter().for_each(|&v| shift[v] -= back);
item_nodes(r).iter().for_each(|&v| shift[v] += on);
moved = true;
}
}
}
// A long edge passing a subgraph it isn't in goes around its box, as dagre's border
// nodes make it: its points on the subgraph's ranks, and one rank either side so the
// curve doesn't cut a corner, move out past the box's nearer side.
for (c, b) in boxes.iter().enumerate().filter(|(_, b)| b[0] <= b[2]) {
let near = first[c].saturating_sub(1)..=last[c] + 1;
for v in n..nodes.len() {
let Kind::Dummy(e, _) = nodes[v].kind else { continue };
let (a, z) = ends(e);
if !near.contains(&nodes[v].rank) || [a, z].iter().any(|&u| node_chains[u].contains(&c)) {
continue;
}
let (lo, hi) = (b[0] - sp.node / 2.0, b[2] + sp.node / 2.0);
if x[v] <= lo || x[v] >= hi {
continue;
}
let left = match first_on_rank[c].get(&nodes[v].rank) {
Some(&w) => pos[v] < pos[w],
None => x[v] < (b[0] + b[2]) / 2.0,
};
shift[v] += if left { lo - x[v] } else { hi - x[v] };
moved = true;
}
}
if !moved {
break;
}
for (xv, s) in x.iter_mut().zip(&shift) {
*xv += s;
}
for (layer, sep) in layers.iter().zip(&seps) {
let want: Vec<f32> = layer.iter().map(|&v| x[v]).collect();
let placed = isotonic_above(want, vec![1.0; layer.len()], sep, layer.iter().map(|&v| floor(v).copied()));
for (&v, p) in layer.iter().zip(placed) {
x[v] = p;
}
}
}
let boxes = boxes_of(&x);
// 9. Normalise to the origin.
let mut lo = [f32::MAX, f32::MAX];
for (v, node) in nodes.iter().enumerate() {
lo = [lo[0].min(x[v] - node.size[0] / 2.0), lo[1].min(y[node.rank] - node.size[1] / 2.0)];
}
for b in boxes.iter().filter(|b| b[0] <= b[2]) {
lo = [lo[0].min(b[0]), lo[1].min(b[1])];
}
if lo[0] == f32::MAX {
lo = [0.0, 0.0];
}
if held.is_some() {
// Streaming in, the last layout's axes stay put, and the drawing keeps its corner (see
// [`steady::origin`]).
lo = [0.0, 0.0];
}
let at = |v: usize| [x[v] - lo[0], y[nodes[v].rank] - lo[1]];
let centers = (0..n).map(at).collect();
let mut paths = Vec::with_capacity(g.edges.len());
let mut labels = Vec::with_capacity(g.edges.len());
for (i, e) in g.edges.iter().enumerate() {
if e.from == e.to {
paths.push(vec![at(e.from)]);
labels.push(None);
continue;
}
let mut pts: Vec<[f32; 2]> = edge_chain[i].iter().map(|&v| at(v)).collect();
labels.push(edge_chain[i].iter().find(|&&v| matches!(nodes[v].kind, Kind::Dummy(_, true))).map(|&v| at(v)));
if reversed[i] {
pts.reverse();
}
paths.push(pts);
}
let clusters = boxes
.iter()
.map(|b| if b[0] <= b[2] { [b[0] - lo[0], b[1] - lo[1], b[2] - lo[0], b[3] - lo[1]] } else { [0.0; 4] })
.collect();
let memo = Memo { rank, along: (0..n).map(|v| Some(x[v] - lo[0])).collect(), depth: y.iter().map(|d| d - lo[1]).collect(), ..Memo::default() };
Some((Placed { centers, paths, labels, clusters }, memo))
}
/// How hard a node streaming in holds its place along its rank against its neighbours' pull
/// (1 for each, 4 for a long edge's point).
const HOLD: f32 = 1000.0;
/// [`isotonic`], with places some nodes never go below: those that end up below theirs are
/// pinned there, the rest solved again around them.
fn isotonic_above(mut want: Vec<f32>, mut w: Vec<f32>, sep: &[f32], floors: impl Iterator<Item = Option<f32>>) -> Vec<f32> {
// A floor also lifts the floors after it by the room between them.
let (mut gap, mut lift) = (0.0, f32::MIN);
let floors: Vec<Option<f32>> = floors
.enumerate()
.map(|(i, f)| {
if i > 0 {
gap += sep[i - 1];
}
lift = lift.max(f.map_or(f32::MIN, |f| f - gap));
(lift > f32::MIN).then_some(lift + gap)
})
.collect();
loop {
let placed = isotonic(&want, &w, sep);
let mut pinned = false;
for (i, f) in floors.iter().enumerate() {
if let Some(f) = *f
&& placed[i] < f - 0.01
&& w[i] < PINNED
{
(want[i], w[i], pinned) = (f, PINNED, true);
}
}
if !pinned {
return placed;
}
}
}
/// The weight that pins a node to its floor: past any pull or room it is solved with.
const PINNED: f32 = 1e9;
/// The positions closest to `want` (weighted least squares) that keep each neighbour at least
/// `sep` apart, in order: pool-adjacent-violators on the positions less their cumulative gaps.
fn isotonic(want: &[f32], w: &[f32], sep: &[f32]) -> Vec<f32> {
let mut offset = Vec::with_capacity(want.len());
let mut at = 0.0;
for i in 0..want.len() {
if i > 0 {
at += sep[i - 1];
}
offset.push(at);
}
let mut blocks: Vec<(f32, f32, usize)> = Vec::new();
for i in 0..want.len() {
let mut b = (want[i] - offset[i], w[i].max(1e-3), 1);
while let Some(&prev) = blocks.last() {
if prev.0 <= b.0 {
break;
}
blocks.pop();
let total = prev.1 + b.1;
b = ((prev.0 * prev.1 + b.0 * b.1) / total, total, prev.2 + b.2);
}
blocks.push(b);
}
let mut out = Vec::with_capacity(want.len());
for (mean, _, count) in blocks {
for _ in 0..count {
let i = out.len();
out.push(mean + offset[i]);
}
}
out
}
#[cfg(test)]
#[path = "layered_tests.rs"]
mod tests;
@@ -0,0 +1,105 @@
use super::*;
fn graph(n: usize, edges: &[(usize, usize)]) -> Graph {
Graph {
sizes: vec![[60.0, 30.0]; n],
edges: edges.iter().map(|&(from, to)| GEdge { from, to, label: None, minlen: 1 }).collect(),
node_cluster: vec![None; n],
clusters: Vec::new(),
ids: Vec::new(),
}
}
const SP: Spacing = Spacing { node: 30.0, rank: 40.0, cluster: 10.0 };
#[test]
fn a_chain_goes_down_in_a_straight_line() {
let p = layout(&graph(3, &[(0, 1), (1, 2)]), &SP).unwrap();
assert!(p.centers[0][1] < p.centers[1][1] && p.centers[1][1] < p.centers[2][1]);
assert!((p.centers[0][0] - p.centers[2][0]).abs() < 0.5, "{:?}", p.centers);
assert_eq!(p.centers[1][1] - p.centers[0][1], 30.0 + 40.0, "one rank is a node plus the rank gap");
}
#[test]
fn a_fork_spreads_children_without_overlap_and_centres_the_parent() {
let p = layout(&graph(3, &[(0, 1), (0, 2)]), &SP).unwrap();
let (a, b) = (p.centers[1], p.centers[2]);
assert_eq!(a[1], b[1]);
assert!((a[0] - b[0]).abs() >= 90.0 - 0.01, "{a:?} {b:?}");
assert!((p.centers[0][0] - (a[0] + b[0]) / 2.0).abs() < 1.0);
}
#[test]
fn cycles_and_self_loops_lay_out() {
let p = layout(&graph(3, &[(0, 1), (1, 2), (2, 0), (1, 1)]), &SP).unwrap();
assert_eq!(p.paths.len(), 4);
let back = &p.paths[2];
assert_eq!(back.first(), Some(&p.centers[2]), "a reversed edge still runs from its source");
assert_eq!(back.last(), Some(&p.centers[0]));
assert!(p.centers.iter().all(|c| c[0].is_finite() && c[1].is_finite()));
}
#[test]
fn sibling_clusters_never_overlap_across_layers() {
let mut g = graph(7, &[(0, 1), (2, 3), (2, 4), (0, 2), (3, 5), (4, 5), (4, 6)]);
g.clusters = vec![
GCluster { parent: None, lead: [0.0, 16.0], min_span: [0.0, 0.0] },
GCluster { parent: None, lead: [0.0, 16.0], min_span: [0.0, 0.0] },
];
g.node_cluster = vec![Some(0), Some(0), Some(1), Some(1), Some(1), None, None];
let p = layout(&g, &SP).unwrap();
let (a, b) = (p.clusters[0], p.clusters[1]);
let apart = a[2] <= b[0] || b[2] <= a[0] || a[3] <= b[1] || b[3] <= a[1];
assert!(apart, "{a:?} {b:?}");
for v in [5, 6] {
let c = p.centers[v];
for bx in [a, b] {
let inside = c[0] > bx[0] && c[0] < bx[2] && c[1] > bx[1] && c[1] < bx[3];
assert!(!inside, "node {v} at {c:?} inside {bx:?}");
}
}
}
/// The shape of `fixtures/plan.mmd`: five subgraphs whose ranks interleave, with edges from
/// one into the next. Sweeps alone ordered the subgraphs differently on different ranks.
#[test]
fn interleaved_subgraphs_keep_one_order_and_never_overlap() {
let edges = [
(2, 3), (3, 6), (8, 9), (9, 10), (9, 6), (6, 7), (5, 7), (4, 7), (10, 11), (6, 11), (10, 12), (10, 13),
(12, 14), (13, 14), (14, 15), (14, 16), (15, 17), (16, 17), (6, 17), (5, 17), (17, 18), (18, 19),
];
let mut g = graph(24, &edges);
let free = GCluster { parent: None, lead: [0.0, 16.0], min_span: [0.0, 0.0] };
g.clusters = (0..5).map(|_| GCluster { ..free }).collect();
g.node_cluster = (0..24).map(|v| Some(match v { 0..=1 => 0, 2..=7 => 1, 8..=11 => 2, 12..=19 => 3, _ => 4 })).collect();
let p = layout(&g, &SP).unwrap();
for a in 0..5 {
for b in a + 1..5 {
let (x, y) = (p.clusters[a], p.clusters[b]);
let apart = x[2] <= y[0] || y[2] <= x[0] || x[3] <= y[1] || y[3] <= x[1];
assert!(apart, "subgraphs {a} and {b} overlap: {x:?} {y:?}");
}
}
}
#[test]
fn isotonic_keeps_separation_and_hits_free_targets() {
assert_eq!(isotonic(&[0.0, 100.0], &[1.0, 1.0], &[10.0]), vec![0.0, 100.0]);
let x = isotonic(&[50.0, 50.0], &[1.0, 1.0], &[20.0]);
assert_eq!(x, vec![40.0, 60.0]);
}
#[test]
fn clusters_stay_contiguous_and_contain_their_members() {
let mut g = graph(4, &[(0, 1), (0, 2), (0, 3)]);
g.clusters.push(GCluster { parent: None, lead: [0.0, 16.0], min_span: [0.0, 0.0] });
g.node_cluster[1] = Some(0);
g.node_cluster[3] = Some(0);
let p = layout(&g, &SP).unwrap();
let b = p.clusters[0];
for v in [1, 3] {
let c = p.centers[v];
assert!(c[0] - 30.0 >= b[0] && c[0] + 30.0 <= b[2] && c[1] - 15.0 >= b[1] + 16.0, "{c:?} in {b:?}");
}
let c2 = p.centers[2];
assert!(c2[0] + 30.0 <= b[0] || c2[0] - 30.0 >= b[2], "a non-member sits outside: {c2:?} {b:?}");
}
+9
View File
@@ -0,0 +1,9 @@
//! Layered (Sugiyama) graph layout, within-layer ordering, edge routing, connectors,
//! shared layered scene rendering and monotonic streaming stability.
pub(crate) mod connector;
pub(crate) mod draw;
pub(crate) mod layered;
mod order;
pub(crate) mod route;
pub(crate) mod steady;
+212
View File
@@ -0,0 +1,212 @@
//! Within-layer ordering and crossing minimisation for [`super::layered`]: DFS seed order,
//! barycentre sweeps that keep subgraphs contiguous, consistent sibling cluster order across
//! layers, and order preservation while a diagram streams in.
use super::layered::LNode;
use super::steady::Memo;
/// Orders `nodes` within their `ranks` layers, keeping subgraphs contiguous and minimising edge
/// crossings, then holds previously placed nodes to their prior order when streaming (`held`).
pub(super) fn order_layers(
nodes: &[LNode],
n: usize,
ranks: usize,
node_chains: &[&[usize]],
parents: &[Option<usize>],
held: Option<&Memo>,
) -> Vec<Vec<usize>> {
let mut layers: Vec<Vec<usize>> = vec![Vec::new(); ranks];
let mut seen = vec![false; nodes.len()];
for root in 0..n {
let mut stack = vec![root];
while let Some(v) = stack.pop() {
if std::mem::replace(&mut seen[v], true) {
continue;
}
layers[nodes[v].rank].push(v);
stack.extend(nodes[v].succs.iter().rev().copied());
}
}
for (v, s) in seen.iter().enumerate() {
if !s {
layers[nodes[v].rank].push(v);
}
}
for layer in &mut layers {
let keys: Vec<f32> = (0..layer.len()).map(|i| i as f32).collect();
*layer = grouped_order(layer, &keys, node_chains);
}
align_clusters(&mut layers, node_chains, parents);
let mut best = layers.clone();
let mut best_x = crossings(&layers, nodes);
for it in 0..16 {
if best_x == 0 {
break;
}
let down = it % 2 == 0;
let order: Vec<usize> = if down { (1..ranks).collect() } else { (0..ranks.saturating_sub(1)).rev().collect() };
let mut pos = positions(&layers, nodes.len());
for r in order {
let layer = &layers[r];
let keys: Vec<f32> = layer
.iter()
.enumerate()
.map(|(i, &v)| {
let nb = if down { &nodes[v].preds } else { &nodes[v].succs };
if nb.is_empty() { i as f32 } else { nb.iter().map(|&u| pos[u] as f32).sum::<f32>() / nb.len() as f32 }
})
.collect();
layers[r] = grouped_order(layer, &keys, node_chains);
for (i, &v) in layers[r].iter().enumerate() {
pos[v] = i;
}
}
align_clusters(&mut layers, node_chains, parents);
let x = crossings(&layers, nodes);
if x < best_x {
best_x = x;
best = layers.clone();
}
}
let mut layers = best;
if let Some(m) = held {
hold_order(&mut layers, m, n, node_chains);
align_clusters(&mut layers, node_chains, parents);
}
layers
}
/// While a diagram streams in, the nodes laid out last time keep their order along each rank;
/// the rest keep the places the sweeps gave them.
fn hold_order(layers: &mut [Vec<usize>], m: &Memo, n: usize, chains: &[&[usize]]) {
let along = |v: usize| m.along.get(v).copied().flatten().filter(|_| v < n);
for layer in layers {
let slots: Vec<usize> = (0..layer.len()).filter(|&i| along(layer[i]).is_some()).collect();
let mut kept: Vec<usize> = slots.iter().map(|&i| layer[i]).collect();
kept.sort_by(|&a, &b| along(a).unwrap_or(0.0).total_cmp(&along(b).unwrap_or(0.0)));
for (&i, v) in slots.iter().zip(kept) {
layer[i] = v;
}
let keys: Vec<f32> = (0..layer.len()).map(|i| i as f32).collect();
*layer = grouped_order(layer, &keys, chains);
}
}
/// Each node's index within its layer.
pub(super) fn positions(layers: &[Vec<usize>], len: usize) -> Vec<usize> {
let mut pos = vec![0; len];
for layer in layers {
for (i, &v) in layer.iter().enumerate() {
pos[v] = i;
}
}
pos
}
/// Sorts a layer by `keys`, keeping each cluster's members together: clusters sort as one item
/// at their members' mean key, recursively.
fn grouped_order(layer: &[usize], keys: &[f32], chains: &[&[usize]]) -> Vec<usize> {
grouped(layer, keys, chains, None)
}
/// [`grouped_order`]; with `rank`, the clusters among each group's items then trade places so
/// they come in `rank` order, while loose nodes keep theirs.
fn grouped(layer: &[usize], keys: &[f32], chains: &[&[usize]], rank: Option<&[f32]>) -> Vec<usize> {
type Items = Vec<(usize, f32)>;
fn go(items: Items, depth: usize, chains: &[&[usize]], rank: Option<&[f32]>) -> Items {
let mut groups: Vec<(Option<usize>, Items)> = Vec::new();
for it in items {
let c = chains[it.0].get(depth).copied();
match groups.iter_mut().find(|g| c.is_some() && g.0 == c) {
Some(g) => g.1.push(it),
None => groups.push((c, vec![it])),
}
}
let mut keyed: Vec<(f32, Option<usize>, Items)> = groups
.into_iter()
.map(|(c, members)| {
let key = members.iter().map(|m| m.1).sum::<f32>() / members.len() as f32;
let members = if c.is_some() { go(members, depth + 1, chains, rank) } else { members };
(key, c, members)
})
.collect();
keyed.sort_by(|a, b| a.0.total_cmp(&b.0));
if let Some(rank) = rank {
let slots: Vec<usize> = (0..keyed.len()).filter(|&i| keyed[i].1.is_some()).collect();
let mut held: Vec<(usize, Items)> = slots.iter().map(|&i| (keyed[i].1.unwrap_or(0), std::mem::take(&mut keyed[i].2))).collect();
held.sort_by(|a, b| rank[a.0].total_cmp(&rank[b.0]));
for (&i, (c, members)) in slots.iter().zip(held) {
(keyed[i].1, keyed[i].2) = (Some(c), members);
}
}
keyed.into_iter().flat_map(|(_, _, m)| m).collect()
}
let items = layer.iter().copied().zip(keys.iter().copied()).collect();
go(items, 0, chains, rank).into_iter().map(|(v, _)| v).collect()
}
/// Puts sibling clusters in one order on every layer, the one most layers already agree on.
/// Sweeps order each layer alone, so two subgraphs could swap from one layer to the next and
/// their boxes, each spanning all its layers, would overlap whatever positions follow.
fn align_clusters(layers: &mut [Vec<usize>], chains: &[&[usize]], parents: &[Option<usize>]) {
let k = parents.len();
if k < 2 {
return;
}
// lead[a][b]: layers where a comes before b, less those where it comes after.
let mut lead = vec![vec![0i32; k]; k];
let mut mean = vec![(0.0f32, 0usize); k];
for layer in layers.iter() {
let mut first: Vec<Option<usize>> = vec![None; k];
for (i, &v) in layer.iter().enumerate() {
for &c in chains[v] {
first[c].get_or_insert(i);
mean[c].0 += i as f32 / layer.len().max(1) as f32;
mean[c].1 += 1;
}
}
for a in 0..k {
for b in 0..k {
if let (Some(ia), Some(ib)) = (first[a], first[b])
&& ia < ib
&& parents[a] == parents[b]
{
lead[a][b] += 1;
lead[b][a] -= 1;
}
}
}
}
// Siblings that come after more of the others sort later; where layers tie, mean place decides.
let rank: Vec<f32> = (0..k)
.map(|c| {
let behind = (0..k).filter(|&b| lead[c][b] < 0).count() as f32 - (0..k).filter(|&b| lead[c][b] > 0).count() as f32;
behind + 0.5 * mean[c].0 / mean[c].1.max(1) as f32
})
.collect();
for layer in layers.iter_mut() {
let keys: Vec<f32> = (0..layer.len()).map(|i| i as f32).collect();
*layer = grouped(layer, &keys, chains, Some(&rank));
}
}
fn crossings(layers: &[Vec<usize>], nodes: &[LNode]) -> usize {
let pos = positions(layers, nodes.len());
let mut total = 0;
for layer in layers {
let mut edges: Vec<(usize, usize)> = Vec::new();
for &v in layer {
for &w in &nodes[v].succs {
edges.push((pos[v], pos[w]));
}
}
for (i, a) in edges.iter().enumerate() {
for b in &edges[i + 1..] {
if (a.0 < b.0 && a.1 > b.1) || (a.0 > b.0 && a.1 < b.1) {
total += 1;
}
}
}
}
total
}
+558
View File
@@ -0,0 +1,558 @@
//! Edge routes for layered diagrams. Each edge leaves and enters its nodes straight along the
//! rank axis, keeps only the layout's bend points it needs to stay clear of other nodes, and
//! joins them with cubics whose tangents also run along the rank axis: no kinks at bends, no
//! wobble from bend points a few points apart, and arrowheads that sit on the line's last
//! tangent. Labels move onto the curve when they fit there.
//!
//! Everything here works in the layout's own axes (ranks run down `y`); callers map points to
//! the screen with [`Ctx::screen`].
use super::draw::{NodeShape, boundary, outline};
use super::layered::Placed;
use crate::canvas::{dist, lerp};
/// Clearance between an edge and nodes it passes.
const NODE_GAP: f32 = 5.0;
/// Clearance between an edge and the box of a subgraph it passes.
const CLUSTER_GAP: f32 = 2.0;
/// Clearance between a moved label and anything else.
const LABEL_GAP: f32 = 2.0;
/// The least distance between two edges' ends on the same side of a node: an arrowhead's width
/// and a little air, so heads arriving together sit side by side instead of on one point.
const PORT_GAP: f32 = 14.0;
/// The drawing an edge routes through.
pub(crate) struct Ctx<'a> {
pub placed: &'a Placed,
/// Screen sizes and shapes per node, then per subgraph an edge stops on ([`Ctx::cluster_ends`]).
pub sizes: Vec<[f32; 2]>,
pub shapes: Vec<NodeShape>,
/// Label box sizes per edge, in layout axes.
pub labels: Vec<Option<[f32; 2]>>,
/// The layout's `x` is the screen's `y`.
pub across: bool,
/// Edge ends per edge, `(from, to)` as the source wrote them.
pub ends: Vec<(usize, usize)>,
/// Centres in layout axes, in the order of `sizes`.
centers: Vec<[f32; 2]>,
/// How many of `sizes` are nodes; the rest are subgraphs edges stop on.
real: usize,
/// Node outlines in layout axes.
outlines: Vec<Vec<[f32; 2]>>,
/// Subgraph titles, `[x0, y0, x1, y1]` in layout axes.
titles: Vec<[f32; 4]>,
/// Port offsets `[start, end]` per edge, across the rank axis, for ends moved apart from
/// others on the same side of a node ([`Ctx::fanned`]).
slots: Vec<[Option<f32>; 2]>,
/// The subgraphs each of `sizes` sits in, innermost last ([`Ctx::homes`]); an edge keeps out
/// of every other subgraph's box.
homes: Vec<Vec<usize>>,
/// The subgraph each of `sizes` past the nodes is.
stops: Vec<usize>,
}
/// An edge drawn: its curve and the tips and directions of its heads, in screen points.
pub(crate) struct Route {
pub curve: Vec<[f32; 2]>,
pub tip_start: [f32; 2],
pub tip_end: [f32; 2],
/// Unit directions the heads point, out of the curve.
pub dir_start: [f32; 2],
pub dir_end: [f32; 2],
pub label: Option<[f32; 2]>,
}
impl<'a> Ctx<'a> {
pub(crate) fn new(placed: &'a Placed, sizes: &[[f32; 2]], shapes: Vec<NodeShape>, labels: Vec<Option<[f32; 2]>>, across: bool, ends: Vec<(usize, usize)>) -> Self {
let swap = |p: [f32; 2]| if across { [p[1], p[0]] } else { p };
let outlines = (0..sizes.len()).map(|v| outline(shapes[v], swap(placed.centers[v]), sizes[v]).into_iter().map(swap).collect()).collect();
let centers = placed.centers.clone();
Ctx { placed, sizes: sizes.to_vec(), shapes, labels, across, ends, centers, real: sizes.len(), outlines, titles: Vec::new(), slots: Vec::new(), homes: Vec::new(), stops: Vec::new() }
}
/// The subgraphs each node sits in, innermost last, given per subgraph as its chain from the
/// outermost. Call after [`Ctx::cluster_ends`]: a subgraph an edge stops on is its end's home.
pub(crate) fn homes(mut self, nodes: impl IntoIterator<Item = Vec<usize>>, chains: &[Vec<usize>]) -> Self {
self.homes = nodes.into_iter().collect();
self.homes.extend(self.stops.iter().map(|&c| chains[c].clone()));
self
}
/// The boxes of subgraphs that hold neither end of edge `i`, in layout axes.
fn foreign(&self, i: usize) -> impl Iterator<Item = [f32; 4]> + '_ {
let (from, to) = self.ends[i];
let home = |v: usize, c: usize| self.homes.get(v).is_some_and(|h| h.contains(&c));
self.placed.clusters.iter().enumerate().filter(move |&(c, b)| *b != [0.0; 4] && !home(from, c) && !home(to, c)).map(|(_, b)| *b)
}
/// Stops edge ends on subgraph borders, `[start, end]` per edge: each subgraph named joins as
/// a box the edge meets the way it meets a node, and that nodes keep clear of.
pub(crate) fn cluster_ends(mut self, on: &[[Option<usize>; 2]]) -> Self {
let mut boxes: Vec<(usize, usize)> = Vec::new();
for (i, ends) in on.iter().enumerate().take(self.ends.len()) {
for (k, c) in ends.iter().enumerate() {
let Some(b) = c.and_then(|c| self.placed.clusters.get(c).copied().filter(|b| *b != [0.0; 4]).map(|b| (c, b))) else { continue };
let v = match boxes.iter().find(|x| x.0 == b.0) {
Some(&(_, v)) => v,
None => {
let [x0, y0, x1, y1] = b.1;
let (c, size) = ([(x0 + x1) / 2.0, (y0 + y1) / 2.0], self.screen([x1 - x0, y1 - y0]));
let shape = NodeShape::Rect;
self.outlines.push(outline(shape, self.screen(c), size).into_iter().map(|p| self.screen(p)).collect());
self.centers.push(c);
self.sizes.push(size);
self.shapes.push(shape);
boxes.push((b.0, self.sizes.len() - 1));
self.stops.push(b.0);
self.sizes.len() - 1
}
};
if k == 0 {
self.ends[i].0 = v;
} else {
self.ends[i].1 = v;
}
}
}
self
}
/// Keeps edges and labels off subgraph titles, given as screen rects.
pub(crate) fn titles(mut self, titles: impl IntoIterator<Item = [f32; 4]>) -> Self {
self.titles = titles
.into_iter()
.map(|r| {
let (a, b) = (self.screen([r[0], r[1]]), self.screen([r[2], r[3]]));
[a[0], a[1], b[0], b[1]]
})
.collect();
self
}
/// Fans out edge ends that would meet a node at the same point: ends on one side of a node
/// closer than [`PORT_GAP`] spread apart, in the order of where the edges come from, so they
/// don't cross. Call last: it routes every edge once to find where each would meet its nodes.
pub(crate) fn fanned(mut self, flip: bool) -> Self {
// (node, side, port x, other end's x, edge, which end) for every end.
let mut ends: Vec<(usize, i8, f32, f32, usize, usize)> = Vec::new();
for i in 0..self.ends.len() {
let (from, to) = self.ends[i];
if from == to || self.placed.paths.get(i).is_none_or(|p| p.len() < 2) {
continue;
}
let r = self.route(i, flip, [0.0, 0.0]);
let (a, b) = (self.screen(r.tip_start), self.screen(r.tip_end));
let side = |d: [f32; 2]| if self.screen(d)[1] > 0.0 { -1 } else { 1 };
ends.push((from, side(r.dir_start), a[0], b[0], i, 0));
ends.push((to, side(r.dir_end), b[0], a[0], i, 1));
}
ends.sort_by(|p, q| (p.0, p.1).cmp(&(q.0, q.1)).then(p.2.total_cmp(&q.2)));
self.slots = vec![[None; 2]; self.ends.len()];
for group in ends.chunk_by(|p, q| (p.0, p.1) == (q.0, q.1)) {
let (c, reach) = (self.centers[group[0].0][0], self.fan_reach(group[0].0));
for (x, &(_, _, natural, _, i, k)) in spread(group, c, reach).into_iter().zip(group) {
if (x - natural).abs() > 0.5 {
self.slots[i][k] = Some(x);
}
}
}
self
}
fn slot(&self, i: usize) -> [Option<f32>; 2] {
self.slots.get(i).copied().unwrap_or_default()
}
/// Whether a label's box (screen, `[x0, y0, x1, y1]`) crosses a subgraph's border.
pub(crate) fn on_border(&self, r: [f32; 4]) -> bool {
let (a, b) = (self.screen([r[0], r[1]]), self.screen([r[2], r[3]]));
let r = [a[0].min(b[0]), a[1].min(b[1]), a[0].max(b[0]), a[1].max(b[1])];
self.placed.clusters.iter().filter(|c| **c != [0.0; 4]).any(|c| straddles(r, *c))
}
/// A layout point on the screen (and back: the map is its own inverse).
pub(crate) fn screen(&self, p: [f32; 2]) -> [f32; 2] {
if self.across { [p[1], p[0]] } else { p }
}
fn size(&self, v: usize) -> [f32; 2] {
self.screen(self.sizes[v])
}
/// Where an edge may touch node `v`: within this far of its centre across the rank axis.
fn port_reach(&self, v: usize) -> f32 {
let half = self.size(v)[0] / 2.0;
let flat = match self.shapes[v] {
NodeShape::Cylinder | NodeShape::LinedCylinder => !self.across,
s => s.flat(),
};
match self.shapes[v] {
_ if flat => (half - 10.0).max(half * 0.5),
// Their flat top and bottom, short of the round or slanted ends.
NodeShape::Stadium if !self.across => (half - self.size(v)[1] / 2.0 - 2.0).max(half * 0.4),
NodeShape::Hexagon if !self.across => (half - self.size(v)[1] / 4.0 - 6.0).max(half * 0.4),
NodeShape::Diamond | NodeShape::Hexagon => half * 0.6,
_ => half * 0.45,
}
}
/// How far from its centre fanned ends may spread across `v`: on a flat side, nearly to its
/// corners.
fn fan_reach(&self, v: usize) -> f32 {
let flat = match self.shapes[v] {
NodeShape::Cylinder | NodeShape::LinedCylinder => !self.across,
s => s.flat(),
};
let reach = self.port_reach(v);
if flat { reach.max(self.size(v)[0] / 2.0 - 6.0) } else { reach }
}
/// The point on `v`'s outline straight along the rank axis from `x`, on the side `s` points to.
fn port(&self, v: usize, x: f32, s: f32) -> [f32; 2] {
let c = self.centers[v][0];
self.port_within(v, x.clamp(c - self.port_reach(v), c + self.port_reach(v)), s)
}
/// [`Ctx::port`], with `x` as far out as a fanned end may go.
fn port_within(&self, v: usize, x: f32, s: f32) -> [f32; 2] {
let c = self.centers[v];
let x = x.clamp(c[0] - self.fan_reach(v), c[0] + self.fan_reach(v));
let poly = &self.outlines[v];
let mut best: Option<f32> = None;
for i in 0..poly.len() {
let (a, b) = (poly[i], poly[(i + 1) % poly.len()]);
if (a[0] - x) * (b[0] - x) > 0.0 || (a[0] - b[0]).abs() < 1e-4 {
continue;
}
let y = a[1] + (b[1] - a[1]) * (x - a[0]) / (b[0] - a[0]);
if best.is_none_or(|y0| (y - y0) * s > 0.0) {
best = Some(y);
}
}
match best {
Some(y) if (y - c[1]) * s >= 0.0 => [x, y],
_ => {
let t = boundary(self.shapes[v], self.screen(c), self.sizes[v], self.screen([x, c[1] + s * 1e4]));
self.screen(t)
}
}
}
/// Whether `p` keeps `gap` away from node `v`.
fn clear_of(&self, v: usize, p: [f32; 2], gap: f32) -> bool {
let (c, s) = (self.centers[v], self.size(v));
if (p[0] - c[0]).abs() > s[0] / 2.0 + gap || (p[1] - c[1]).abs() > s[1] / 2.0 + gap {
return true;
}
let poly = &self.outlines[v];
!inside(poly, p) && (0..poly.len()).all(|i| seg_dist(p, poly[i], poly[(i + 1) % poly.len()]) > gap)
}
/// Other edges' label boxes, where the layout put them, and subgraph titles.
fn label_boxes(&self, skip: usize) -> impl Iterator<Item = [f32; 4]> + '_ {
let labels = (0..self.labels.len()).filter(move |&j| j != skip).filter_map(|j| {
let (at, s) = (self.placed.labels[j]?, self.labels[j]?);
Some([at[0] - s[0] / 2.0, at[1] - s[1] / 2.0, at[0] + s[0] / 2.0, at[1] + s[1] / 2.0])
});
labels.chain(self.titles.iter().copied())
}
/// Whether the curve from `a` to `b` stays clear of every node but `ends` and of other labels.
fn clear(&self, edge: usize, a: [f32; 2], b: [f32; 2], ends: (usize, usize)) -> bool {
let pts: Vec<[f32; 2]> = cubic(a, b)
.windows(2)
.flat_map(|w| {
let steps = (dist(w[0], w[1]) / 3.0).ceil().max(1.0) as usize;
(0..steps).map(move |k| lerp(w[0], w[1], k as f32 / steps as f32))
})
.chain([b])
.collect();
let boxes: Vec<[f32; 4]> = self.label_boxes(edge).collect();
let foreign: Vec<[f32; 4]> = self.foreign(edge).collect();
let g = CLUSTER_GAP;
pts.iter().all(|&p| {
(0..self.real).all(|v| v == ends.0 || v == ends.1 || self.clear_of(v, p, NODE_GAP))
&& boxes.iter().all(|r| p[0] < r[0] || p[0] > r[2] || p[1] < r[1] || p[1] > r[3])
&& foreign.iter().all(|r| p[0] < r[0] - g || p[0] > r[2] + g || p[1] < r[1] - g || p[1] > r[3] + g)
})
}
/// Edge `i`'s route, with its heads' insets `[start, end]` taken off the line.
pub(crate) fn route(&self, i: usize, flip: bool, insets: [f32; 2]) -> Route {
let (from, to) = self.ends[i];
let mut path = self.placed.paths[i].clone();
if flip {
path.reverse();
}
let label = self.placed.labels[i];
// Edges between the same two nodes keep the layout's separate tracks.
let twin = self.ends.iter().enumerate().any(|(j, &(a, b))| j != i && ((a, b) == (from, to) || (a, b) == (to, from)));
let label_at = label.and_then(|l| path.iter().position(|&p| p == l));
let mut anchors = self.anchors(i, &path, twin, None);
let mut at = label;
if let (Some(l), Some(size), false) = (label, self.labels[i], twin) {
// The label sits on the line where it crosses the label's rank, if the line runs
// straight through it there; a slanted line would jog across the gap.
let line = curve(&anchors);
let upright = |p: &[f32; 2]| match (along(&line, p[1] - size[1] / 2.0), along(&line, p[1] + size[1] / 2.0)) {
(Some(a), Some(b)) => (a - b).abs() < 1.0,
_ => false,
};
let on = along(&line, l[1]).map(|x| [x, l[1]]);
match on.filter(|p| upright(p) && self.label_fits(i, *p, size)) {
Some(p) => at = Some(p),
None => {
anchors = self.anchors(i, &path, false, label_at);
// The line meets the label square on: into its near side, out of its far one.
if let Some(k) = anchors.iter().position(|&p| p == l).filter(|&k| k > 0 && k + 1 < anchors.len()) {
let h = size[1] / 2.0 * (anchors[k + 1][1] - anchors[k - 1][1]).signum();
anchors.splice(k..=k, [[l[0], l[1] - h], [l[0], l[1] + h]]);
}
}
}
}
let n = anchors.len();
let (s0, s1) = ((anchors[1][1] - anchors[0][1]).signum(), (anchors[n - 1][1] - anchors[n - 2][1]).signum());
let (tip_start, tip_end) = (anchors[0], anchors[n - 1]);
let room = |a: [f32; 2], b: [f32; 2], inset: f32| (b[1] - a[1]).abs() > inset + 4.0;
if room(anchors[0], anchors[1], insets[0]) {
anchors[0][1] += s0 * insets[0];
}
if room(anchors[n - 2], anchors[n - 1], insets[1]) {
anchors[n - 1][1] -= s1 * insets[1];
}
Route {
curve: curve(&anchors).into_iter().map(|p| self.screen(p)).collect(),
tip_start: self.screen(tip_start),
tip_end: self.screen(tip_end),
dir_start: self.screen([0.0, -s0]),
dir_end: self.screen([0.0, s1]),
label: at.map(|p| self.screen(p)),
}
}
/// Ports on both nodes, then the fewest of `path`'s bend points that keep the curve clear;
/// `all` keeps every one, and `at` one in particular.
fn anchors(&self, i: usize, path: &[[f32; 2]], all: bool, at: Option<usize>) -> Vec<[f32; 2]> {
let keep = |k: usize| all || Some(k) == at;
let (from, to) = self.ends[i];
let n = path.len();
let ends = (from, to);
let s0 = (path[1][1] - path[0][1]).signum();
let s1 = (path[n - 1][1] - path[n - 2][1]).signum();
if !all
&& at.is_none()
&& let Some(pair) = self.direct(i, path, s0, s1)
{
return pair.to_vec();
}
let mut pts = path.to_vec();
pts[0] = self.port(from, path[1][0], s0);
pts[n - 1] = self.port(to, path[n - 2][0], -s1);
// Greedy: from each kept point, jump to the farthest point the curve reaches cleanly.
let mut kept = vec![0];
let mut k = 0;
while k < n - 1 {
let stop = (k + 1..n).find(|&j| j == n - 1 || keep(j)).unwrap_or(n - 1);
let next = (k + 1..=stop).rev().find(|&j| j == k + 1 || self.clear(i, pts[k], pts[j], ends)).unwrap_or(k + 1);
kept.push(next);
k = next;
}
let mut out: Vec<[f32; 2]> = kept.iter().map(|&k| pts[k]).collect();
// Ports face what they now connect to: straight down when both nodes can meet, else
// as close to straight as each allows.
let m = out.len();
let (c0, c1) = (self.centers[from][0], self.centers[to][0]);
let (r0, r1) = (self.port_reach(from), self.port_reach(to));
let (lo, hi) = ((c0 - r0).max(c1 - r1), (c0 + r0).min(c1 + r1));
let wanted = if m == 2 && lo <= hi {
let mid = path[1..n - 1].iter().map(|p| p[0]).sum::<f32>() / (n - 2).max(1) as f32;
let x = if n > 2 { mid.clamp(lo, hi) } else { ((c0 + c1) / 2.0).clamp(lo, hi) };
(x, x)
} else {
(out[1][0], out[m - 2][0])
};
let slot = self.slot(i);
if m == 2 {
let facing = (out[m - 1][0], out[0][0]);
let fanned = (slot[0].unwrap_or(wanted.0), slot[1].unwrap_or(wanted.1));
for (x0, x1) in [fanned, wanted, facing] {
let (a, b) = (self.port_within(from, x0, s0), self.port_within(to, x1, -s1));
if self.clear(i, a, b, ends) {
out[0] = a;
out[m - 1] = b;
break;
}
}
} else {
// Each end on its own: the port nearest straight at its neighbour that stays clear.
let near = |v: usize, toward: [f32; 2], s: f32, first: bool| {
let (c, r) = (self.centers[v][0], self.port_reach(v));
let mut xs: Vec<f32> = (0..=8).map(|k| c - r + 2.0 * r * k as f32 / 8.0).chain([toward[0].clamp(c - r, c + r)]).collect();
xs.sort_by(|a, b| (a - toward[0]).abs().total_cmp(&(b - toward[0]).abs()));
if let Some(x) = slot[usize::from(!first)] {
xs.insert(0, x);
}
xs.into_iter().map(|x| self.port_within(v, x, s)).find(|&p| if first { self.clear(i, p, toward, ends) } else { self.clear(i, toward, p, ends) })
};
if let Some(a) = near(from, out[1], s0, true) {
out[0] = a;
}
if let Some(b) = near(to, out[m - 2], -s1, false) {
out[m - 1] = b;
}
}
out
}
/// One curve straight from node to node, as straight as the nodes allow: the ports'
/// offsets come from the layout's bend points and the nodes' own reach, and the pair with
/// the least sideways travel that stays clear wins.
fn direct(&self, i: usize, path: &[[f32; 2]], s0: f32, s1: f32) -> Option<[[f32; 2]; 2]> {
const TRIES: usize = 16;
let (from, to) = self.ends[i];
let (c0, c1) = (self.centers[from][0], self.centers[to][0]);
let (r0, r1) = (self.port_reach(from), self.port_reach(to));
let mut xs: Vec<f32> = path[1..path.len() - 1].iter().map(|p| p[0]).collect();
xs.extend([c0, c1, c0 - r0, c0 + r0, c1 - r1, c1 + r1]);
let pairs: Vec<(f32, f32)> = xs.iter().flat_map(|&a| xs.iter().map(move |&b| (a.clamp(c0 - r0, c0 + r0), b.clamp(c1 - r1, c1 + r1)))).collect();
let cost = |&(a, b): &(f32, f32)| (a - b).abs() * 4.0 + (a - c0).abs() + (b - c1).abs();
let best = |mut pairs: Vec<(f32, f32)>| {
pairs.sort_by(|p, q| cost(p).total_cmp(&cost(q)));
pairs.dedup_by(|p, q| (p.0 - q.0).abs() < 0.5 && (p.1 - q.1).abs() < 0.5);
pairs.into_iter().take(TRIES).find_map(|(x0, x1)| {
let (a, b) = (self.port_within(from, x0, s0), self.port_within(to, x1, -s1));
self.clear(i, a, b, (from, to)).then_some([a, b])
})
};
// Fanned ends first, at their slots; where those can't stay clear, the free choice.
let slot = self.slot(i);
let fanned = (slot != [None, None]).then(|| best(pairs.iter().map(|&(a, b)| (slot[0].unwrap_or(a), slot[1].unwrap_or(b))).collect())).flatten();
fanned.or_else(|| best(pairs))
}
/// Whether edge `i`'s label, centred at `p`, keeps clear of every node and other label.
fn label_fits(&self, i: usize, p: [f32; 2], size: [f32; 2]) -> bool {
let (hw, hh) = (size[0] / 2.0 + LABEL_GAP, size[1] / 2.0 + LABEL_GAP);
let corners = [[p[0] - hw, p[1] - hh], [p[0] + hw, p[1] - hh], [p[0] + hw, p[1] + hh], [p[0] - hw, p[1] + hh], p];
let nodes_ok = (0..self.real).all(|v| {
let (c, s) = (self.centers[v], self.size(v));
let apart = (p[0] - c[0]).abs() > hw + s[0] / 2.0 || (p[1] - c[1]).abs() > hh + s[1] / 2.0;
apart || (corners.iter().all(|&q| !inside(&self.outlines[v], q)) && self.outlines[v].iter().all(|q| (q[0] - p[0]).abs() > hw || (q[1] - p[1]).abs() > hh))
});
let rect = [p[0] - hw, p[1] - hh, p[0] + hw, p[1] + hh];
let borders_ok = !self.placed.clusters.iter().filter(|c| **c != [0.0; 4]).any(|c| straddles(rect, *c));
nodes_ok && borders_ok && self.label_boxes(i).all(|r| p[0] + hw < r[0] || p[0] - hw > r[2] || p[1] + hh < r[1] || p[1] - hh > r[3])
}
}
/// A cubic from `a` to `b` leaving and arriving along the rank axis, flattened.
pub(crate) fn cubic(a: [f32; 2], b: [f32; 2]) -> Vec<[f32; 2]> {
let dy = b[1] - a[1];
if (b[0] - a[0]).abs() < 0.25 {
return vec![a, b];
}
let (c1, c2) = ([a[0], a[1] + dy * 0.5], [b[0], b[1] - dy * 0.5]);
let len = dist(a, c1) + dist(c1, c2) + dist(c2, b);
let steps = (len / 3.0).ceil().clamp(8.0, 96.0) as usize;
(0..=steps)
.map(|s| {
let t = s as f32 / steps as f32;
let u = 1.0 - t;
let (b0, b1, b2, b3) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t);
[b0 * a[0] + b1 * c1[0] + b2 * c2[0] + b3 * b[0], b0 * a[1] + b1 * c1[1] + b2 * c2[1] + b3 * b[1]]
})
.collect()
}
/// The curve through `anchors`, one [`cubic`] per pair.
pub(crate) fn curve(anchors: &[[f32; 2]]) -> Vec<[f32; 2]> {
let mut out = vec![anchors[0]];
for w in anchors.windows(2) {
out.extend(cubic(w[0], w[1]).into_iter().skip(1));
}
out
}
/// Port offsets for the ends on one side of a node, `(.., port x, other end's x, ..)` sorted by
/// port: runs closer than [`PORT_GAP`] spread about their middle, ordered by where their edges
/// come from, then everything is pushed apart left to right and kept within `c ± reach`.
fn spread(group: &[(usize, i8, f32, f32, usize, usize)], c: f32, reach: f32) -> Vec<f32> {
let mut order: Vec<usize> = (0..group.len()).collect();
let mut runs: Vec<std::ops::Range<usize>> = Vec::new();
for k in 0..group.len() {
match runs.last_mut() {
Some(r) if group[k].2 - group[k - 1].2 < PORT_GAP => r.end = k + 1,
_ => runs.push(k..k + 1),
}
}
let mut xs = vec![0.0; group.len()];
for r in &runs {
order[r.clone()].sort_by(|&a, &b| group[a].3.total_cmp(&group[b].3).then(group[a].4.cmp(&group[b].4)));
let mid = group[r.clone()].iter().map(|e| e.2).sum::<f32>() / r.len() as f32;
for (n, k) in r.clone().enumerate() {
xs[k] = mid + (n as f32 - (r.len() - 1) as f32 / 2.0) * PORT_GAP;
}
}
for k in 1..xs.len() {
xs[k] = xs[k].max(xs[k - 1] + PORT_GAP);
}
let (lo, hi) = (c - reach, c + reach);
let span = xs[xs.len() - 1] - xs[0];
if span > hi - lo {
let n = (xs.len() - 1).max(1) as f32;
xs.iter_mut().enumerate().for_each(|(k, x)| *x = lo + (hi - lo) * k as f32 / n);
} else {
let shift = (lo - xs[0]).max(0.0) + (hi - xs[xs.len() - 1]).min(0.0);
xs.iter_mut().for_each(|x| *x += shift);
}
// Back in the group's order: `xs[k]` is the slot of `group[order[k]]`.
let mut out = vec![0.0; group.len()];
for (k, &g) in order.iter().enumerate() {
out[g] = xs[k];
}
out
}
/// Where `pts` crosses the rank coordinate `y`.
fn along(pts: &[[f32; 2]], y: f32) -> Option<f32> {
pts.windows(2).find_map(|w| {
let (a, b) = (w[0], w[1]);
if (a[1] - y) * (b[1] - y) > 0.0 || (a[1] - b[1]).abs() < 1e-5 {
return None;
}
Some(a[0] + (b[0] - a[0]) * (y - a[1]) / (b[1] - a[1]))
})
}
/// Whether rect `r` lies partly inside and partly outside rect `c` (both `[x0, y0, x1, y1]`).
fn straddles(r: [f32; 4], c: [f32; 4]) -> bool {
let overlaps = r[0] < c[2] && r[2] > c[0] && r[1] < c[3] && r[3] > c[1];
let within = r[0] >= c[0] && r[2] <= c[2] && r[1] >= c[1] && r[3] <= c[3];
overlaps && !within
}
fn inside(poly: &[[f32; 2]], p: [f32; 2]) -> bool {
let mut odd = false;
for i in 0..poly.len() {
let (a, b) = (poly[i], poly[(i + 1) % poly.len()]);
if (a[1] > p[1]) != (b[1] > p[1]) && p[0] < a[0] + (b[0] - a[0]) * (p[1] - a[1]) / (b[1] - a[1]) {
odd = !odd;
}
}
odd
}
fn seg_dist(p: [f32; 2], a: [f32; 2], b: [f32; 2]) -> f32 {
let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
let l = dx * dx + dy * dy;
let t = if l < 1e-6 { 0.0 } else { (((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / l).clamp(0.0, 1.0) };
dist(p, [a[0] + dx * t, a[1] + dy * t])
}
#[cfg(test)]
#[path = "route_tests.rs"]
mod tests;
@@ -0,0 +1,119 @@
use super::*;
use crate::canvas::Op;
use crate::{DiagramStyle, scene};
/// The largest turn between consecutive segments of `pts`, in degrees.
fn sharpest_turn(pts: &[[f32; 2]]) -> f32 {
let dirs: Vec<f32> = pts.windows(2).filter(|w| crate::canvas::dist(w[0], w[1]) > 1e-3).map(|w| (w[1][1] - w[0][1]).atan2(w[1][0] - w[0][0])).collect();
dirs.windows(2)
.map(|d| {
let mut a = (d[1] - d[0]).to_degrees().abs();
if a > 180.0 {
a = 360.0 - a;
}
a
})
.fold(0.0, f32::max)
}
#[test]
fn curves_leave_and_arrive_along_the_rank_axis() {
let pts = curve(&[[0.0, 0.0], [40.0, 100.0], [40.0, 200.0]]);
assert_eq!(pts.first(), Some(&[0.0, 0.0]));
assert_eq!(pts.last(), Some(&[40.0, 200.0]));
let (a, b) = (pts[0], pts[1]);
assert!((b[0] - a[0]).abs() < (b[1] - a[1]).abs() * 0.05, "leaves straight down: {a:?} → {b:?}");
assert!(sharpest_turn(&pts) < 6.0, "no kink where the segments meet: {}", sharpest_turn(&pts));
assert_eq!(cubic([5.0, 0.0], [5.0, 90.0]).len(), 2, "an aligned pair is one straight segment");
}
#[test]
fn flowchart_edges_draw_without_kinks() {
let src = "flowchart TD\n A[Audio] --> B[Parakeet writes text<br/>'went to the capuchin']\n B --> C{Any word that looks<br/>or sounds like a term?}\n C -- no --> F[Paste as is]\n C -- \"capuchin ≈ Cappuccino\" --> D[Score the same audio twice:<br/>as 'capuchin' and as 'Cappuccino']\n D --> E{Cappuccino score + boost<br/>≥ capuchin score?}\n E -- yes --> G[Write Cappuccino]\n E -- no --> F";
let paint = DiagramStyle::neutral(true);
let Some(crate::Parsed { diagram: crate::Diagram::Flowchart(f), .. }) = crate::parse(src) else { panic!() };
let c = crate::graph::flowchart::draw_canvas(&f, &paint, Some((crate::Hover::Edges, paint.text))).expect("draws");
let lines: Vec<&Vec<[f32; 2]>> = c.ops.iter().filter_map(|op| match op {
Op::Stroke { points, closed: false, color, .. } if *color == paint.line => Some(points),
_ => None,
}).collect();
assert_eq!(lines.len(), 11, "one stroke per edge, broken around its label");
for l in lines {
assert!(sharpest_turn(l) < 12.0, "edge turns {}° at once: {l:?}", sharpest_turn(l));
}
assert_eq!(c.traces.len(), 7, "every edge keeps a trace for hover");
assert!(scene(src, &paint, None).is_some());
}
#[test]
fn arrows_point_into_the_node_they_reach() {
let paint = DiagramStyle::neutral(true);
let Some(crate::Parsed { diagram: crate::Diagram::Flowchart(f), .. }) = crate::parse("flowchart TD\n A[Audio] --> B[Parakeet]") else { panic!() };
let c = crate::graph::flowchart::draw_canvas(&f, &paint, Some((crate::Hover::Edges, paint.text))).expect("draws");
let head = c.ops.iter().find_map(|op| match op {
Op::Fill(p, col) if *col == paint.line && p.len() == 3 => Some(p.clone()),
_ => None,
});
let tip = head.expect("an arrowhead")[0];
let b_top = c.regions[1].iter().map(|p| p[1]).fold(f32::MAX, f32::min);
assert!((tip[1] - b_top).abs() < 0.5, "tip {tip:?} on B's top {b_top}");
}
#[test]
fn long_edges_stay_clear_of_the_nodes_they_pass() {
let paint = DiagramStyle::neutral(true);
let src = "flowchart TD\n A[Audio] --> B[Parakeet writes text]\n B --> C{Any word that looks<br/>or sounds like a term?}\n C -- no --> F[Paste as is]\n C -- \"capuchin ≈ Cappuccino\" --> D[Score the same audio twice:<br/>as 'capuchin' and as 'Cappuccino']\n D --> E{Cappuccino score + boost<br/>≥ capuchin score?}\n E -- yes --> G[Write Cappuccino]\n E -- no --> F";
let Some(crate::Parsed { diagram: crate::Diagram::Flowchart(f), .. }) = crate::parse(src) else { panic!() };
let c = crate::graph::flowchart::draw_canvas(&f, &paint, Some((crate::Hover::Edges, paint.text))).expect("draws");
let (d, e) = (&c.regions[4], &c.regions[5]);
let lines: Vec<&Vec<[f32; 2]>> = c.ops.iter().filter_map(|op| match op {
Op::Stroke { points, closed: false, color, .. } if *color == paint.line => Some(points),
_ => None,
}).collect();
// The long "no" edge, C to F, in two runs around its label.
for w in lines[2..4].iter().flat_map(|l| l.windows(2)) {
for k in 0..=8 {
let p = crate::canvas::lerp(w[0], w[1], k as f32 / 8.0);
assert!(!inside(d, p) && !inside(e, p), "the long \"no\" edge crosses a node at {p:?}");
}
}
}
#[test]
fn labels_break_the_line_instead_of_covering_it() {
let rect = [10.0, 40.0, 30.0, 60.0];
let runs = crate::layout::connector::outside(&[[20.0, 0.0], [20.0, 50.0], [20.0, 100.0]], rect);
assert_eq!(runs.len(), 2);
assert!((runs[0].last().unwrap()[1] - 40.0).abs() < 0.1 && (runs[1][0][1] - 60.0).abs() < 0.1, "{runs:?}");
assert_eq!(crate::layout::connector::outside(&[[0.0, 0.0], [0.0, 9.0]], rect).len(), 1, "a curve that misses the label is whole");
}
#[test]
fn every_direction_draws_smooth_edges_that_reach_their_nodes() {
let paint = DiagramStyle::neutral(true);
for dir in ["TD", "BT", "LR", "RL"] {
let src = format!("flowchart {dir}\n A[Start] --> B[Left]\n A --> C[Right]\n B --> D[End]\n C -- label --> D\n A --> D");
let Some(crate::Parsed { diagram: crate::Diagram::Flowchart(f), .. }) = crate::parse(&src) else { panic!() };
let c = crate::graph::flowchart::draw_canvas(&f, &paint, Some((crate::Hover::Edges, paint.text))).expect("draws");
let mut lines = 0;
for op in &c.ops {
if let Op::Stroke { points, closed: false, color, .. } = op
&& *color == paint.line
{
lines += 1;
assert!(sharpest_turn(points) < 12.0, "{dir}: edge turns {}° at once", sharpest_turn(points));
}
}
assert!(lines >= 5, "{dir}: {lines} strokes");
let tips: Vec<[f32; 2]> = c.ops.iter().filter_map(|op| match op {
Op::Fill(p, col) if *col == paint.line && p.len() == 3 => Some(p[0]),
_ => None,
}).collect();
assert_eq!(tips.len(), 5, "{dir}: one arrowhead per edge");
for t in tips {
let touching = c.regions.iter().any(|r| (0..r.len()).any(|k| seg_dist(t, r[k], r[(k + 1) % r.len()]) < 1.0));
assert!(touching, "{dir}: arrow tip {t:?} doesn't touch a node");
}
}
}
+129
View File
@@ -0,0 +1,129 @@
//! Layouts that only grow while a diagram streams in. A build of a source still arriving holds
//! to the layout of the same source one line shorter: no node moves back a rank or changes
//! places with a node it was laid out beside, nodes only move on along their ranks (right in a
//! top-down diagram, down in a left-right one), never back toward where they were, and no gap
//! between ranks narrows. A new edge that would pull a node a rank further and leave the
//! diagram shorter for one line, only for the next line to stretch it again, leaves it as tall
//! as it was instead. The finished source lays out afresh, as a diagram that never streamed
//! does, and settles there in one glide.
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
/// What one layout leaves for the next build of a longer source to hold to, in the layout's
/// own axes, which stay put while the diagram streams in (see [`super::layered`]).
#[derive(Clone, Default)]
pub(crate) struct Memo {
/// Each node's rank.
pub rank: Vec<usize>,
/// Each node's centre along its rank (`None` for one new since the last build). The next
/// build places it there or further on.
pub along: Vec<Option<f32>>,
/// Each rank's centre across the ranks.
pub depth: Vec<f32>,
/// Each node's name (empty: known by index).
pub ids: Vec<String>,
}
impl Memo {
/// This memo for a layout of nodes named `ids`, each where the node of its name was.
fn renamed(&self, ids: &[String]) -> Memo {
if ids.is_empty() || self.ids.is_empty() {
return self.clone();
}
let was: HashMap<&str, usize> = self.ids.iter().enumerate().map(|(i, id)| (id.as_str(), i)).collect();
let old: Vec<Option<usize>> = ids.iter().map(|id| was.get(id.as_str()).copied()).collect();
Memo {
rank: old.iter().map(|o| o.and_then(|o| self.rank.get(o).copied()).unwrap_or(0)).collect(),
along: old.iter().map(|o| o.and_then(|o| self.along.get(o).copied().flatten())).collect(),
depth: self.depth.clone(),
ids: ids.to_vec(),
}
}
}
/// What a streaming build laid out, one [`Memo`] per layout in the order it ran them, whether a
/// horizontal diagram turned upright, and how big it drew.
#[derive(Default)]
pub(crate) struct Memory {
layouts: Vec<Memo>,
turned: bool,
/// The top left corner it was drawn from, in its layouts' points.
origin: Option<[f32; 2]>,
/// The size the scene was drawn at.
pub size: [f32; 2],
}
struct Build {
prev: Option<Rc<Memory>>,
next: Memory,
}
thread_local! {
static BUILD: RefCell<Option<Build>> = const { RefCell::new(None) };
}
/// Runs `f`, a scene build, holding its layouts to `prev`'s, and returns what they laid out.
pub(crate) fn build<R>(prev: Option<Rc<Memory>>, f: impl FnOnce() -> R) -> (R, Memory) {
struct Restore(Option<Build>);
impl Drop for Restore {
fn drop(&mut self) {
BUILD.set(self.0.take());
}
}
let restore = Restore(BUILD.replace(Some(Build { prev, next: Memory::default() })));
let out = f();
let next = BUILD.with_borrow_mut(|b| b.take().map(|b| b.next)).unwrap_or_default();
drop(restore);
(out, next)
}
/// Runs one layout of nodes named `ids`: `place` gets the memo this layout's counterpart in the
/// last build left (`None` outside a streaming build, or for a first one) and returns what it
/// placed and the memo for the next build.
pub(crate) fn layout<T>(ids: &[String], place: impl FnOnce(Option<&Memo>) -> Option<(T, Memo)>) -> Option<T> {
let Some((prev, at)) = BUILD.with_borrow(|b| b.as_ref().map(|b| (b.prev.clone(), b.next.layouts.len()))) else {
return place(None).map(|p| p.0);
};
let held = prev.as_ref().and_then(|m| m.layouts.get(at)).map(|m| m.renamed(ids));
let placed = place(held.as_ref());
let (out, mut memo) = placed.map_or((None, Memo::default()), |(t, m)| (Some(t), m));
memo.ids = ids.to_vec();
BUILD.with_borrow_mut(|b| {
if let Some(b) = b {
b.next.layouts.push(memo);
}
});
out
}
/// Whether the last build turned a horizontal diagram upright, so this one stays turned.
pub(crate) fn turned() -> bool {
BUILD.with_borrow(|b| b.as_ref().and_then(|b| b.prev.as_ref()).is_some_and(|m| m.turned))
}
pub(crate) fn set_turned(turned: bool) {
BUILD.with_borrow_mut(|b| {
if let Some(b) = b {
b.next.turned = turned;
}
});
}
/// The top left corner a drawing with bounds `b` is drawn from: never further in than the last
/// build's, so a diagram growing up or left moves its nodes on, and one drawing less far out
/// than before doesn't move them back. A turned diagram starts afresh.
pub(crate) fn origin(b: [f32; 4], turned: bool) -> [f32; 2] {
BUILD.with_borrow_mut(|build| {
let Some(build) = build else { return [b[0], b[1]] };
let was = build.prev.as_ref().filter(|m| m.turned == turned).and_then(|m| m.origin);
let o = was.map_or([b[0], b[1]], |o| [o[0].min(b[0]), o[1].min(b[1])]);
build.next.origin = Some(o);
o
})
}
#[cfg(test)]
#[path = "steady_tests.rs"]
mod tests;
@@ -0,0 +1,130 @@
use std::collections::HashMap;
use std::rc::Rc;
use crate::canvas::Scene;
use crate::canvas::scenes::{Cache, SCENES, growing as growing_scene};
use crate::{DiagramStyle, scene};
/// A reply's flowchart whose fourth line pulls `On` a rank further, which used to leave the
/// diagram shorter for one line (119, 90, 119, 156 tall).
const RETRIES: &str = "flowchart LR
Drop[Socket drops] --> R1[Retry at once]
R1 -->|ok| On[Online]
R1 -->|fails| R2[Back off 1 s]
R2 -->|ok| On
R2 -->|fails| Off[Offline]
Off -->|retry| R2
";
/// Each node's centre, before the scene shrinks to fit.
fn centres(s: &Scene) -> HashMap<String, [f32; 2]> {
s.pieces
.iter()
.filter(|p| p.key.starts_with("n:") && !p.key.contains('.'))
.map(|p| (p.key.clone(), [p.at[0] + p.size[0] / 2.0, p.at[1] + p.size[1] / 2.0]))
.collect()
}
/// Each prefix of `src`, a line longer each time, built as it streams in.
fn stream(src: &str) -> Vec<Rc<Scene>> {
let lines: Vec<&str> = src.lines().collect();
(2..=lines.len())
.filter_map(|k| growing_scene(&(lines[..k].join("\n") + "\n"), &DiagramStyle::neutral(true), None))
.collect()
}
/// How far any node moves back along an axis it has already moved along the other way.
fn worst_reversal(scenes: &[&Scene]) -> (f32, String) {
let mut paths: HashMap<String, Vec<[f32; 2]>> = HashMap::new();
for s in scenes {
for (k, c) in centres(s) {
paths.entry(k).or_default().push(c);
}
}
let mut worst = (0.0, String::new());
for (k, path) in &paths {
for axis in 0..2 {
let (mut lo, mut hi, mut up, mut down) = (f32::MAX, f32::MIN, 0.0f32, 0.0f32);
for p in path {
let v = p[axis];
// Back from the furthest point either way.
up = up.max(hi - v);
down = down.max(v - lo);
lo = lo.min(v);
hi = hi.max(v);
}
let back = up.min(down);
if back > worst.0 {
worst = (back, format!("{k} axis {axis}: {path:?}"));
}
}
}
worst
}
/// A top-down chart with a subgraph, a merge and a loop back.
const DEPLOY: &str = "flowchart TD
A[Push] --> B{Tests pass?}
B -->|no| C[Fix]
C --> A
B -->|yes| D[Build image]
subgraph Ship
D --> E[Canary]
E --> F[Roll out]
end
E -->|errors| G[Roll back]
G --> C
F --> H([Done])
";
/// A state diagram whose later lines add states beside and before the first ones.
const CONNECTION: &str = "stateDiagram-v2
[*] --> Idle
Idle --> Connecting: open
Connecting --> Open: ok
Connecting --> Backoff: fail
Backoff --> Connecting: timer
Open --> Closing: close
Open --> Backoff: drop
Closing --> [*]
";
#[test]
fn a_streaming_diagram_only_grows() {
for src in [RETRIES, DEPLOY, CONNECTION] {
let scenes = stream(src);
let sizes: Vec<[f32; 2]> = scenes.iter().map(|s| s.size).collect();
assert!(sizes.windows(2).all(|w| w[1][0] >= w[0][0] - 0.01 && w[1][1] >= w[0][1] - 0.01), "it never shrinks: {sizes:?}\n{src}");
let (back, which) = worst_reversal(&scenes.iter().map(|s| &**s).collect::<Vec<_>>());
assert!(back <= 1.0, "no node doubles back more than a point: {back} at {which}\n{src}");
}
}
#[test]
fn a_finished_stream_lays_out_as_if_it_never_streamed() {
let paint = DiagramStyle::neutral(true);
let before = scene(RETRIES, &paint, None).unwrap();
let streamed = stream(RETRIES);
let after = scene(RETRIES, &paint, None).unwrap();
assert_eq!(centres(&before), centres(&after), "a streaming build leaves nothing behind for the next build");
assert_eq!(before.size, after.size);
assert!(!streamed.is_empty());
}
#[test]
fn a_growing_build_is_the_same_however_many_lines_arrived_at_once() {
let paint = DiagramStyle::neutral(true);
let by_line = stream(RETRIES).pop().unwrap();
SCENES.with_borrow_mut(|c| *c = Cache::default());
let at_once = growing_scene(RETRIES, &paint, None).unwrap();
assert_eq!(centres(&by_line), centres(&at_once));
assert_eq!(by_line.size, at_once.size);
}
#[test]
fn nodes_keep_their_places_by_name_when_one_before_them_becomes_a_subgraph() {
// `S` starts as a node and turns into a frame, so `W` and `Y` each move up the node list.
let scenes = stream("graph TD\n X -->|in| S\n S --> W\n W -->|out| Y\n subgraph S\n D\n end\n");
let (back, which) = worst_reversal(&scenes.iter().map(|s| &**s).collect::<Vec<_>>());
assert!(back <= 1.0, "no node doubles back more than a point: {back} at {which}");
}
+752
View File
@@ -0,0 +1,752 @@
//! Native ```` ```mermaid ```` diagrams: flowcharts, sequence, state, class and
//! entity-relationship diagrams, gantt and pie charts, mindmaps, timelines, user journeys, git
//! graphs, quadrant and XY charts, sankey, block, requirement and C4 diagrams, parsed and laid out
//! in Rust and drawn with [`rune::Shape`]s and text, so they theme with the app and stay crisp at
//! any scale. No JavaScript, web view or network.
//!
//! **Flowcharts** (`graph` or `flowchart`, directions `TD`/`TB`/`BT`/`LR`/`RL`): node shapes
//! `[rect]`, `(rounded)`, `([stadium])`, `[[subroutine]]`, `[(cylinder)]`, `((circle))`,
//! `(((double circle)))`, `>asymmetric]`, `{diamond}`, `{{hexagon}}`, `[/lean right/]`,
//! `[\lean left\]`, `[/trapezoid\]`, `[\inverted trapezoid/]`, and every v11
//! `@{ shape: …, label: … }` name and alias (documents, stacked shapes, cylinders, braces,
//! markers, bang, cloud and the rest; icons and images draw as their frame); edge ids
//! (`A e1@--> B`, with `e1@{ … }` settings read and left out); links `-->`, `---`, `-.->`, `==>`, `~~~`, `<-->`, `--o`, `--x`,
//! longer forms for longer links, labels as `-- text -->`, `-- "text" -->` or `-->|text|`; chains
//! (`A --> B --> C`), `&` groups, quoted labels, `<br>` and `\n` breaks, nested `subgraph … end`
//! (including edges to/from subgraph ids), node tints from `style`/`classDef`/`class`/`:::class`,
//! and edge tints from `linkStyle`.
//!
//! **Sequence diagrams** (`sequenceDiagram`): `participant` and `actor` with `as` aliases;
//! `box` participant column groups; `rect` highlight bands; messages `->`, `-->`, `->>`, `-->>`,
//! `-x`, `--x`, `-)`, `--)`, `<<->>` and `<<-->>`, with `+`/`-` activation; `activate` and
//! `deactivate`; `Note left of|right of|over A[,B]`; `autonumber [start [step]]` and
//! `autonumber off`; `create` and `destroy`; v11 participant types (`@{ "type": "database" }`:
//! boundary, control, entity, database, collections, queue); and `loop`, `alt`/`else`, `opt`,
//! `par`/`and`, `critical`/`option` and `break` frames.
//!
//! **State diagrams** (`stateDiagram` or `stateDiagram-v2`): `direction TB|BT|LR|RL`, `[*]`
//! start and end pseudostates, `state "Label" as id`, `state id <<choice>>` (`<<fork>>`,
//! `<<join>>`), `id : description`, transitions `A --> B : label`, composite `state Name { … }`
//! with `--` concurrent regions, and `note left of|right of` notes, on one line or up to `end note`.
//!
//! **Class diagrams** (`classDiagram`): `class Name { +field \n +method() }`, `Name : +member`,
//! `<<trait>>` / `<<enum>>` stereotypes, `namespace Name { … }`, and UML relationships `<|--`,
//! `*--`, `o--`, `-->`, `..>`, `..|>`, `--` and `..` with labels and cardinalities.
//!
//! **Entity-relationship diagrams** (`erDiagram`): entities with `{ type name PK, FK "comment" }`
//! attribute tables, `name["Alias"]` and quoted names, relationships in crow's-foot notation
//! (`||`, `|o`, `}|`, `}o` either side of `--` or `..`, or worded: `only one to zero or more`,
//! `optionally to`) with labels, `direction`, and `classDef`/`class`/`style` tints.
//!
//! **Gantt charts** (`gantt`): `dateFormat` (dayjs tokens), `axisFormat` (d3 `%` codes),
//! `tickInterval`, `section`s, tasks `Name :[done|active|crit|milestone|vert,] [id,] [start,]
//! end` with dates, durations (`3d`, `1w`, `12h`), `after a b` and `until a`, `excludes`
//! (weekends, weekdays, dates; `weekend friday`) and `inclusiveEndDates`. Times have no zone,
//! and there is no today marker, so a chart draws the same anywhere.
//!
//! **Pie charts** (`pie`): `showData`, `title`, and `"Label" : value` slices.
//!
//! **Mindmaps** (`mindmap`): nesting by indentation from one root, node shapes `[square]`,
//! `(rounded)`, `((circle))`, `))bang((`, `)cloud(` and `{{hexagon}}`, with `::icon(…)` and
//! `:::class` read and left out. Branches split to either side of the root, each in its colour.
//!
//! **Timelines** (`timeline`, `timeline TD`): `title`, `section`s, and `period : event : event`
//! with `: event` continuation lines. Periods that don't fit across run top to bottom.
//!
//! **User journeys** (`journey`): `title`, `section`s, and `Task: score: actor, actor` tasks, with a
//! face for each score from 1 to 5 and a legend of actors.
//!
//! **Git graphs** (`gitGraph`, `gitGraph TB:`, `gitGraph BT:`): `commit` with `id`, `tag` and
//! `type: NORMAL | REVERSE | HIGHLIGHT`, `branch` (with `order`), `checkout`/`switch`, `merge` and
//! `cherry-pick`. Commits without an `id` are unlabelled.
//!
//! **Quadrant charts** (`quadrantChart`): `title`, `x-axis`/`y-axis` with `low --> high` ends,
//! `quadrant-1` to `quadrant-4`, and `Name: [x, y]` points with `radius`, `color`, `stroke-color`
//! and `stroke-width`, inline or from `classDef` and `:::class`.
//!
//! **XY charts** (`xychart-beta`, `xychart-beta horizontal`): `title`, `x-axis` as `[categories]`
//! or `min --> max`, `y-axis "title" min --> max`, and `bar` and `line` series (optionally named,
//! with a legend). Without a y range the axis rounds out from the data and takes in zero.
//!
//! **Sankey diagrams** (`sankey-beta`): `source,target,value` CSV rows with quoted fields. Nodes
//! sit in columns by their longest path, sinks last, joined by bands as thick as their flow.
//!
//! **Block diagrams** (`block-beta`): `columns n`, blocks with the flowchart shapes, `id:n` spans,
//! `space[:n]`, nested `block[:id[:n]] … end` groups, block arrows `id<["label"]>(right|left|up|down|x|y)`,
//! edges with labels, and `style`/`classDef`/`class`. Blocks fill rows left to right and wrap.
//!
//! **Requirement diagrams** (`requirementDiagram`): `requirement` (and the functional, interface,
//! performance, physical and design-constraint kinds) and `element` blocks with their fields,
//! `a - satisfies -> b` and `b <- copies - a` relationships of the seven kinds, `direction`, and
//! `style`/`classDef`/`class`/`:::class`.
//!
//! **C4 diagrams** (`C4Context`, `C4Container`, `C4Component`, `C4Dynamic`, `C4Deployment`):
//! `Person`, `System`, `Container` and `Component` with their `Db`, `Queue` and `_Ext` forms;
//! `Boundary`, `Enterprise_Boundary`, `System_Boundary`, `Container_Boundary` and
//! `Deployment_Node`/`Node` frames, nested; `Rel`, `BiRel`, `Rel_Back`, the `Rel_U`/`D`/`L`/`R`
//! forms and `RelIndex`, with technology, numbered in `C4Dynamic`. Style and layout updates are
//! read and left out.
//!
//! **Leniency.** A statement that doesn't read is skipped and the rest still draws; a shape opener
//! without its closer (`B[/items split view]`) is a plain rectangle holding the text as written;
//! blocks left open close at the end. [`render`] returns `None`, so callers can show the source,
//! only for a diagram type it doesn't know (kanban, packet, architecture, …), when nothing reads,
//! or past the size bounds (400 items, nesting 8 deep).
//!
//! **Streaming.** Each node, edge, participant, message and frame is its own element, keyed by
//! what it is (a flowchart node by its id), so a diagram rebuilt as its source grows keeps what
//! it has drawn. [`render_streaming`] brings each new one in on its own: nodes fade and grow in,
//! edges and messages draw on from source to target with the arrowhead landing last, frames
//! fade; anything already there glides to its new place. While it streams the diagram only grows:
//! each build holds to the last one's ranks, order and places, so nothing doubles back and no gap
//! closes. [`render_streamed`] lays the finished source out as [`render`] and
//! [`render_with_hover`] do (they draw everything the frame it mounts), so a diagram settles in
//! one glide once it has all arrived and doesn't move after.
#![forbid(unsafe_code)]
mod canvas;
mod chart;
mod graph;
mod layout;
mod sequence;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use rune::{Color, El, TextStyle, oklch, oklcha, tok};
use canvas::{Scene, scenes};
pub use canvas::drawing::DrawingModel;
pub use canvas::drawing::prepare_drawing;
pub use canvas::hover::Hover;
/// Colours and type a diagram draws with.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct DiagramStyle {
pub text: Color,
pub muted: Color,
pub surface: Color,
pub surface_border: Color,
pub node_fill: Color,
pub node_border: Color,
pub line: Color,
pub cluster_fill: Color,
pub note_fill: Color,
pub note_border: Color,
pub font: TextStyle,
pub max_width: f32,
/// Set with [`Self::min_scale`].
min_scale: f32,
}
impl Hash for DiagramStyle {
fn hash<H: Hasher>(&self, state: &mut H) {
[
self.text,
self.muted,
self.surface,
self.surface_border,
self.node_fill,
self.node_border,
self.line,
self.cluster_fill,
self.note_fill,
self.note_border,
]
.hash(state);
self.font.hash(state);
let bits = if self.max_width == 0.0 { 0 } else if self.max_width.is_nan() { f32::NAN.to_bits() } else { self.max_width.to_bits() };
bits.hash(state);
self.min_scale.to_bits().hash(state);
}
}
impl DiagramStyle {
/// Neutral light or dark colours derived from Rune's core tokens.
pub fn neutral(dark: bool) -> Self {
let t = tok::theme(dark);
Self {
text: t.text,
muted: t.text_secondary,
surface: t.bg,
surface_border: t.separator,
node_fill: t.card,
node_border: t.text.alpha(0.2),
line: t.text.alpha(0.42),
cluster_fill: t.text.alpha(if dark { 0.04 } else { 0.025 }),
note_fill: oklcha(if dark { 0.3 } else { 0.95 }, 0.04, 80.0, 1.0),
note_border: oklch(if dark { 0.4 } else { 0.85 }, 0.08, 80.0),
font: TextStyle::new(13.0, 400.0).lh(18.0),
max_width: 680.0,
min_scale: 0.6,
}
}
/// The least a diagram wider than [`Self::max_width`] shrinks to (0.6 by default). Past it,
/// the card shows the middle and fades out at its sides. `0.0` always fits the whole
/// diagram in.
pub fn min_scale(mut self, k: f32) -> Self {
self.min_scale = k.clamp(0.0, 1.0);
self
}
}
/// `src` drawn as a diagram card in `style`, or `None` when it is outside the supported subset.
pub fn render(src: &str, style: &DiagramStyle) -> Option<El> {
render_with_hover(src, style, Hover::Edges, style.text.alpha(0.9))
}
/// [`render`], with `hover` lighting up in `color` while the pointer is over a flowchart, state
/// or class diagram node; an edge, or its label, lights itself and its label whatever `hover` is
/// short of [`Hover::Off`].
pub fn render_with_hover(src: &str, style: &DiagramStyle, hover: Hover, color: Color) -> Option<El> {
render_inner(src, style, hover, color, Mode::Still)
}
/// [`render_with_hover`] for a source still arriving (pass only its complete lines): each node,
/// edge and frame new since the last build comes in on its own, and the rest glide into place.
/// The diagram only grows: what's drawn keeps its order and place, as far as what's new leaves
/// room, and no gap closes.
pub fn render_streaming(src: &str, style: &DiagramStyle, hover: Hover, color: Color) -> Option<El> {
render_inner(src, style, hover, color, Mode::Growing)
}
/// [`render_streaming`] for the whole source once it has all arrived: laid out as
/// [`render_with_hover`] lays it out, so the diagram settles there in one glide, while what's
/// new since the last build still comes in on its own.
pub fn render_streamed(src: &str, style: &DiagramStyle, hover: Hover, color: Color) -> Option<El> {
render_inner(src, style, hover, color, Mode::Settled)
}
/// A diagram's title and drawing without its card, for a viewer that frames and scales it
/// itself (a lightbox whose frame stays the card's size while the drawing grows).
#[non_exhaustive]
pub struct Drawing {
pub el: El,
/// The points `el` takes.
pub size: [f32; 2],
/// The fill and border of the card it would draw in, for the viewer's frame.
pub surface: Color,
pub surface_border: Color,
}
/// [`render_with_hover`]'s title and drawing alone, laid out and fitted for `style.max_width`
/// as its card would be.
pub fn render_drawing(src: &str, style: &DiagramStyle, hover: Hover, color: Color) -> Option<Drawing> {
let hover = (hover != Hover::Off).then_some((hover, color));
let (el, size) = scenes::built(src, style, hover, None).0?.drawing(style, None);
Some(Drawing { el, size, surface: style.surface, surface_border: style.surface_border })
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Mode {
/// Laid out afresh and drawn the frame it mounts.
Still,
/// Laid out afresh; what's new comes in on its own.
Settled,
/// Held to the build one line shorter ([`layout::steady`]); what's new comes in on its own.
Growing,
}
fn render_inner(src: &str, style: &DiagramStyle, hover: Hover, color: Color, mode: Mode) -> Option<El> {
let hover = (hover != Hover::Off).then_some((hover, color));
let scene = if mode == Mode::Growing { scenes::growing(src, style, hover) } else { scenes::built(src, style, hover, None).0 };
scene.map(|s| s.el(style, mode != Mode::Still))
}
/// Whether `src` parses as a supported diagram.
pub fn supported(src: &str) -> bool {
parse(src).is_some()
}
pub(crate) enum Diagram {
Flowchart(graph::flowchart::Flowchart),
Sequence(sequence::Sequence),
State(graph::state::StateDiagram),
Class(graph::class::ClassDiagram),
Er(graph::er::ErDiagram),
Gantt(chart::gantt::Gantt),
Pie(chart::pie::Pie),
Mindmap(chart::mindmap::Mindmap),
Timeline(chart::timeline::Timeline),
Journey(chart::journey::Journey),
Git(chart::git::GitGraph),
Quadrant(chart::quadrant::Quadrant),
XyChart(chart::xychart::XyChart),
Sankey(chart::sankey::Sankey),
Block(graph::block::BlockDiagram),
Requirement(graph::requirement::Requirements),
C4(graph::c4::C4),
}
pub(crate) struct Parsed {
pub title: Option<String>,
pub diagram: Diagram,
}
/// Diagrams bigger than this are left as source: they would be unreadable at markdown width.
pub(crate) const MAX_ITEMS: usize = 400;
/// How deep subgraphs, composite states, frames and other blocks may nest.
pub(crate) const MAX_DEPTH: usize = 8;
/// Whether `src`, the complete lines of a diagram still arriving, may draw once more arrive: it
/// has no header yet (only blank lines, comments or front matter), or its header names a type
/// this crate draws.
pub fn may_draw(src: &str) -> bool {
let (_, mut lines) = cleaned(src);
lines.next().is_none_or(|(_, header)| KINDS.contains(&header.split_once(|c: char| c.is_whitespace() || c == ';').map_or(header, |h| h.0)))
}
/// Every diagram type [`parse`] reads, by its header's first word.
const KINDS: &[&str] = &[
"graph", "flowchart", "sequenceDiagram", "stateDiagram", "stateDiagram-v2", "classDiagram", "erDiagram", "gantt", "pie",
"mindmap", "timeline", "journey", "gitGraph", "gitGraph:", "quadrantChart", "xychart-beta", "xychart", "sankey-beta",
"sankey", "block-beta", "block", "requirementDiagram", "C4Context", "C4Container", "C4Component", "C4Dynamic",
"C4Deployment",
];
/// `src`'s front-matter title, and its lines with their indents, without comments, directives
/// and front matter.
fn cleaned(src: &str) -> (Option<String>, impl Iterator<Item = (usize, &str)>) {
let mut in_directive = false;
let mut lines = src.lines().filter_map(move |raw| {
let line = raw.trim();
let (indent, text) = if in_directive || line.starts_with("%%{") {
let Some((_, rest)) = line.split_once("}%%") else {
in_directive = true;
return None;
};
in_directive = false;
(0, rest.trim())
} else {
// Mindmaps nest by indentation.
(raw.len() - raw.trim_start().len(), line)
};
(!text.is_empty() && !text.starts_with("%%")).then_some((indent, text))
}).peekable();
let mut fm_title = None;
// A front-matter block (`---` … `---`) may carry `title: …` and config.
if lines.peek().map(|l| l.1) == Some("---") {
lines.next();
for (_, l) in lines.by_ref() {
if l == "---" {
break;
}
if let Some(rest) = l.strip_prefix("title:") {
let t = clean_quoted(rest);
if !t.is_empty() {
fm_title = Some(t);
}
}
}
}
(fm_title, lines)
}
pub(crate) fn parse(src: &str) -> Option<Parsed> {
let (fm_title, mut lines) = cleaned(src);
let (_, header) = lines.next()?;
let (kind, rest) = header.split_once(|c: char| c.is_whitespace() || c == ';').unwrap_or((header, ""));
let (indents, body): (Vec<usize>, Vec<&str>) = lines.unzip();
let (body_title, diagram) = match kind {
"graph" | "flowchart" => graph::flowchart::parse(rest, &body).map(|f| (f.title.clone(), Diagram::Flowchart(f)))?,
"sequenceDiagram" => sequence::parse(rest, &body).map(|s| (s.title.clone(), Diagram::Sequence(s)))?,
"stateDiagram" | "stateDiagram-v2" => graph::state::parse(rest, &body).map(|s| (s.title.clone(), Diagram::State(s)))?,
"classDiagram" => graph::class::parse(rest, &body).map(|c| (c.title.clone(), Diagram::Class(c)))?,
"erDiagram" => graph::er::parse(rest, &body).map(|e| (e.title.clone(), Diagram::Er(e)))?,
"gantt" => chart::gantt::parse(rest, &body).map(|g| (g.title.clone(), Diagram::Gantt(g)))?,
"pie" => chart::pie::parse(rest, &body).map(|p| (p.title.clone(), Diagram::Pie(p)))?,
"mindmap" => chart::mindmap::parse(&body, &indents).map(|m| (None, Diagram::Mindmap(m)))?,
"timeline" => chart::timeline::parse(rest, &body).map(|t| (t.title.clone(), Diagram::Timeline(t)))?,
"journey" => chart::journey::parse(&body).map(|j| (j.title.clone(), Diagram::Journey(j)))?,
"gitGraph" | "gitGraph:" => chart::git::parse(rest, &body).map(|g| (None, Diagram::Git(g)))?,
"quadrantChart" => chart::quadrant::parse(&body).map(|q| (q.title.clone(), Diagram::Quadrant(q)))?,
"xychart-beta" | "xychart" => chart::xychart::parse(rest, &body).map(|x| (x.title.clone(), Diagram::XyChart(x)))?,
"sankey-beta" | "sankey" => chart::sankey::parse(&body).map(|s| (None, Diagram::Sankey(s)))?,
"block-beta" | "block" => graph::block::parse(&body).map(|b| (None, Diagram::Block(b)))?,
"requirementDiagram" => graph::requirement::parse(&body).map(|r| (None, Diagram::Requirement(r)))?,
"C4Context" | "C4Container" | "C4Component" | "C4Dynamic" | "C4Deployment" => graph::c4::parse(kind, &body).map(|c| (c.title.clone(), Diagram::C4(c)))?,
_ => return None,
};
Some(Parsed { title: body_title.or(fm_title), diagram })
}
pub(crate) fn scene(src: &str, paint: &DiagramStyle, hover: Option<(Hover, Color)>) -> Option<Scene> {
let parsed = parse(src)?;
let s = match &parsed.diagram {
Diagram::Flowchart(f) => graph::flowchart::draw(f, paint, hover),
Diagram::Sequence(s) => sequence::draw(s, paint),
Diagram::State(s) => graph::state::draw(s, paint, hover),
Diagram::Class(c) => graph::class::draw(c, paint, hover),
Diagram::Er(e) => graph::er::draw(e, paint, hover),
Diagram::Gantt(g) => chart::gantt::draw(g, paint),
Diagram::Pie(p) => chart::pie::draw(p, paint),
Diagram::Mindmap(m) => chart::mindmap::draw(m, paint),
Diagram::Timeline(t) => chart::timeline::draw(t, paint),
Diagram::Journey(j) => chart::journey::draw(j, paint),
Diagram::Git(g) => chart::git::draw(g, paint),
Diagram::Quadrant(q) => chart::quadrant::draw(q, paint),
Diagram::XyChart(x) => chart::xychart::draw(x, paint),
Diagram::Sankey(s) => chart::sankey::draw(s, paint),
Diagram::Block(b) => graph::block::draw(b, paint),
Diagram::Requirement(r) => graph::requirement::draw(r, paint, hover),
Diagram::C4(c) => graph::c4::draw(c, paint, hover),
}?;
Some(s.with_title(parsed.title))
}
/// Strips one pair of surrounding `"…"` quotes (unescaping `\"`), then runs [`clean`].
pub(crate) fn clean_quoted(s: &str) -> String {
let t = s.trim();
if let Some(inner) = t.strip_prefix('"').and_then(|r| r.strip_suffix('"')) {
return clean(&inner.replace("\\\"", "\""));
}
clean(t)
}
/// Mermaid label markup to plain text: `<br>` and `\n` breaks, entity codes, markdown-string backticks.
pub(crate) fn clean(s: &str) -> String {
let s = s.trim();
let s = s.strip_prefix('`').and_then(|s| s.strip_suffix('`')).unwrap_or(s);
let mut out = String::with_capacity(s.len());
let mut rest = s;
while let Some(i) = rest.find(['<', '#', '&', '\\']) {
out.push_str(&rest[..i]);
rest = &rest[i..];
let lower = rest.get(..6).unwrap_or(rest).to_ascii_lowercase();
let (rep, len) = if lower.starts_with("<br>") {
("\n", 4)
} else if lower.starts_with("<br/>") {
("\n", 5)
} else if lower.starts_with("<br />") {
("\n", 6)
} else if rest.starts_with("\\n") {
("\n", 2)
} else if rest.starts_with("#quot;") {
("\"", 6)
} else if rest.starts_with("#59;") {
(";", 4)
} else if rest.starts_with("#35;") {
("#", 4)
} else if rest.starts_with("&amp;") {
("&", 5)
} else if rest.starts_with("&lt;") {
("<", 4)
} else if rest.starts_with("&gt;") {
(">", 4)
} else if rest.starts_with("&quot;") {
("\"", 6)
} else if rest.starts_with("&apos;") || rest.starts_with("#apos;") {
("'", 6)
} else {
(&rest[..1], 1)
};
out.push_str(rep);
rest = &rest[len..];
}
out.push_str(rest);
out.lines().map(str::trim).collect::<Vec<_>>().join("\n")
}
/// Optional CSS-like node colours from `style` or `classDef`.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(crate) struct NodeStyle {
pub fill: Option<Color>,
pub stroke: Option<Color>,
pub color: Option<Color>,
/// `stroke-width`, in Mermaid's px (one point each).
pub width: Option<f32>,
}
impl NodeStyle {
pub(crate) fn merge(self, over: NodeStyle) -> NodeStyle {
NodeStyle {
fill: over.fill.or(self.fill),
stroke: over.stroke.or(self.stroke),
color: over.color.or(self.color),
width: over.width.or(self.width),
}
}
/// Resolves `(fill, border, text)` against `paint` in Oklab so light-mode Mermaid hex fills
/// (like `fill:#dcf5dc`) read cleanly in both dark and light themes without washing out text.
pub(crate) fn resolve(self, paint: &DiagramStyle) -> (Color, Color, Color) {
let fill = self.fill.map_or(paint.node_fill, |c| adapt_fill(paint.node_fill, c, 0.055, 0.035));
let border = self.stroke.or(self.fill).map_or(paint.node_border, |c| adapt_stroke(paint.node_border, c, paint.node_fill.to_oklab()[0] < 0.5));
let text = match self.color {
Some(c) if (c.to_oklab()[0] - fill.to_oklab()[0]).abs() > 0.35 => c,
_ => paint.text,
};
(fill, border, text)
}
}
/// Optional edge overrides from `linkStyle`.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(crate) struct EdgeStyle {
pub stroke: Option<Color>,
pub width: Option<f32>,
}
impl EdgeStyle {
pub(crate) fn merge(self, over: EdgeStyle) -> EdgeStyle {
EdgeStyle { stroke: over.stroke.or(self.stroke), width: over.width.or(self.width) }
}
}
/// Accumulates `classDef`, `class` / `:::class`, and `style` rules and resolves a node's [`NodeStyle`].
#[derive(Default)]
pub(crate) struct StyleSheet {
defs: HashMap<String, NodeStyle>,
classes: HashMap<String, Vec<String>>,
inline: HashMap<String, NodeStyle>,
}
impl StyleSheet {
pub(crate) fn class_def(&mut self, rest: &str) -> Option<()> {
let (names, props) = rest.trim().split_once(char::is_whitespace)?;
let st = parse_style_props(props);
for name in names.split(',').map(str::trim).filter(|n| !n.is_empty()) {
self.defs.insert(name.to_owned(), st);
}
Some(())
}
pub(crate) fn assign_classes(&mut self, rest: &str) -> Option<()> {
let (targets, classes) = rest.trim().split_once(char::is_whitespace)?;
let cls_list: Vec<&str> = classes.split(',').map(str::trim).filter(|c| !c.is_empty()).collect();
for id in targets.split(',').map(str::trim).filter(|n| !n.is_empty()) {
for &cls in &cls_list {
self.add_class(id, cls);
}
}
Some(())
}
pub(crate) fn style(&mut self, rest: &str) -> Option<()> {
let (targets, props) = rest.trim().split_once(char::is_whitespace)?;
let st = parse_style_props(props);
for id in targets.split(',').map(str::trim).filter(|n| !n.is_empty()) {
self.add_style(id, st);
}
Some(())
}
pub(crate) fn add_class(&mut self, id: &str, class: &str) {
if !id.is_empty() && !class.is_empty() {
self.classes.entry(id.to_owned()).or_default().push(class.to_owned());
}
}
pub(crate) fn add_style(&mut self, id: &str, st: NodeStyle) {
if !id.is_empty() {
let cur = self.inline.get(id).copied().unwrap_or_default();
self.inline.insert(id.to_owned(), cur.merge(st));
}
}
/// Strips a trailing `:::class` from `raw`, recording the class assignment.
pub(crate) fn strip_inline(&mut self, raw: &str) -> Option<String> {
match raw.split_once(":::") {
Some((id, cls)) => {
let (id, cls) = (id.trim(), cls.trim());
if id.is_empty() || cls.is_empty() {
return None;
}
self.add_class(id, cls);
Some(id.to_owned())
}
None => Some(raw.trim().to_owned()),
}
}
pub(crate) fn get(&self, id: &str) -> NodeStyle {
let mut st = NodeStyle::default();
if let Some(classes) = self.classes.get(id) {
for cls in classes {
if let Some(&cs) = self.defs.get(cls) {
st = st.merge(cs);
}
}
}
if let Some(&inline) = self.inline.get(id) {
st = st.merge(inline);
}
st
}
}
/// Adapts a user colour `c` into a subtle Oklab fill harmonious with `base`.
pub(crate) fn adapt_fill(base: Color, c: Color, dark_lift: f32, light_drop: f32) -> Color {
let base_l = base.to_oklab()[0];
let dark = base_l < 0.5;
let [_, a, b, _] = c.to_oklab();
let chroma = a.hypot(b);
if chroma < 0.01 {
return oklab_mix(base, c, 0.2);
}
let scale = (chroma * 0.9).clamp(0.032, 0.075) / chroma;
let l = if dark { (base_l + dark_lift).min(0.42) } else { (base_l - light_drop).max(0.82) };
Color::from_oklab([l, a * scale, b * scale, base.a])
}
pub(crate) fn adapt_stroke(base: Color, c: Color, dark: bool) -> Color {
let [_, a, b, _] = c.to_oklab();
let chroma = a.hypot(b);
if chroma < 0.01 {
return oklab_mix(base, c, 0.35);
}
let scale = (chroma * 1.1).clamp(0.07, 0.13) / chroma;
Color::from_oklab([if dark { 0.58 } else { 0.60 }, a * scale, b * scale, 1.0])
}
pub(crate) fn oklab_mix(a: Color, b: Color, t: f32) -> Color {
let (a, b) = (a.to_oklab(), b.to_oklab());
Color::from_oklab([0, 1, 2, 3].map(|i| if i == 3 { a[3] } else { a[i] + (b[i] - a[i]) * t }))
}
pub(crate) fn parse_style_props(props: &str) -> NodeStyle {
let mut out = NodeStyle::default();
for part in props.split([',', ';']) {
let Some((k, v)) = part.split_once(':') else { continue };
let v = v.trim().trim_end_matches("!important").trim();
match k.trim() {
"fill" => out.fill = parse_color_spec(v),
"stroke" => out.stroke = parse_color_spec(v),
"color" => out.color = parse_color_spec(v),
"stroke-width" => out.width = px(v).map(|w| w.clamp(0.0, 5.0)),
_ => {}
}
}
out
}
/// A CSS length in px (`2px`, `2`).
fn px(v: &str) -> Option<f32> {
v.trim_end_matches("px").trim().parse::<f32>().ok().filter(|w| w.is_finite())
}
pub(crate) fn parse_edge_style_props(props: &str) -> EdgeStyle {
let mut out = EdgeStyle::default();
for part in props.split([',', ';']) {
let Some((k, v)) = part.split_once(':') else { continue };
let v = v.trim().trim_end_matches("!important").trim();
match k.trim() {
"stroke" => out.stroke = parse_color_spec(v),
"stroke-width" => out.width = px(v).map(|w| w.clamp(0.75, 5.0)),
_ => {}
}
}
out
}
/// `#hex`, `rgb(r, g, b)`, `rgba(r, g, b, a)`, or a common CSS colour word.
pub(crate) fn parse_color_spec(s: &str) -> Option<Color> {
let s = s.trim();
if let Some(c) = rune::color::hex(s) {
return Some(c);
}
let lower = s.to_ascii_lowercase();
if let Some(inner) = lower.strip_prefix("rgb(").or_else(|| lower.strip_prefix("rgba(")).and_then(|r| r.strip_suffix(')')) {
let nums: Vec<f32> = inner.split(',').filter_map(|p| p.trim().parse::<f32>().ok()).collect();
if nums.len() >= 3 {
let [r, g, b] = [nums[0], nums[1], nums[2]].map(|v| rune::color::srgb_decode((v / 255.0).clamp(0.0, 1.0)));
let a = nums.get(3).copied().unwrap_or(1.0).clamp(0.0, 1.0);
return Some(Color { r, g, b, a });
}
}
let hex = match lower.as_str() {
"red" | "crimson" | "salmon" | "lightcoral" | "pink" => "#ef4444",
"green" | "lightgreen" | "palegreen" | "emerald" | "lime" => "#22c55e",
"blue" | "lightblue" | "skyblue" | "dodgerblue" => "#3b82f6",
"yellow" | "lightyellow" | "gold" | "amber" | "orange" => "#eab308",
"purple" | "violet" | "lavender" | "magenta" => "#a855f7",
"cyan" | "aqua" | "teal" | "turquoise" => "#06b6d4",
"gray" | "grey" | "lightgray" | "lightgrey" | "silver" => "#9ca3af",
_ => return None,
};
rune::color::hex(hex)
}
/// What follows keyword `w` and a space, trimmed.
pub(crate) fn word<'a>(l: &'a str, w: &str) -> Option<&'a str> {
l.strip_prefix(w).filter(|r| r.is_empty() || r.starts_with(char::is_whitespace)).map(str::trim)
}
/// A line split at `;` outside quotes and brackets (and never at an HTML entity's `;`).
pub(crate) fn statements(line: &str) -> Vec<&str> {
let mut out = Vec::new();
let (mut start, mut quoted, mut escaped, mut brackets) = (0usize, false, false, 0usize);
for (i, c) in line.char_indices() {
if escaped {
escaped = false;
continue;
}
if quoted {
match c {
'\\' => escaped = true,
'"' => quoted = false,
_ => {}
}
continue;
}
match c {
'"' => quoted = true,
'[' | '(' | '{' => brackets += 1,
']' | ')' | '}' => brackets = brackets.saturating_sub(1),
';' if brackets == 0 => {
out.push(&line[start..i]);
start = i + 1;
}
_ => {}
}
}
out.push(&line[start..]);
out.into_iter().map(str::trim).filter(|s| !s.is_empty() && !s.starts_with("%%")).collect()
}
/// A byte cursor over one statement.
pub(crate) struct Cur<'a> {
pub s: &'a str,
pub i: usize,
}
impl<'a> Cur<'a> {
pub fn new(s: &'a str) -> Self {
Cur { s, i: 0 }
}
pub fn rest(&self) -> &'a str {
&self.s[self.i..]
}
pub fn peek(&self) -> Option<char> {
self.rest().chars().next()
}
pub fn peek2(&self) -> Option<char> {
self.rest().chars().nth(1)
}
pub fn bump(&mut self) {
if let Some(c) = self.peek() {
self.i += c.len_utf8();
}
}
pub fn eat(&mut self, t: &str) -> bool {
let hit = self.rest().starts_with(t);
if hit {
self.i += t.len();
}
hit
}
pub fn skip_ws(&mut self) {
while self.peek().is_some_and(char::is_whitespace) {
self.bump();
}
}
pub fn done(&self) -> bool {
self.i >= self.s.len()
}
}
#[cfg(test)]
mod tests;
+384
View File
@@ -0,0 +1,384 @@
//! Sequence diagram drawing: participants across the top, events down the page.
use rune::{Align, Color, TextStyle};
use super::{Event, Kind, NotePos, Sequence, Tip};
use crate::canvas::parts::{Kind as PartKind, Part};
use crate::canvas::shape::{self, NodeShape};
use crate::canvas::{Canvas, Measured, Scene, arrowhead, ellipse, measure, rounded_rect};
use crate::{DiagramStyle, adapt_fill};
const BAR: f32 = 10.0;
struct Frame {
kind: Option<Measured>,
label: Measured,
fill: Option<Color>,
top: f32,
dividers: Vec<(f32, Measured)>,
x: [f32; 2],
}
pub(crate) fn draw(s: &Sequence, paint: &DiagramStyle) -> Option<Scene> {
let font = paint.font;
let small = TextStyle { size: font.size - 1.0, line_height: font.line_height - 2.0, ..font };
let bold = TextStyle { weight: 600.0, ..small };
let num_font = TextStyle { size: 10.0, line_height: 12.0, weight: 600.0, ..font };
let n = s.participants.len();
let heads: Vec<Measured> = s.participants.iter().map(|p| measure(&p.label, font)).collect();
let boxes: Vec<[f32; 2]> = s.participants.iter().zip(&heads).map(|(p, m)| head_size(p.kind, m.size)).collect();
let box_titles: Vec<Measured> = s.boxes.iter().map(|b| measure(&b.title, bold)).collect();
let box_lead = if s.boxes.is_empty() {
0.0
} else {
let th = box_titles.iter().map(|t| t.size[1]).fold(0.0, f32::max);
if th > 0.0 { th + 18.0 } else { 10.0 }
};
let max_head_h = boxes.iter().map(|b| b[1]).fold(0.0, f32::max);
let top_h = box_lead + max_head_h;
let texts: Vec<Option<Measured>> = s
.events
.iter()
.map(|e| match e {
Event::Message(m) => Some(measure(&m.text, small)),
Event::Note(_, t) => Some(measure(t, small)),
Event::Open { label: t, .. } | Event::Else(t) => Some(measure(&if t.is_empty() { String::new() } else { format!("[{t}]") }, small)),
_ => None,
})
.collect();
let width_of = |i: usize| texts[i].as_ref().map_or(0.0, |m| m.size[0]);
let number = if s.autonumber { 20.0 } else { 0.0 };
let mut need: Vec<(usize, usize, f32)> = Vec::new();
for (i, e) in s.events.iter().enumerate() {
match e {
Event::Message(m) if m.from != m.to => need.push((m.from.min(m.to), m.from.max(m.to), width_of(i) + 32.0 + number)),
Event::Message(m) if m.from + 1 < n => need.push((m.from, m.from + 1, width_of(i) + 48.0)),
Event::Note(NotePos::Right(a), _) if a + 1 < n => need.push((*a, a + 1, width_of(i) + 40.0)),
Event::Note(NotePos::Left(a), _) if *a > 0 => need.push((a - 1, *a, width_of(i) + 40.0)),
_ => {}
}
}
let mut cx = vec![boxes[0][0] / 2.0 + if s.participants[0].group.is_some() { 10.0 } else { 0.0 }; n];
for j in 1..n {
let boundary_gap = if s.participants[j - 1].group != s.participants[j].group { 20.0 } else { 0.0 };
cx[j] = cx[j - 1] + (boxes[j - 1][0] + boxes[j][0]) / 2.0 + 24.0 + boundary_gap;
for &(a, b, d) in &need {
if b == j {
cx[j] = cx[j].max(cx[a] + d);
}
}
}
let (mut groups_bg, mut back, mut lifelines, mut bars, mut front, mut tops) = (
Canvas::default(),
Canvas::default(),
Canvas::default(),
Canvas::default(),
Canvas::default(),
Canvas::default(),
);
let mut tabs = Canvas::default();
let mut active: Vec<Vec<f32>> = vec![Vec::new(); n];
let mut frames: Vec<Frame> = Vec::new();
let mut y = top_h + 20.0;
let mut number: Option<(u32, u32)> = None;
// Where each lifeline starts and ends, and who goes at their next message.
let mut starts = vec![top_h; n];
let mut ends: Vec<Option<f32>> = vec![None; n];
let mut doomed: Vec<usize> = Vec::new();
let edge_x = |active: &[Vec<f32>], i: usize, right: bool| {
let d = active[i].len();
if d == 0 { cx[i] } else { cx[i] + (d - 1) as f32 * 4.0 + if right { BAR / 2.0 } else { -BAR / 2.0 } }
};
let close_bar = |bars: &mut Canvas, active: &mut [Vec<f32>], i: usize, y: f32| {
let d = active[i].len();
if let Some(top) = active[i].pop() {
let x = cx[i] + (d - 1) as f32 * 4.0;
let k = bars.marks.len();
bars.part(Some(Part::Key(PartKind::Frame, format!("bar{k}"))));
bars.shape(rounded_rect(x - BAR / 2.0, top, x + BAR / 2.0, y.max(top + 8.0), 1.0), paint.node_fill, paint.node_border, 1.0);
}
};
let touch = |frames: &mut [Frame], x0: f32, x1: f32| {
for f in frames.iter_mut() {
f.x = [f.x[0].min(x0), f.x[1].max(x1)];
}
};
for (i, e) in s.events.iter().enumerate() {
match e {
Event::Message(m) => {
front.part(Some(Part::Key(PartKind::Edge, format!("m{i}"))));
let t = texts[i].as_ref().expect("messages are measured");
if m.activate {
active[m.to].push(y + t.size[1] + 6.0);
}
let line_y;
if m.from == m.to {
let x = edge_x(&active, m.from, true);
front.label_at(t, [x + 8.0, y], small, paint.muted, Align::Start);
line_y = y + t.size[1] + 6.0;
let pts = vec![[x, line_y], [x + 30.0, line_y], [x + 30.0, line_y + 18.0], [x + 2.0 + tip_len(m.tip), line_y + 18.0]];
stroke(&mut front, pts, m.dotted, paint);
tip(&mut front, m.tip, [x, line_y + 18.0], [-1.0, 0.0], paint);
touch(&mut frames, cx[m.from] - BAR, (x + 30.0).max(x + 8.0 + t.size[0]));
y = line_y + 18.0 + 16.0;
} else {
let right = m.to > m.from;
let sx = edge_x(&active, m.from, right);
let ex = edge_x(&active, m.to, !right);
let dir = if right { 1.0 } else { -1.0 };
let mid = (sx + ex) / 2.0;
let has_text = !t.text.is_empty();
front.label(t, [mid, y + t.size[1] / 2.0], small, paint.muted, Align::Center);
line_y = y + if has_text { t.size[1] + 6.0 } else { 4.0 };
let a = if m.both { sx + dir * tip_len(m.tip) } else { sx };
stroke(&mut front, vec![[a, line_y], [ex - dir * tip_len(m.tip), line_y]], m.dotted, paint);
tip(&mut front, m.tip, [ex, line_y], [dir, 0.0], paint);
if m.both {
tip(&mut front, m.tip, [sx, line_y], [-dir, 0.0], paint);
}
if let Some((k, step)) = &mut number {
let m = measure(&k.to_string(), num_font);
front.shape(rounded_rect(sx - (m.size[0] / 2.0 + 4.0).max(8.0), line_y - 8.0, sx + (m.size[0] / 2.0 + 4.0).max(8.0), line_y + 8.0, 8.0), paint.line, paint.line, 1.0);
front.label(&m, [sx, line_y], num_font, paint.surface, Align::Center);
*k = k.saturating_add(*step);
}
let (lo, hi) = (cx[m.from].min(cx[m.to]) - BAR, cx[m.from].max(cx[m.to]) + BAR);
touch(&mut frames, lo.min(mid - t.size[0] / 2.0), hi.max(mid + t.size[0] / 2.0));
y = line_y + 16.0;
}
if m.deactivate {
close_bar(&mut bars, &mut active, m.from, line_y);
}
let end_y = if m.from == m.to { line_y + 18.0 } else { line_y };
doomed.retain(|&d| {
let gone = d == m.from || d == m.to;
if gone {
ends[d] = Some(end_y + 14.0);
cross(&mut front, [cx[d], end_y + 14.0], paint);
y = y.max(end_y + 30.0);
}
!gone
});
}
Event::Create(a) => {
let [w, h] = boxes[*a];
let top = y;
tops.part(Some(Part::Key(PartKind::Node, format!("p{a}"))));
head(&mut tops, s.participants[*a].kind, &heads[*a], [cx[*a], top], [w, h], paint);
starts[*a] = top + h;
touch(&mut frames, cx[*a] - w / 2.0, cx[*a] + w / 2.0);
y = top + h + 14.0;
}
Event::Destroy(a) => doomed.push(*a),
Event::Number(on) => number = *on,
Event::Note(pos, _) => {
let t = texts[i].as_ref().expect("notes are measured");
let w = t.size[0] + 20.0;
let (x0, x1) = match *pos {
NotePos::Left(a) => (cx[a] - 12.0 - w, cx[a] - 12.0),
NotePos::Right(a) => (cx[a] + 12.0, cx[a] + 12.0 + w),
NotePos::Over(a, b) => {
let span = (cx[b] - cx[a] + 40.0).max(w);
let mid = (cx[a] + cx[b]) / 2.0;
(mid - span / 2.0, mid + span / 2.0)
}
};
let h = t.size[1] + 14.0;
y += 2.0;
front.part(Some(Part::Key(PartKind::Node, format!("note{i}"))));
front.shape(rounded_rect(x0, y, x1, y + h, 2.0), paint.note_fill, paint.note_border, 1.0);
front.label(t, [(x0 + x1) / 2.0, y + h / 2.0], small, paint.text, Align::Center);
touch(&mut frames, x0, x1);
y += h + 14.0;
}
Event::Activate(a) => active[*a].push(y - 8.0),
Event::Deactivate(a) => close_bar(&mut bars, &mut active, *a, y - 8.0),
Event::Open { kind, fill, .. } => {
let label = texts[i].clone().expect("frames are measured");
let kind = kind.as_deref().map(|k| measure(k, bold));
let h = kind.as_ref().map_or(if fill.is_some() { 8.0 } else { 0.0 }, |k| k.size[1].max(label.size[1]) + 14.0);
frames.push(Frame { kind, label, fill: *fill, top: y, dividers: Vec::new(), x: [f32::MAX, f32::MIN] });
y += h;
}
Event::Else(_) => {
let label = texts[i].clone().expect("dividers are measured");
let h = label.size[1] + 14.0;
if let Some(f) = frames.last_mut() {
f.dividers.push((y, label));
}
y += h;
}
Event::End => {
let Some(mut f) = frames.pop() else { continue };
if f.x[0] > f.x[1] {
f.x = [cx[0], cx[n - 1]];
}
let x0 = f.x[0] - 12.0;
let tab_w = f.kind.as_ref().map_or(0.0, |k| k.size[0] + 18.0);
let x1 = (f.x[1] + 12.0).max(x0 + tab_w + f.label.size[0] + 20.0);
let bottom = y - 4.0;
let key = format!("frame{}", back.marks.len());
back.part(Some(Part::Key(PartKind::Frame, key.clone())));
tabs.part(Some(Part::Key(PartKind::Frame, key)));
if let Some(kind) = &f.kind {
let th = kind.size[1].max(f.label.size[1]) + 6.0;
back.stroke(vec![[x0, f.top], [x1, f.top], [x1, bottom], [x0, bottom]], true, 1.0, paint.node_border);
let tab = vec![[x0, f.top], [x0 + tab_w, f.top], [x0 + tab_w, f.top + th - 6.0], [x0 + tab_w - 6.0, f.top + th], [x0, f.top + th]];
tabs.shape(tab, paint.node_fill, paint.node_border, 1.0);
tabs.label_at(kind, [x0 + 9.0, f.top + 3.0], bold, paint.text, Align::Start);
tabs.label_at(&f.label, [x0 + tab_w + 8.0, f.top + 3.0], small, paint.muted, Align::Start);
for (dy, label) in &f.dividers {
back.dashed(&[[x0, *dy], [x1, *dy]], 1.0, paint.node_border, 4.0, 3.0);
tabs.label_at(label, [x0 + 9.0, dy + 4.0], small, paint.muted, Align::Start);
}
} else if let Some(rect_col) = f.fill {
let band = adapt_fill(paint.surface, rect_col, 0.04, 0.03).alpha(0.55);
back.fill(rounded_rect(x0, f.top - 2.0, x1, bottom, 4.0), band);
}
touch(&mut frames, x0, x1);
y = bottom + 16.0;
}
}
}
let end = y + 4.0;
for a in 0..n {
while !active[a].is_empty() {
close_bar(&mut bars, &mut active, a, end - 8.0);
}
}
// Participant `box` columns behind everything else.
let box_border = crate::canvas::group_border(paint);
for (b_idx, b) in s.boxes.iter().enumerate() {
let members: Vec<usize> = (0..n).filter(|&i| s.participants[i].group == Some(b_idx)).collect();
let (Some(&first), Some(&last)) = (members.first(), members.last()) else { continue };
let mut x0 = cx[first] - boxes[first][0] / 2.0 - 10.0;
let mut x1 = cx[last] + boxes[last][0] / 2.0 + 10.0;
let title = &box_titles[b_idx];
if x1 - x0 < title.size[0] + 20.0 {
let mid = (x0 + x1) / 2.0;
x0 = mid - title.size[0] / 2.0 - 10.0;
x1 = mid + title.size[0] / 2.0 + 10.0;
}
let fill = b.color.map_or(paint.cluster_fill, |col| adapt_fill(paint.surface, col, 0.035, 0.03));
groups_bg.part(Some(Part::Key(PartKind::Frame, format!("box{b_idx}"))));
groups_bg.shape(rounded_rect(x0, 0.0, x1, end + max_head_h + 10.0, 6.0), fill, box_border, 1.0);
groups_bg.label(title, [(x0 + x1) / 2.0, 7.0 + title.size[1] / 2.0], bold, paint.muted, Align::Center);
}
let created: Vec<bool> = (0..n).map(|i| s.events.iter().any(|e| matches!(e, Event::Create(a) if *a == i))).collect();
for (i, p) in s.participants.iter().enumerate() {
let size = boxes[i];
let stop = ends[i].unwrap_or(end);
lifelines.part(Some(Part::Key(PartKind::Frame, format!("life{i}"))));
lifelines.stroke(vec![[cx[i], starts[i]], [cx[i], stop]], false, 1.0, paint.node_border);
if !created[i] {
tops.part(Some(Part::Key(PartKind::Node, format!("p{i}"))));
head(&mut tops, p.kind, &heads[i], [cx[i], top_h - size[1]], size, paint);
}
if ends[i].is_none() {
tops.part(Some(Part::Key(PartKind::Node, format!("p{i}.end"))));
head(&mut tops, p.kind, &heads[i], [cx[i], end], size, paint);
}
}
let mut c = groups_bg;
for layer in [back, lifelines, bars, tabs, front, tops] {
c.append(layer);
}
c.finish_fit(paint)
}
fn tip_len(t: Tip) -> f32 {
match t {
Tip::Filled => 8.0,
Tip::None | Tip::Open | Tip::Cross => 0.0,
}
}
fn stroke(c: &mut Canvas, pts: Vec<[f32; 2]>, dotted: bool, paint: &DiagramStyle) {
if dotted {
c.dashed(&pts, 1.25, paint.line, 4.0, 3.0);
} else {
c.stroke(pts, false, 1.25, paint.line);
}
}
fn tip(c: &mut Canvas, t: Tip, at: [f32; 2], d: [f32; 2], paint: &DiagramStyle) {
let back = |by: f32, side: f32| [at[0] - d[0] * by - d[1] * side, at[1] - d[1] * by + d[0] * side];
match t {
Tip::None => {}
Tip::Filled => c.fill(arrowhead(at, d, 9.0, 8.0), paint.line),
Tip::Open => c.stroke(vec![back(8.0, 4.5), at, back(8.0, -4.5)], false, 1.25, paint.line),
Tip::Cross => {
c.stroke(vec![back(9.0, 4.0), back(1.0, -4.0)], false, 1.5, paint.line);
c.stroke(vec![back(9.0, -4.0), back(1.0, 4.0)], false, 1.5, paint.line);
}
}
}
fn head_size(kind: Kind, t: [f32; 2]) -> [f32; 2] {
match kind {
Kind::Box => [(t[0] + 24.0).max(72.0), t[1] + 16.0],
Kind::Actor => [t[0].max(40.0), 40.0 + t[1]],
Kind::Boundary | Kind::Control | Kind::Entity => [t[0].max(44.0), 36.0 + t[1]],
Kind::Database => shape::node_size(NodeShape::Cylinder, t),
Kind::Collections => shape::node_size(NodeShape::StackedRect, t),
Kind::Queue => shape::node_size(NodeShape::HCylinder, t),
}
}
/// A participant's head, `size` wide and tall, its top centre at `top`.
fn head(c: &mut Canvas, kind: Kind, label: &Measured, top: [f32; 2], size: [f32; 2], paint: &DiagramStyle) {
let [x, y] = top;
let (w, h) = (size[0], size[1]);
let ring = |c: &mut Canvas, at: [f32; 2], r: f32| c.shape(ellipse(at, r, r), paint.node_fill, paint.line, 1.25);
let under = |c: &mut Canvas, glyph: f32| c.label(label, [x, y + glyph + label.size[1] / 2.0], paint.font, paint.text, Align::Center);
let colors = [paint.node_fill, paint.node_border, paint.text];
match kind {
Kind::Box => {
c.shape(rounded_rect(x - w / 2.0, y, x + w / 2.0, y + h, 4.0), paint.node_fill, paint.node_border, 1.0);
c.label(label, [x, y + h / 2.0], paint.font, paint.text, Align::Center);
}
Kind::Actor => {
actor(c, top, paint);
under(c, 40.0);
}
Kind::Boundary => {
ring(c, [x + 5.0, y + 15.0], 11.0);
c.stroke(vec![[x - 14.0, y + 4.0], [x - 14.0, y + 26.0]], false, 1.25, paint.line);
c.stroke(vec![[x - 14.0, y + 15.0], [x - 6.0, y + 15.0]], false, 1.25, paint.line);
under(c, 36.0);
}
Kind::Control => {
ring(c, [x, y + 17.0], 12.0);
c.stroke(vec![[x + 4.0, y + 1.0], [x - 1.0, y + 5.0], [x + 4.0, y + 9.0]], false, 1.25, paint.line);
under(c, 36.0);
}
Kind::Entity => {
ring(c, [x, y + 14.0], 12.0);
c.stroke(vec![[x - 12.0, y + 29.0], [x + 12.0, y + 29.0]], false, 1.25, paint.line);
under(c, 36.0);
}
Kind::Database => shape::draw(c, NodeShape::Cylinder, label, [x, y + h / 2.0], size, colors, paint),
Kind::Collections => shape::draw(c, NodeShape::StackedRect, label, [x, y + h / 2.0], size, colors, paint),
Kind::Queue => shape::draw(c, NodeShape::HCylinder, label, [x, y + h / 2.0], size, colors, paint),
}
}
/// The X that ends a destroyed participant's lifeline.
fn cross(c: &mut Canvas, at: [f32; 2], paint: &DiagramStyle) {
let [x, y] = at;
c.stroke(vec![[x - 7.0, y - 7.0], [x + 7.0, y + 7.0]], false, 2.0, paint.line);
c.stroke(vec![[x - 7.0, y + 7.0], [x + 7.0, y - 7.0]], false, 2.0, paint.line);
}
fn actor(c: &mut Canvas, top: [f32; 2], paint: &DiagramStyle) {
let [x, y] = top;
c.shape(ellipse([x, y + 7.0], 7.0, 7.0), paint.node_fill, paint.line, 1.25);
c.stroke(vec![[x, y + 14.0], [x, y + 26.0]], false, 1.25, paint.line);
c.stroke(vec![[x - 10.0, y + 18.0], [x + 10.0, y + 18.0]], false, 1.25, paint.line);
c.stroke(vec![[x - 8.0, y + 36.0], [x, y + 26.0], [x + 8.0, y + 36.0]], false, 1.25, paint.line);
}
+337
View File
@@ -0,0 +1,337 @@
//! Sequence diagrams: the parser for `sequenceDiagram` sources and their drawing.
mod draw;
use std::collections::HashMap;
use rune::Color;
pub(crate) use draw::draw;
use crate::{MAX_DEPTH, MAX_ITEMS, clean, clean_quoted, parse_color_spec};
#[derive(Debug)]
pub(crate) struct Participant {
#[cfg_attr(not(test), allow(dead_code, reason = "tests check parsing by id"))]
pub id: String,
pub label: String,
pub kind: Kind,
pub group: Option<usize>,
}
/// How a participant's head draws: `actor`, or a v11 `participant A@{ "type": "…" }`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Kind {
Box,
Actor,
Boundary,
Control,
Entity,
Database,
Collections,
Queue,
}
#[derive(Debug)]
pub(crate) struct ParticipantBox {
pub title: String,
pub color: Option<Color>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Tip {
None,
Filled,
Open,
Cross,
}
#[derive(Debug)]
pub(crate) struct Message {
pub from: usize,
pub to: usize,
pub text: String,
pub dotted: bool,
pub tip: Tip,
pub both: bool,
pub activate: bool,
pub deactivate: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum NotePos {
Left(usize),
Right(usize),
Over(usize, usize),
}
#[derive(Debug)]
pub(crate) enum Event {
Message(Message),
Note(NotePos, String),
Activate(usize),
Deactivate(usize),
/// `create`: the participant's head draws here instead of at the top.
Create(usize),
/// `destroy`: the participant's lifeline ends after its next message.
Destroy(usize),
/// `autonumber [start [step]]` from here on, or `autonumber off` (`None`).
Number(Option<(u32, u32)>),
/// A frame (`Some(kind)`) or a `rect` highlight band (`None`, with optional colour).
Open { kind: Option<String>, label: String, fill: Option<Color> },
Else(String),
End,
}
#[derive(Debug)]
pub(crate) struct Sequence {
pub title: Option<String>,
pub participants: Vec<Participant>,
pub boxes: Vec<ParticipantBox>,
pub events: Vec<Event>,
pub autonumber: bool,
}
pub(crate) fn parse(_header: &str, body: &[&str]) -> Option<Sequence> {
let mut p = Parser {
s: Sequence { title: None, participants: Vec::new(), boxes: Vec::new(), events: Vec::new(), autonumber: false },
ids: HashMap::new(),
depth: 0,
active_box: None,
};
// A line that doesn't read is skipped; one past the bounds leaves the whole diagram as source.
for line in body {
let (people, events) = (p.s.participants.len(), p.s.events.len());
if p.line(line).is_none() {
// Whatever the line added before it failed goes too.
p.s.participants.truncate(people);
p.s.events.truncate(events);
p.ids.retain(|_, &mut i| i < people);
}
if p.s.participants.len() > 40 || p.s.events.len() > MAX_ITEMS || p.depth > MAX_DEPTH {
return None;
}
}
// Frames still open at the end close there.
p.s.events.extend((0..p.depth).map(|_| Event::End));
(!p.s.participants.is_empty()).then_some(p.s)
}
struct Parser {
s: Sequence,
ids: HashMap<String, usize>,
depth: usize,
active_box: Option<usize>,
}
const ARROWS: &[(&str, bool, Tip, bool)] = &[
("<<-->>", true, Tip::Filled, true),
("<<->>", false, Tip::Filled, true),
("-->>", true, Tip::Filled, false),
("->>", false, Tip::Filled, false),
("--x", true, Tip::Cross, false),
("-x", false, Tip::Cross, false),
("--)", true, Tip::Open, false),
("-)", false, Tip::Open, false),
("-->", true, Tip::None, false),
("->", false, Tip::None, false),
];
impl Parser {
fn line(&mut self, l: &str) -> Option<()> {
let l = l.trim().trim_end_matches(';').trim_end();
let (word, rest) = l.split_once(char::is_whitespace).map_or((l, ""), |(w, r)| (w, r.trim()));
match word.trim_end_matches(':') {
"participant" | "actor" => {
self.declare(rest, word == "actor")?;
}
"create" => {
let (kind, name) = rest.split_once(char::is_whitespace).map_or((rest, ""), |(w, r)| (w, r.trim()));
let i = match kind {
"participant" | "actor" => self.declare(name, kind == "actor")?,
_ => return None,
};
self.s.events.push(Event::Create(i));
}
"destroy" => {
let i = self.id(rest)?;
self.s.events.push(Event::Destroy(i));
}
"title" => {
let t = clean_quoted(l["title".len()..].trim().trim_start_matches(':'));
if !t.is_empty() {
self.s.title = Some(t);
}
}
"accTitle" | "accDescr" | "link" | "links" | "properties" | "details" => {}
"autonumber" => {
let mut nums = rest.split_whitespace().map(str::parse::<u32>);
let on = match (rest, nums.next(), nums.next()) {
("off", ..) => None,
(_, None, _) => Some((1, 1)),
(_, Some(Ok(start)), None) => Some((start, 1)),
(_, Some(Ok(start)), Some(Ok(step))) => Some((start, step)),
_ => return None,
};
self.s.autonumber |= on.is_some();
self.s.events.push(Event::Number(on));
}
"activate" => {
let i = self.id(rest)?;
self.s.events.push(Event::Activate(i));
}
"deactivate" => {
let i = self.id(rest)?;
self.s.events.push(Event::Deactivate(i));
}
"Note" | "note" => self.note(rest)?,
kind @ ("loop" | "alt" | "opt" | "par" | "critical" | "break") => {
self.depth += 1;
self.s.events.push(Event::Open { kind: Some(kind.to_owned()), label: clean(rest), fill: None });
}
"rect" => {
self.depth += 1;
self.s.events.push(Event::Open { kind: None, label: String::new(), fill: parse_color_spec(rest) });
}
"box" => {
if self.active_box.is_some() {
return None;
}
let (color, title) = parse_box_header(rest);
self.s.boxes.push(ParticipantBox { title, color });
self.active_box = Some(self.s.boxes.len() - 1);
}
"else" | "and" | "option" => {
if self.depth == 0 {
return None;
}
self.s.events.push(Event::Else(clean(rest)));
}
"end" => {
if self.active_box.is_some() {
self.active_box = None;
} else {
self.depth = self.depth.checked_sub(1)?;
self.s.events.push(Event::End);
}
}
_ => self.message(l)?,
}
Some(())
}
fn declare(&mut self, rest: &str, actor: bool) -> Option<usize> {
let (rest, meta) = rest.split_once("@{").map_or((rest, ""), |(id, meta)| (id, meta));
let kind = if actor { Kind::Actor } else { meta_kind(meta) };
let (id, label) = match rest.split_once(" as ") {
Some((id, label)) => (id.trim(), clean_quoted(label)),
None => (rest.trim(), clean_quoted(rest)),
};
let i = self.id(id)?;
let p = &mut self.s.participants[i];
p.label = label;
p.kind = kind;
if p.group.is_none() {
p.group = self.active_box;
}
Some(i)
}
fn id(&mut self, name: &str) -> Option<usize> {
let name = name.trim().trim_matches('"');
if name.is_empty() || name.contains([':', ',']) {
return None;
}
if let Some(&i) = self.ids.get(name) {
return Some(i);
}
self.s.participants.push(Participant { id: name.to_owned(), label: clean(name), kind: Kind::Box, group: self.active_box });
self.ids.insert(name.to_owned(), self.s.participants.len() - 1);
Some(self.s.participants.len() - 1)
}
fn note(&mut self, rest: &str) -> Option<()> {
let (place, text) = rest.split_once(':')?;
let place = place.trim();
let lower = place.to_ascii_lowercase();
let pos = if lower.starts_with("left of ") {
NotePos::Left(self.id(&place["left of ".len()..])?)
} else if lower.starts_with("right of ") {
NotePos::Right(self.id(&place["right of ".len()..])?)
} else if lower.starts_with("over ") {
let who = &place["over ".len()..];
match who.split_once(',') {
Some((a, b)) => {
let (a, b) = (self.id(a)?, self.id(b)?);
NotePos::Over(a.min(b), a.max(b))
}
None => {
let a = self.id(who)?;
NotePos::Over(a, a)
}
}
} else {
return None;
};
self.s.events.push(Event::Note(pos, clean_quoted(text)));
Some(())
}
fn message(&mut self, l: &str) -> Option<()> {
let (lhs, text) = l.split_once(':').unwrap_or((l, ""));
let (at, &(tok, dotted, tip, both)) = lhs
.char_indices()
.filter(|&(_, ch)| ch == '-' || ch == '<')
.find_map(|(i, _)| ARROWS.iter().find(|a| lhs[i..].starts_with(a.0)).map(|a| (i, a)))?;
let from = lhs[..at].trim();
let rest = lhs[at + tok.len()..].trim_start();
let (activate, deactivate, to) = match rest.as_bytes().first() {
Some(b'+') => (true, false, &rest[1..]),
Some(b'-') => (false, true, &rest[1..]),
_ => (false, false, rest),
};
let (from, to) = (self.id(from)?, self.id(to)?);
self.s.events.push(Event::Message(Message { from, to, text: clean(text), dotted, tip, both, activate, deactivate }));
Some(())
}
}
/// The kind a v11 `@{ "type": "database" }` names; anything else is a plain box.
fn meta_kind(meta: &str) -> Kind {
let Some((_, after)) = meta.split_once("type") else { return Kind::Box };
let name = after.trim_start_matches(|c: char| c == '"' || c == ':' || c.is_whitespace());
let name: String = name.chars().take_while(|c| c.is_ascii_alphabetic()).collect();
match name.as_str() {
"actor" => Kind::Actor,
"boundary" => Kind::Boundary,
"control" => Kind::Control,
"entity" => Kind::Entity,
"database" => Kind::Database,
"collections" => Kind::Collections,
"queue" => Kind::Queue,
_ => Kind::Box,
}
}
fn parse_box_header(rest: &str) -> (Option<Color>, String) {
let rest = rest.trim();
if rest.is_empty() {
return (None, String::new());
}
if let Some(after_paren) = rest.strip_prefix("rgb(").or_else(|| rest.strip_prefix("rgba("))
&& let Some(end) = after_paren.find(')')
{
let col_len = rest.len() - after_paren.len() + end + 1;
return (parse_color_spec(&rest[..col_len]), clean_quoted(&rest[col_len..]));
}
let (first, tail) = rest.split_once(char::is_whitespace).unwrap_or((rest, ""));
if first.eq_ignore_ascii_case("transparent") {
return (None, clean_quoted(tail));
}
if let Some(c) = parse_color_spec(first) {
return (Some(c), clean_quoted(tail));
}
(None, clean_quoted(rest))
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,149 @@
use super::*;
use crate::DiagramStyle;
fn seq(src: &str) -> Sequence {
match crate::parse(src).map(|p| p.diagram) {
Some(crate::Diagram::Sequence(s)) => s,
_ => panic!("not a sequence diagram: {src:?}"),
}
}
#[test]
fn participants_messages_and_activation() {
let s = seq(
"sequenceDiagram\n autonumber\n actor U as User\n participant A as API server\n U->>+A: GET /items\n A-->>-U: 200 OK\n A->B: plain\n B-->A: dotted\n A-xB: lost\n B--)A: async\n A<<->>B: both\n A->>A: think",
);
assert!(s.autonumber);
let names: Vec<(&str, &str, Kind)> = s.participants.iter().map(|p| (p.id.as_str(), p.label.as_str(), p.kind)).collect();
assert_eq!(names, [("U", "User", Kind::Actor), ("A", "API server", Kind::Box), ("B", "B", Kind::Box)]);
let msgs: Vec<&Message> = s.events.iter().filter_map(|e| if let Event::Message(m) = e { Some(m) } else { None }).collect();
assert_eq!((msgs[0].from, msgs[0].to, msgs[0].text.as_str(), msgs[0].activate), (0, 1, "GET /items", true));
assert_eq!((msgs[1].dotted, msgs[1].tip, msgs[1].deactivate), (true, Tip::Filled, true));
assert_eq!((msgs[2].dotted, msgs[2].tip), (false, Tip::None));
assert_eq!((msgs[3].dotted, msgs[3].tip), (true, Tip::None));
assert_eq!(msgs[4].tip, Tip::Cross);
assert_eq!((msgs[5].dotted, msgs[5].tip), (true, Tip::Open));
assert!(msgs[6].both);
assert_eq!((msgs[7].from, msgs[7].to), (1, 1));
}
#[test]
fn notes_frames_boxes_and_explicit_activation() {
let s = seq(
"sequenceDiagram\n\
title Frame commit\n\
box rgb(30, 60, 90) Desk\n\
participant web-app\n\
end\n\
box Storage\n\
participant db\n\
end\n\
Note right of web-app: thinks\n\
note over web-app,db: shared<br>two lines\n\
loop Every minute\n\
web-app->>db: ping\n\
end\n\
alt ok\n\
activate db\n\
db-->>web-app: rows\n\
deactivate db\n\
else error\n\
db-->>web-app: 500\n\
end\n\
rect rgb(40, 80, 60)\n\
opt maybe\n\
web-app->db: x\n\
end\n\
end",
);
assert_eq!(s.title.as_deref(), Some("Frame commit"));
assert_eq!(s.boxes.len(), 2);
assert_eq!(s.boxes[0].title, "Desk");
assert!(s.boxes[0].color.is_some());
assert_eq!(s.participants[0].group, Some(0));
assert_eq!(s.participants[1].group, Some(1));
assert_eq!(s.participants[0].id, "web-app", "dashes in names");
assert!(matches!(s.events[0], Event::Note(NotePos::Right(0), ref t) if t == "thinks"));
assert!(matches!(s.events[1], Event::Note(NotePos::Over(0, 1), ref t) if t == "shared\ntwo lines"));
assert!(matches!(s.events[2], Event::Open { kind: Some(ref k), ref label, .. } if k == "loop" && label == "Every minute"));
assert!(s.events.iter().any(|e| matches!(e, Event::Else(l) if l == "error")));
assert!(s.events.iter().any(|e| matches!(e, Event::Activate(1))));
assert!(s.events.iter().any(|e| matches!(e, Event::Open { kind: None, fill: Some(_), .. })));
assert_eq!(s.events.iter().filter(|e| matches!(e, Event::End)).count(), 4);
assert!(draw(&s, &DiagramStyle::neutral(true)).is_some());
}
#[test]
fn only_sources_where_nothing_reads_are_rejected() {
for src in ["sequenceDiagram", "sequenceDiagram\nA something B", "sequenceDiagram\n->>B: no sender\nend\nelse x"] {
assert!(crate::parse(src).is_none(), "{src:?}");
}
}
#[test]
fn a_line_that_does_not_read_is_skipped() {
let msgs = |src: &str| seq(src).events.iter().filter(|e| matches!(e, Event::Message(_))).count();
for src in [
"sequenceDiagram\nA something B\nA->>B: hi",
"sequenceDiagram\n->>B: no sender\nA->>B: hi",
"sequenceDiagram\nA->>: no receiver\nA->>B: hi",
"sequenceDiagram\nend\nelse x\nA->>B: hi",
"sequenceDiagram\nNote sideways of A: x\nNote over A no colon\nA->>B: hi",
] {
assert_eq!(msgs(src), 1, "{src:?}");
assert_eq!(seq(src).participants.len(), 2, "a line that fails adds no participants: {src:?}");
}
let s = seq("sequenceDiagram\nloop unclosed\n A->>B: hi\nbox unclosed\n participant C");
assert!(matches!(s.events.last(), Some(Event::End)), "an open frame closes at the end");
assert_eq!(s.participants[2].group, Some(0));
let s = seq("sequenceDiagram\nparticipant A@{ \"type\": \"database\" }\nA->>B: hi");
assert_eq!(s.participants[0].label, "A");
}
#[test]
fn participant_types_draw_their_own_heads() {
let src = "sequenceDiagram\n participant W@{ \"type\": \"boundary\" }\n participant C@{ \"type\" : \"control\" }\n participant E@{ \"type\": \"entity\" }\n participant D@{ \"type\": \"database\" }\n participant L@{ \"type\": \"collections\" }\n participant Q@{ \"type\": \"queue\" }\n participant P@{ \"type\": \"mystery\" }\n W->>C: a\n C->>E: b\n E->>D: c\n D->>L: d\n L->>Q: e\n Q->>P: f";
let s = seq(src);
let kinds: Vec<Kind> = s.participants.iter().map(|p| p.kind).collect();
assert_eq!(kinds, [Kind::Boundary, Kind::Control, Kind::Entity, Kind::Database, Kind::Collections, Kind::Queue, Kind::Box]);
assert!(draw(&s, &DiagramStyle::neutral(false)).is_some());
}
#[test]
fn create_destroy_and_numbering() {
let s = seq(
"sequenceDiagram\n autonumber 10 5\n A->>B: hello\n create participant C\n B->>C: make\n destroy C\n C-->>B: bye\n autonumber off\n A->>B: quiet",
);
let has = |f: &dyn Fn(&Event) -> bool| s.events.iter().any(f);
assert!(has(&|e| matches!(e, Event::Number(Some((10, 5))))));
assert!(has(&|e| matches!(e, Event::Number(None))));
assert!(has(&|e| matches!(e, Event::Create(2))));
assert!(has(&|e| matches!(e, Event::Destroy(2))));
let paint = DiagramStyle::neutral(false);
let scene = draw(&s, &paint).unwrap();
let both = crate::scene("sequenceDiagram\n A->>B: hello\n B->>C: make\n C-->>B: bye\n A->>B: quiet", &paint, None).unwrap();
assert!(scene.size[1] > both.size[1], "the created head takes room of its own");
assert!(crate::parse("sequenceDiagram\n autonumber many\n A->>B: hi").is_some(), "an autonumber it can't read is skipped");
}
#[test]
fn nesting_past_the_bound_still_rejects() {
let deep = "loop x\n".repeat(crate::MAX_DEPTH + 1);
assert!(crate::parse(&format!("sequenceDiagram\n{deep}A->>B: hi")).is_none());
}
#[test]
fn every_prefix_draws_or_falls_back_without_panicking() {
crate::tests::assert_prefixes_never_panic(
"sequenceDiagram\n autonumber\n actor U as User\n U->>+A: hi\n loop retry\n A->>B: call\n B--xA: fail\n end\n Note left of U: waits\n A-->>-U: done",
true,
);
}
#[test]
fn long_messages_widen_their_gap() {
let paint = DiagramStyle::neutral(false);
let narrow = crate::scene("sequenceDiagram\nA->>B: hi", &paint, None).unwrap();
let wide = crate::scene("sequenceDiagram\nA->>B: a much longer message that needs room", &paint, None).unwrap();
assert!(wide.size[0] > narrow.size[0] + 100.0, "{:?} vs {:?}", wide.size, narrow.size);
}
+227
View File
@@ -0,0 +1,227 @@
use super::canvas::{Canvas, Op, dist, smooth};
use super::*;
#[test]
fn clean_turns_markup_into_text() {
assert_eq!(clean("a<br>b<br/>c<BR />d\\ne"), "a\nb\nc\nd\ne");
assert_eq!(clean("#quot;hi#quot; &amp; &lt;3 &apos;ok&apos;"), "\"hi\" & <3 'ok'");
assert_eq!(clean("`**md**`"), "**md**");
assert_eq!(clean("# not an entity & also not"), "# not an entity & also not");
assert_eq!(clean_quoted(" \"capuchin ≈ Cappuccino\" "), "capuchin ≈ Cappuccino");
}
#[test]
fn other_diagram_types_and_garbage_are_unsupported() {
for src in ["", "kanban\n Todo", "pie title Pets", "gantt\ntitle x", "erDiagram", "hello", "%% only a comment"] {
assert!(!supported(src), "{src:?}");
}
let with_title = scene("---\ntitle: Hi\n---\ngraph TD\nA-->B", &DiagramStyle::neutral(true), None).unwrap();
assert_eq!(with_title.title.as_deref(), Some("Hi"), "front matter title is preserved");
assert!(supported("%%{\n init: {'theme': 'dark'}\n}%%\nflowchart LR\nA-->B"), "multiline init directive is skipped");
assert!(supported("stateDiagram-v2\n[*] --> Idle\nIdle --> [*]"));
assert!(supported("classDiagram\nA <|-- B"));
assert!(supported("flowchart TD\n A[Runtime&lt;S&gt;] --> B[a; b]; B --> C"), "entities and bracketed `;` stay intact");
}
#[test]
fn directive_end_keeps_a_diagram_on_the_same_line() {
for directive in ["%%{init: {}}%%", "%%{\ninit: {}\n}%%"] {
let src = format!("{directive} mindmap\n root\n child");
let (_, lines) = cleaned(&src);
assert_eq!(lines.collect::<Vec<_>>(), [(0, "mindmap"), (2, "root"), (4, "child")]);
assert!(may_draw(&src));
}
}
#[test]
fn node_stroke_width_reads_mermaid_px() {
assert_eq!(parse_style_props("stroke:#333,stroke-width:2px").width, Some(2.0));
assert_eq!(parse_style_props("stroke-width:4").width, Some(4.0));
assert_eq!(parse_style_props("stroke-width:wide").width, None);
}
#[test]
fn node_style_keeps_contrast_in_dark_and_light_themes() {
let pastel = parse_style_props("fill:#dcf5dc,stroke:#333");
for dark in [true, false] {
let style = DiagramStyle::neutral(dark);
let (fill, _border, text) = pastel.resolve(&style);
let diff = (fill.to_oklab()[0] - text.to_oklab()[0]).abs();
assert!(diff > 0.45, "dark={dark} contrast {diff} between {fill:?} and {text:?}");
}
assert!(parse_color_spec("rgb(30, 60, 90)").is_some());
assert!(parse_color_spec("lightgreen").is_some());
}
#[test]
fn dashes_cover_the_line_in_on_off_runs() {
let mut c = Canvas::default();
c.dashed(&[[0.0, 0.0], [10.0, 0.0], [10.0, 10.0]], 1.0, Color::WHITE, 3.0, 1.0);
let dashes: Vec<&Vec<[f32; 2]>> = c.ops.iter().map(|op| match op { Op::Stroke { points, .. } => points, Op::Fill(..) => unreachable!() }).collect();
assert_eq!(dashes.len(), 5, "20 points of line in 4-point periods");
assert_eq!(dashes[0].first(), Some(&[0.0, 0.0]));
let corner = dashes[2];
assert_eq!(corner.len(), 3, "a dash turns the corner: {corner:?}");
assert!(dist(corner[0], [8.0, 0.0]) < 1e-4 && dist(corner[1], [10.0, 0.0]) < 1e-4 && dist(corner[2], [10.0, 1.0]) < 1e-4);
}
#[test]
fn smooth_passes_through_its_points() {
let pts = [[0.0, 0.0], [20.0, 40.0], [0.0, 80.0]];
let curve = smooth(&pts);
assert_eq!(curve.first(), Some(&pts[0]));
assert_eq!(curve.last(), Some(&pts[2]));
assert!(curve.iter().any(|p| dist(*p, pts[1]) < 0.01));
}
fn hostile(src: &str, draws: bool) {
let paint = DiagramStyle::neutral(true);
let t = rune::time::now();
let scene = scene(src, &paint, None);
let took = t.elapsed();
assert_eq!(scene.is_some(), draws, "{}…", &src[..src.len().min(80)]);
assert!(took.as_secs_f32() < 5.0, "{took:?} for {}…", &src[..src.len().min(80)]);
}
fn ids(prefix: &str, n: usize) -> String {
(1..=n).map(|i| format!("{prefix}{i}")).collect::<Vec<_>>().join(" & ")
}
#[test]
fn deep_subgraphs_fall_back() {
hostile(&format!("graph TD\n{}A\n{}", "subgraph s\n".repeat(5000), "end\n".repeat(5000)), false);
hostile(&format!("graph TD\n{}A\n{}", "subgraph s\n".repeat(9), "end\n".repeat(9)), false);
hostile(&format!("graph TD\n{}A\n{}", "subgraph s\n".repeat(8), "end\n".repeat(8)), true);
hostile(&format!("graph TD\nA\n{}", "subgraph s\nend\n".repeat(5000)), false);
}
#[test]
fn a_huge_cross_product_falls_back_before_it_is_built() {
hostile(&format!("graph TD\n{} --> {}", ids("A", 500), ids("B", 500)), false);
hostile(&format!("graph TD\n{}", ids("A", 5000)), false);
hostile(&format!("graph TD\n{} --> {}", ids("A", 10), ids("B", 10)), true);
}
#[test]
fn a_huge_dash_count_draws_at_the_longest_link() {
let paint = DiagramStyle::neutral(true);
hostile(&format!("graph TD\nA {}> B", "-".repeat(10_000)), true);
hostile(&format!("graph TD\nA -{}-> B", ".".repeat(10_000)), true);
let longest = scene(&format!("graph TD\nA {}> B", "-".repeat(10_000)), &paint, None).unwrap();
let eight = scene(&format!("graph TD\nA {}> B", "-".repeat(9)), &paint, None).unwrap();
assert_eq!(longest.size, eight.size);
}
#[test]
fn long_chords_over_a_chain_fall_back() {
let chain: Vec<String> = (0..129).map(|i| format!("N{i} --> N{}", i + 1)).collect();
let chords: Vec<String> = (0..140).map(|k| format!("N{} --> N{}", k % 10, 120 + k % 10)).collect();
hostile(&format!("graph TD\n{}\n{}", chain.join("\n"), chords.join("\n")), false);
let short: Vec<String> = (0..4).map(|k| format!("N{k} --> N{}", 30 + k)).collect();
hostile(&format!("graph TD\n{}\n{}", chain[..40].join("\n"), short.join("\n")), true);
}
#[test]
fn the_biggest_allowed_charts_draw_in_bounded_time() {
let mut lines = vec!["graph LR".to_owned()];
for i in 0..130 {
lines.push(format!("N{i} --> N{} & N{}", (i * 7 + 1) % 130, (i * 13 + 5) % 130));
}
let src = lines.join("\n");
assert!(parse(&src).is_some());
let paint = DiagramStyle::neutral(true);
let t = rune::time::now();
let drawn = scene(&src, &paint, None).is_some();
assert!(!drawn, "dense 260-edge random graph hits MAX_DUMMIES and falls back");
assert!(t.elapsed().as_secs_f32() < 5.0, "{:?}", t.elapsed());
let mut big = String::from("graph TD\nsubgraph left\n");
for i in 0..59 {
big.push_str(&format!("N{i} --> N{}\n", i + 1));
if i == 30 {
big.push_str("end\nsubgraph right\n");
}
}
big.push_str("end\n");
for k in 0..40 {
big.push_str(&format!("N{} --> N{}\n", k % 20, k % 20 + 37));
}
let t = rune::time::now();
assert!(scene(&big, &paint, None).is_some());
assert!(t.elapsed().as_secs_f32() < 5.0, "{:?}", t.elapsed());
let mut nested = String::from("graph TD\n");
for d in 0..8 {
nested.push_str(&format!("subgraph s{d}\nA{d} --> B{d} --> C{d}\n"));
}
nested.push_str(&"end\n".repeat(8));
nested.push_str("A0 --> C7\nC7 --> A0");
hostile(&nested, true);
}
#[test]
fn repeated_create_is_skipped_without_recursing() {
hostile(&format!("sequenceDiagram\n{}participant A\nA->>B: hi", "create ".repeat(100_000)), true);
hostile("sequenceDiagram\ncreate loop x\nA->>B: hi\nend", true);
hostile("sequenceDiagram\ncreate participant A\nA->>B: hi", true);
hostile("sequenceDiagram\nA->>B: hi\ncreate actor C as Carol\nB->>C: hello", true);
}
#[test]
fn dashes_stop_on_huge_and_non_finite_lengths() {
let ink = Color::BLACK;
for end in [1e9, f32::INFINITY, f32::NAN] {
let mut c = Canvas::default();
c.dashed(&[[0.0, 0.0], [end, 0.0]], 1.0, ink, 4.0, 3.0);
assert!(c.ops.len() <= 20_000);
}
}
pub(crate) fn assert_prefixes_never_panic(src: &str, dark: bool) {
let paint = DiagramStyle::neutral(dark);
for (i, _) in src.char_indices() {
let _ = scene(&src[..i], &paint, None);
}
assert!(scene(src, &paint, None).is_some());
}
/// Seven lanes with long names: wider than a 420-point column even at 60%.
const WIDE_SEQUENCE: &str = "sequenceDiagram\n autonumber\n participant B as Browser on a laptop\n participant E as Edge cache in front\n participant A as Auth service cluster\n participant P as Payments API server\n participant W as Billing worker pool\n participant S as Search index shard\n participant L as Long-running audit log\n B->>E: a request arrives at the edge\n E->>A: is this session token still valid?\n A-->>E: yes, here is the account scope\n E->>P: forward the call with its scope\n P->>W: enqueue the invoice with the scope\n W->>S: index the invoice\n S-->>W: ok\n W->>L: record the change\n W-->>P: done\n P-->>E: the response";
#[test]
fn min_scale_zero_fits_any_width() {
let narrow = DiagramStyle { max_width: 420.0, ..DiagramStyle::neutral(true) };
let room = super::canvas::room(&narrow);
let floored = scene(WIDE_SEQUENCE, &narrow, None).expect("draws");
assert!((floored.scale - 0.6).abs() < 1e-4 && floored.size[0] > room, "by default it stops at 60%: {} at {}", floored.size[0], floored.scale);
let fits = scene(WIDE_SEQUENCE, &narrow.min_scale(0.0), None).expect("draws");
assert!(fits.size[0] <= room + 2.01, "min_scale 0 fits the room {room}: {}", fits.size[0]);
assert!(fits.scale < 0.6 && (fits.full[1] * fits.scale - fits.size[1]).abs() < 0.01, "it shrinks evenly: {}", fits.scale);
let roomy = DiagramStyle { max_width: 4000.0, ..narrow }.min_scale(0.0);
assert_eq!(scene(WIDE_SEQUENCE, &roomy, None).expect("draws").scale, 1.0, "never grows past full size");
}
/// The bare drawing is the card's drawing without the card: the same size, plus its title.
#[test]
fn a_drawing_is_the_card_without_its_padding() {
let roomy = DiagramStyle { max_width: 4000.0, ..DiagramStyle::neutral(true) };
let full = scene(WIDE_SEQUENCE, &roomy, None).expect("draws");
let d = render_drawing(WIDE_SEQUENCE, &roomy, Hover::Off, roomy.text).expect("draws");
assert_eq!(d.size, full.size);
let titled = format!("---\ntitle: Checkout\n---\n{WIDE_SEQUENCE}");
let t = render_drawing(&titled, &roomy, Hover::Off, roomy.text).expect("draws");
assert!(t.size[1] > d.size[1] + 20.0 && t.size[0] >= d.size[0], "the title adds a line: {:?} {:?}", t.size, d.size);
}
/// Lines shrink with the drawing, as an SVG's do: a shrunk diagram's full-size pieces are the
/// same as an unshrunk one's, so magnifying it never shows fat lines.
#[test]
fn lines_shrink_with_the_drawing() {
let narrow = DiagramStyle { max_width: 420.0, ..DiagramStyle::neutral(true) }.min_scale(0.0);
let roomy = DiagramStyle { max_width: 4000.0, ..narrow };
let (small, full) = (scene(WIDE_SEQUENCE, &narrow, None).expect("draws"), scene(WIDE_SEQUENCE, &roomy, None).expect("draws"));
assert!(small.scale < 0.5, "shrinks: {}", small.scale);
for (a, b) in small.pieces.iter().zip(&full.pieces) {
assert_eq!(a.key, b.key);
let close = (a.size[0] - b.size[0]).abs() < 0.01 && (a.size[1] - b.size[1]).abs() < 0.01;
assert!(close, "{} is {:?} shrunk, {:?} full", a.key, a.size, b.size);
}
}