chartlet 0.23.0

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

use crate::{
    error::ChartWarning,
    layout::{fit_text, two_lines},
    metrics::TextMetrics,
    scene::{Circle, Element, Polyline, Rect, Text, TextAnchor},
    spec::ChartSpec,
};

/// Length and half width of an arrowhead.
pub(crate) const HEAD: f64 = 8.0;
const HEAD_HALF: f64 = 3.5;
/// Radius of the corners where an edge changes course.
const CORNER: f64 = 6.0;
/// How far a step's shadow falls below it.
const SHADOW: f64 = 2.5;
/// The text of a chip, the distance between its lines, and the space around it.
pub(crate) const CHIP_SIZE: f64 = 12.0;
pub(crate) const CHIP_LINE: f64 = 15.0;
const CHIP_PAD_X: f64 = 5.0;
const CHIP_PAD_Y: f64 = 3.0;
/// How far a chip reaches beyond its text on each side, with a little air.
pub(crate) const CHIP_REACH: f64 = CHIP_PAD_X + 2.0;
/// Radius of a number badge.
pub(crate) const BADGE: f64 = 8.0;

/// A polyline with nothing but its points, its class and an optional tooltip.
pub(crate) fn polyline(
    points: Vec<(f64, f64)>,
    class: &'static str,
    tooltip: Option<String>,
) -> Polyline {
    Polyline {
        points,
        class,
        series_index: None,
        style_index: None,
        tooltip,
    }
}

/// The arrowhead with its tip at `tip`, pointing along the unit vector `direction`: a closed
/// triangle when `filled`, two strokes otherwise.
pub(crate) fn arrowhead(
    tip: (f64, f64),
    direction: (f64, f64),
    filled: bool,
    class: &'static str,
) -> Polyline {
    let base = (tip.0 - direction.0 * HEAD, tip.1 - direction.1 * HEAD);
    let side = (-direction.1 * HEAD_HALF, direction.0 * HEAD_HALF);
    let one = (base.0 + side.0, base.1 + side.1);
    let other = (base.0 - side.0, base.1 - side.1);
    let points = if filled {
        vec![one, tip, other, one]
    } else {
        vec![one, tip, other]
    };
    polyline(points, class, None)
}

/// `points` with every corner rounded: each turn becomes a short curve, as far as the segments on
/// either side of it leave room.
pub(crate) fn rounded(points: &[(f64, f64)]) -> Vec<(f64, f64)> {
    if points.len() < 3 {
        return points.to_vec();
    }
    let mut output = vec![points[0]];
    for corner in points.windows(3) {
        let (before, at, after) = (corner[0], corner[1], corner[2]);
        let into = (at.0 - before.0).hypot(at.1 - before.1);
        let out = (after.0 - at.0).hypot(after.1 - at.1);
        let radius = CORNER.min(into / 2.0).min(out / 2.0);
        if radius < 0.5 {
            output.push(at);
            continue;
        }
        let start = (
            at.0 - (at.0 - before.0) / into * radius,
            at.1 - (at.1 - before.1) / into * radius,
        );
        let end = (
            at.0 + (after.0 - at.0) / out * radius,
            at.1 + (after.1 - at.1) / out * radius,
        );
        output.push(start);
        // Points on the quadratic curve from `start` to `end` that `at` controls.
        for t in [0.25, 0.5, 0.75] {
            let u = 1.0 - t;
            output.push((
                u * u * start.0 + 2.0 * u * t * at.0 + t * t * end.0,
                u * u * start.1 + 2.0 * u * t * at.1 + t * t * end.1,
            ));
        }
        output.push(end);
    }
    output.push(points[points.len() - 1]);
    output
}

/// A shape's shadow: the same shape, a little lower, in the shadow color.
fn shadow(element: &Element) -> Option<Element> {
    match element {
        Element::Rect(rect) => Some(Element::Rect(Rect {
            y: rect.y + SHADOW,
            class: "chartlet-diagram-shadow",
            tooltip: None,
            ..rect.clone()
        })),
        Element::Polyline(shape) => Some(Element::Polyline(polyline(
            shape.points.iter().map(|(x, y)| (*x, y + SHADOW)).collect(),
            "chartlet-diagram-shadow",
            None,
        ))),
        _ => None,
    }
}

/// Pushes `shape` with its shadow beneath it.
pub(crate) fn with_shadow(shape: Element, elements: &mut Vec<Element>) {
    if let Some(shadow) = shadow(&shape) {
        elements.push(shadow);
    }
    elements.push(shape);
}

/// The plate of a chip with `lines` whose first baseline is at `y`: left, top, width, height.
pub(crate) fn chip_box(
    lines: &[String],
    (x, y): (f64, f64),
    anchor: TextAnchor,
    metrics: &impl TextMetrics,
) -> (f64, f64, f64, f64) {
    let width = lines
        .iter()
        .map(|line| metrics.width(line, CHIP_SIZE))
        .fold(0.0, f64::max);
    let left = match anchor {
        TextAnchor::Start => x,
        TextAnchor::Middle => x - width / 2.0,
        TextAnchor::End => x - width,
    };
    let rows = crate::layout::count(lines.len());
    (
        left - CHIP_PAD_X,
        y - 11.0 - CHIP_PAD_Y,
        width + 2.0 * CHIP_PAD_X,
        15.0 + CHIP_LINE * (rows - 1.0) + 2.0 * CHIP_PAD_Y,
    )
}

/// A label on a chip: its lines on a small rounded plate in the background color, so that it
/// reads clearly where it crosses or sits beside lines. `y` is the baseline of the first line.
pub(crate) fn chip(
    lines: &[String],
    (x, y): (f64, f64),
    anchor: TextAnchor,
    metrics: &impl TextMetrics,
    elements: &mut Vec<Element>,
) {
    let (left, top, width, height) = chip_box(lines, (x, y), anchor, metrics);
    elements.push(Element::Rect(Rect {
        x: left,
        y: top,
        width,
        height,
        class: "chartlet-diagram-chip",
        series_index: None,
        style_index: None,
        tooltip: None,
    }));
    for (index, line) in lines.iter().enumerate() {
        elements.push(Element::Text(Text {
            x,
            y: y + CHIP_LINE * crate::layout::count(index),
            class: "chartlet-diagram-chip-text",
            anchor,
            content: line.clone(),
        }));
    }
}

/// The size of the technology of an edge label, set in monospace after the label.
pub(crate) const TECH_SIZE: f64 = 11.0;

/// The width of a chip line whose tail is the technology `tech`: the label before it, then the
/// technology in its own size.
pub(crate) fn run_width(line: &str, tech: Option<&str>, metrics: &impl TextMetrics) -> f64 {
    match tech.filter(|tech| !tech.is_empty() && line.ends_with(*tech)) {
        Some(tech) => {
            metrics.width(&line[..line.len() - tech.len()], CHIP_SIZE)
                + metrics.width(tech, TECH_SIZE)
        }
        None => metrics.width(line, CHIP_SIZE),
    }
}

/// [`chip_box`] for lines that may end in the technology `tech`.
pub(crate) fn chip_box_tech(
    lines: &[String],
    tech: Option<&str>,
    at: (f64, f64),
    anchor: TextAnchor,
    metrics: &impl TextMetrics,
) -> (f64, f64, f64, f64) {
    if tech.is_none() {
        return chip_box(lines, at, anchor, metrics);
    }
    let width = lines
        .iter()
        .map(|line| run_width(line, tech, metrics))
        .fold(0.0, f64::max);
    let left = match anchor {
        TextAnchor::Start => at.0,
        TextAnchor::Middle => at.0 - width / 2.0,
        TextAnchor::End => at.0 - width,
    };
    let rows = crate::layout::count(lines.len());
    (
        left - CHIP_PAD_X,
        at.1 - 11.0 - CHIP_PAD_Y,
        width + 2.0 * CHIP_PAD_X,
        15.0 + CHIP_LINE * (rows - 1.0) + 2.0 * CHIP_PAD_Y,
    )
}

/// [`chip`] for lines that may end in the technology `tech`: the label in the sans font, the
/// technology after it in monospace.
pub(crate) fn chip_tech(
    lines: &[String],
    tech: Option<&str>,
    at: (f64, f64),
    anchor: TextAnchor,
    metrics: &impl TextMetrics,
    elements: &mut Vec<Element>,
) {
    if tech.is_none() {
        chip(lines, at, anchor, metrics, elements);
        return;
    }
    let (left, top, width, height) = chip_box_tech(lines, tech, at, anchor, metrics);
    elements.push(Element::Rect(Rect {
        x: left,
        y: top,
        width,
        height,
        class: "chartlet-diagram-chip",
        series_index: None,
        style_index: None,
        tooltip: None,
    }));
    for (index, line) in lines.iter().enumerate() {
        let y = at.1 + CHIP_LINE * crate::layout::count(index);
        let own = run_width(line, tech, metrics);
        let start = match anchor {
            TextAnchor::Start => at.0,
            TextAnchor::Middle => at.0 - own / 2.0,
            TextAnchor::End => at.0 - own,
        };
        match tech.filter(|tech| !tech.is_empty() && line.ends_with(*tech)) {
            Some(tech) => {
                let label = &line[..line.len() - tech.len()];
                if !label.is_empty() {
                    elements.push(Element::Text(Text {
                        x: start,
                        y,
                        class: "chartlet-diagram-chip-text",
                        anchor: TextAnchor::Start,
                        content: label.to_owned(),
                    }));
                }
                elements.push(Element::Text(Text {
                    x: start + metrics.width(label, CHIP_SIZE),
                    y,
                    class: "chartlet-diagram-tech",
                    anchor: TextAnchor::Start,
                    content: tech.to_owned(),
                }));
            }
            None => elements.push(Element::Text(Text {
                x: at.0,
                y,
                class: "chartlet-diagram-chip-text",
                anchor,
                content: line.clone(),
            })),
        }
    }
}

/// A round badge with a number, centred on `center`.
pub(crate) fn badge(number: usize, center: (f64, f64), elements: &mut Vec<Element>) {
    elements.push(Element::Circle(Circle {
        cx: center.0,
        cy: center.1,
        radius: BADGE,
        class: "chartlet-diagram-badge",
        series_index: None,
        style_index: None,
        tooltip: None,
    }));
    elements.push(Element::Text(Text {
        x: center.0,
        y: center.1 + 3.5,
        class: "chartlet-diagram-badge-text",
        anchor: TextAnchor::Middle,
        content: number.to_string(),
    }));
}

/// A data store: a cylinder in the box at `x`, `y`, whose top shows its front rim. `classes`
/// style the body and the rim.
pub(crate) fn cylinder(
    (x, y, width, height): (f64, f64, f64, f64),
    (body, rim): (&'static str, &'static str),
    tooltip: Option<String>,
    elements: &mut Vec<Element>,
) {
    const RIM: f64 = 5.0;
    const STEPS: u32 = 12;
    let center = x + width / 2.0;
    let arc = |middle: f64, sign: f64, forward: bool| -> Vec<(f64, f64)> {
        (0..=STEPS)
            .map(|step| {
                let angle = std::f64::consts::PI * f64::from(step) / f64::from(STEPS);
                let cos = if forward { -angle.cos() } else { angle.cos() };
                (
                    center + width / 2.0 * cos,
                    middle + sign * RIM * angle.sin(),
                )
            })
            .collect()
    };
    let mut outline = vec![(x, y + RIM)];
    outline.extend(arc(y + height - RIM, 1.0, true));
    outline.extend(arc(y + RIM, -1.0, false));
    outline.push((x, y + RIM));
    with_shadow(
        Element::Polyline(polyline(outline, body, tooltip)),
        elements,
    );
    elements.push(Element::Polyline(polyline(
        arc(y + RIM, 1.0, true),
        rim,
        None,
    )));
}

/// A label on one or two lines that fit `max_width`; a longer second line, or a first word wider
/// than that, is shortened.
pub(crate) fn wrap(
    label: &str,
    max_width: f64,
    size: f64,
    metrics: &impl TextMetrics,
    warnings: &mut Vec<ChartWarning>,
    path: &str,
) -> Vec<String> {
    match two_lines(label, max_width, size, metrics) {
        Some((first, rest)) => vec![
            first.to_owned(),
            fit_text(rest, max_width, size, metrics, warnings, path),
        ],
        None => vec![fit_text(label, max_width, size, metrics, warnings, path)],
    }
}

/// Which orientation `auto` takes, from the size each needs: portrait where it fits the canvas,
/// landscape where only that fits, and otherwise the one that has to grow the canvas less.
pub(crate) fn prefers_landscape(
    spec: &ChartSpec,
    portrait: (f64, f64),
    landscape: (f64, f64),
) -> bool {
    let (width, height) = (f64::from(spec.width), f64::from(spec.height));
    let growth = |(needed_width, needed_height): (f64, f64)| {
        (needed_width / width).max(needed_height / height)
    };
    growth(portrait) > 1.0 && growth(landscape) < growth(portrait)
}

/// Warns that the diagram did not fit the canvas and was drawn larger, naming the size it needs.
pub(crate) fn warn_growth(
    spec: &ChartSpec,
    width: f64,
    height: f64,
    warnings: &mut Vec<ChartWarning>,
) {
    warn_growth_advising(spec, (width, height), "try the other orientation", warnings);
}

/// [`warn_growth`] with the last piece of advice of its own, for a diagram without orientation.
pub(crate) fn warn_growth_advising(
    spec: &ChartSpec,
    (width, height): (f64, f64),
    advice: &str,
    warnings: &mut Vec<ChartWarning>,
) {
    for (path, needed, given) in [
        ("/width", pixels(width), spec.width),
        ("/height", pixels(height), spec.height),
    ] {
        if needed > given {
            warnings.push(ChartWarning::new(
                "canvas_too_small",
                path,
                format!(
                    "the diagram needs {needed} pixels here and was drawn that large; raise {} to {needed}, shorten labels, or {advice}",
                    &path[1..]
                ),
            ));
        }
    }
}

/// Whole pixels, rounded up so that nothing is cut off. A layout that fills the canvas exactly
/// may come out a hair above it in floating point; that is no reason to grow it by a pixel.
pub(crate) fn pixels(value: f64) -> u32 {
    // Canvas sizes stay far below the range of u32 and are never negative.
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
    let pixels = (value - 1e-6).ceil() as u32;
    pixels
}