charcoal 0.1.1

Declarative, DataFrame-native chart library for Polars. No browser required.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
//! SVG canvas assembly and rendering pipeline.
//!
//! [`SvgCanvas`] is the top-level renderer: chart builders compute their data,
//! call into [`geometry`] for atomic SVG elements, [`axes`] for scale
//! computation and tick rendering, and then hand everything to
//! `SvgCanvas::render` to produce the final `<svg>` string.
//!
//! The optional [`raster`] submodule (enabled by the `static` feature) converts
//! the SVG to PNG via `resvg`. The [`html`] submodule wraps the SVG in a
//! minimal standalone HTML document.

#![allow(dead_code)]

pub(crate) mod geometry;
pub(crate) mod axes;
pub(crate) mod html;
#[cfg(feature = "static")]
pub(crate) mod raster;

use std::sync::atomic::{AtomicU64, Ordering};

use crate::theme::ThemeConfig;
use crate::render::geometry as geo;
use crate::render::axes::AxisOutput;

static CANVAS_COUNTER: AtomicU64 = AtomicU64::new(0);

pub(crate) const LEGEND_SWATCH_SIZE: f64 = 12.0;
pub(crate) const LEGEND_ROW_PADDING: f64 = 4.0;
pub(crate) const LEGEND_PLOT_GAP:    f64 = 8.0;
pub(crate) const LEGEND_RIGHT_PAD:   f64 = 8.0;

/// Computes the right margin in pixels needed to fit a legend without clipping.
///
/// Scales with `font_size_px` so larger themes get more space automatically.
/// Returns `30` when there is no legend (the original default).
pub(crate) fn legend_right_margin(
    legend:       &Option<Vec<(String, String)>>,
    font_size_px: u32,
) -> u32 {
    let entries = match legend {
        None => return 30,
        Some(v) if v.is_empty() => return 30,
        Some(v) => v,
    };
    let longest = entries.iter().map(|(l, _)| l.len()).max().unwrap_or(0);
    let text_px = longest as f64 * (font_size_px as f64 * 0.55);
    (LEGEND_PLOT_GAP + LEGEND_SWATCH_SIZE + LEGEND_ROW_PADDING + text_px + LEGEND_RIGHT_PAD)
        .ceil() as u32
}

pub(crate) fn unique_id() -> String {
    let n = CANVAS_COUNTER.fetch_add(1, Ordering::SeqCst);
    format!("cc_{:06x}", n)
}

#[derive(Debug, Clone)]
pub(crate) struct Margin {
    pub top: u32,
    pub right: u32,
    pub bottom: u32,
    pub left: u32,
}

impl Margin {

    pub(crate) fn new(top: u32, right: u32, bottom: u32, left: u32) -> Self {
        Self { top, right, bottom, left }
    }

    pub(crate) fn default_chart() -> Self {
        Self { top: 50, right: 30, bottom: 60, left: 70 }
    }
}

pub(crate) struct SvgCanvas {
    pub width: u32,
    pub height: u32,
    pub margin: Margin,
    pub theme: ThemeConfig,
    pub chart_id: String,
}

impl SvgCanvas {
    pub(crate) fn new(width: u32, height: u32, margin: Margin, theme: ThemeConfig) -> Self {
        Self {
            width,
            height,
            margin,
            theme,
            chart_id: unique_id(),
        }
    }

    pub(crate) fn plot_width(&self) -> f64 {
        (self.width as i64 - self.margin.left as i64 - self.margin.right as i64).max(0) as f64
    }

    pub(crate) fn plot_height(&self) -> f64 {
        (self.height as i64 - self.margin.top as i64 - self.margin.bottom as i64).max(0) as f64
    }

    pub(crate) fn plot_origin_x(&self) -> f64 {
        self.margin.left as f64
    }

    pub(crate) fn plot_origin_y(&self) -> f64 {
        self.margin.top as f64
    }

    #[allow(clippy::too_many_arguments)]
    pub(crate) fn render(
        &self,
        elements: Vec<String>,
        x_axis: AxisOutput,
        y_axis: AxisOutput,
        title: &str,
        x_label: &str,
        y_label: &str,
        legend: Option<Vec<(String, String)>>,
    ) -> String {
        let clip_id = format!("{}_clip", self.chart_id);
        let svg_id = &self.chart_id;

        let w = self.width;
        let h = self.height;
        let ox = self.plot_origin_x();
        let oy = self.plot_origin_y();
        let pw = self.plot_width();
        let ph = self.plot_height();

        let svg_open = format!(
            r#"<svg id="{svg_id}" xmlns="http://www.w3.org/2000/svg" width="{w}" height="{h}" viewBox="0 0 {w} {h}">"#,
        );
        let background = geo::rect(0.0, 0.0, w as f64, h as f64, self.theme.background, 0.0);
        let defs = format!(
            r#"<defs><clipPath id="{clip_id}"><rect x="{ox:.2}" y="{oy:.2}" width="{pw:.2}" height="{ph:.2}"/></clipPath></defs>"#,
        );
        let grids = format!("{}\n{}", x_axis.grid_lines, y_axis.grid_lines);
        let axes_svg = format!("{}\n{}", x_axis.axis_line, y_axis.axis_line);
        let data_group = geo::group(&elements, Some(&clip_id));
        let title_svg = if title.is_empty() {
            String::new()
        } else {
            geo::text(
                w as f64 / 2.0,
                self.margin.top as f64 * 0.6,
                title,
                "middle",
                self.theme.font_size_px + 4,
                self.theme.text_color,
                0.0,
            )
        };

        let x_label_svg = if x_label.is_empty() {
            String::new()
        } else {
            geo::text(
                ox + pw / 2.0,
                h as f64 - 6.0,
                x_label,
                "middle",
                self.theme.font_size_px,
                self.theme.text_color,
                0.0,
            )
        };

        let y_label_svg = if y_label.is_empty() {
            String::new()
        } else {
            let lx = self.margin.left as f64 * 0.35;
            let ly = oy + ph / 2.0;
            geo::text(lx, ly, y_label, "middle", self.theme.font_size_px, self.theme.text_color, -90.0)
        };

        let legend_svg = match legend {
            None => String::new(),
            Some(entries) => render_legend(&entries, ox + pw + LEGEND_PLOT_GAP, oy, &self.theme),
        };

        let parts = [
            svg_open.as_str(),
            &background,
            &defs,
            &grids,
            &axes_svg,
            &data_group,
            &title_svg,
            &x_label_svg,
            &y_label_svg,
            &legend_svg,
            "</svg>",
        ];

        parts.join("\n")
    }
}

fn render_legend(entries: &[(String, String)], x: f64, y_start: f64, theme: &ThemeConfig) -> String {
    let swatch_size = LEGEND_SWATCH_SIZE;
    let row_height  = swatch_size + LEGEND_ROW_PADDING;
    let text_offset = swatch_size + LEGEND_ROW_PADDING;

    let mut parts = Vec::new();
    for (i, (label, color)) in entries.iter().enumerate() {
        let y = y_start + i as f64 * row_height;
        parts.push(geo::rect(x, y, swatch_size, swatch_size, color, 2.0));
        parts.push(geo::text(
            x + text_offset,
            y + swatch_size * 0.8,
            label,
            "start",
            theme.font_size_px,
            theme.text_color,
            0.0,
        ));
    }
    parts.join("\n")
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::theme::{Theme, ThemeConfig};
    use crate::render::axes::AxisOutput;

    fn default_canvas() -> SvgCanvas {
        SvgCanvas::new(800, 600, Margin::default_chart(), ThemeConfig::from(&Theme::Default))
    }

    fn empty_axis() -> AxisOutput {
        AxisOutput {
            ticks: Vec::new(),
            axis_line: String::new(),
            grid_lines: String::new(),
        }
    }

    #[test]
    fn render_starts_with_svg_and_ends_with_close() {
        let canvas = default_canvas();
        let svg = canvas.render(vec![], empty_axis(), empty_axis(), "", "", "", None);
        assert!(svg.trim_start().starts_with("<svg"), "should start with <svg: {}", &svg[..50]);
        assert!(svg.trim_end().ends_with("</svg>"), "should end with </svg>");
    }

    #[test]
    fn render_contains_clip_path() {
        let canvas = default_canvas();
        let svg = canvas.render(vec![], empty_axis(), empty_axis(), "", "", "", None);
        assert!(svg.contains("<clipPath"), "missing <clipPath: found none");
    }

    #[test]
    fn render_includes_title_when_provided() {
        let canvas = default_canvas();
        let svg = canvas.render(vec![], empty_axis(), empty_axis(), "My Chart", "", "", None);
        assert!(svg.contains("My Chart"), "title not found in SVG");
    }

    #[test]
    fn render_omits_title_when_empty() {
        let canvas = default_canvas();
        let svg = canvas.render(vec![], empty_axis(), empty_axis(), "", "", "", None);
        assert!(!svg.contains("<text></text>"), "empty title text element present");
    }

    #[test]
    fn plot_width_subtracts_margins() {
        let canvas = SvgCanvas::new(
            800,
            600,
            Margin::new(50, 30, 60, 70),
            ThemeConfig::from(&Theme::Default),
        );
        assert!((canvas.plot_width() - (800.0 - 70.0 - 30.0)).abs() < 1e-9);
    }

    #[test]
    fn plot_height_subtracts_margins() {
        let canvas = SvgCanvas::new(
            800,
            600,
            Margin::new(50, 30, 60, 70),
            ThemeConfig::from(&Theme::Default),
        );
        assert!((canvas.plot_height() - (600.0 - 50.0 - 60.0)).abs() < 1e-9);
    }

    #[test]
    fn plot_origin_x_equals_left_margin() {
        let canvas = SvgCanvas::new(800, 600, Margin::new(50, 30, 60, 70), ThemeConfig::from(&Theme::Default));
        assert!((canvas.plot_origin_x() - 70.0).abs() < 1e-9);
    }

    #[test]
    fn plot_origin_y_equals_top_margin() {
        let canvas = SvgCanvas::new(800, 600, Margin::new(50, 30, 60, 70), ThemeConfig::from(&Theme::Default));
        assert!((canvas.plot_origin_y() - 50.0).abs() < 1e-9);
    }

    #[test]
    fn unique_id_returns_different_values() {
        let id1 = unique_id();
        let id2 = unique_id();
        let id3 = unique_id();
        assert_ne!(id1, id2);
        assert_ne!(id2, id3);
        assert_ne!(id1, id3);
    }

    #[test]
    fn unique_id_starts_with_cc_prefix() {
        let id = unique_id();
        assert!(id.starts_with("cc_"), "id should start with cc_: {id}");
    }

    #[test]
    fn two_canvases_have_different_chart_ids() {
        let c1 = default_canvas();
        let c2 = default_canvas();
        assert_ne!(c1.chart_id, c2.chart_id);
    }

    #[test]
    fn render_legend_entries_appear_in_output() {
        let canvas = default_canvas();
        let legend = vec![
            ("Setosa".to_string(), "#E69F00".to_string()),
            ("Versicolor".to_string(), "#56B4E9".to_string()),
        ];
        let svg = canvas.render(vec![], empty_axis(), empty_axis(), "", "", "", Some(legend));
        assert!(svg.contains("Setosa"), "legend label Setosa missing");
        assert!(svg.contains("Versicolor"), "legend label Versicolor missing");
        assert!(svg.contains("#E69F00"), "legend color missing");
    }


    #[test]
    fn full_pipeline_produces_valid_svg() {
        use crate::render::axes::{
            LinearScale, AxisOrientation, nice_ticks, tick_labels_numeric,
            build_tick_marks, compute_axis,
        };
        use crate::render::geometry::circle;

        let canvas = default_canvas();
        let theme = ThemeConfig::from(&Theme::Default);

        let ox = canvas.plot_origin_x();
        let oy = canvas.plot_origin_y();
        let pw = canvas.plot_width();
        let ph = canvas.plot_height();

        let x_scale = LinearScale::new(0.0, 100.0, ox, ox + pw);
        let x_vals = nice_ticks(0.0, 100.0, 6);
        let x_labels = tick_labels_numeric(&x_vals);
        let x_ticks = build_tick_marks(&x_vals, &x_labels, &x_scale);
        let x_axis = compute_axis(&x_scale, &x_ticks, AxisOrientation::Horizontal,
            ox, oy, pw, ph, &theme);

        let y_scale = LinearScale::new(0.0, 50.0, oy + ph, oy);
        let y_vals = nice_ticks(0.0, 50.0, 5);
        let y_labels = tick_labels_numeric(&y_vals);
        let y_ticks = build_tick_marks(&y_vals, &y_labels, &y_scale);
        let y_axis = compute_axis(&y_scale, &y_ticks, AxisOrientation::Vertical,
            ox, oy, pw, ph, &theme);

        let elements: Vec<String> = [(25.0, 30.0), (50.0, 45.0), (75.0, 20.0)]
            .iter()
            .map(|&(xd, yd)| circle(x_scale.map(xd), y_scale.map(yd), 5.0, "#4e79a7", 0.8))
            .collect();

        let svg = canvas.render(
            elements, x_axis, y_axis,
            "Integration Test", "X Axis", "Y Axis",
            Some(vec![("Series A".to_string(), "#4e79a7".to_string())]),
        );

        assert!(svg.starts_with("<svg"),        "must start with <svg");
        assert!(svg.ends_with("</svg>"),        "must end with </svg>");
        assert!(svg.contains("<clipPath"),       "must contain <clipPath");
        assert!(svg.contains("Integration Test"), "title must appear");
        assert!(svg.contains("X Axis"),         "x-label must appear");
        assert!(svg.contains("Y Axis"),         "y-label must appear");
        assert!(svg.contains("Series A"),       "legend must appear");
        assert!(svg.contains("circle"),         "data points must appear");
    }

    #[test]
    fn html_wrapper_around_rendered_svg() {
        use crate::render::html::to_inline_html;

        let canvas = default_canvas();
        let svg = canvas.render(vec![], empty_axis(), empty_axis(), "HTML Test", "", "", None);
        let html = to_inline_html(&svg, "HTML Test");

        assert!(html.starts_with("<!DOCTYPE html>"));
        assert!(html.contains("<title>HTML Test</title>"));
        assert!(html.contains("<svg ") || html.contains("<svg\n"));
        assert!(html.contains("</svg>"));
        let body_pos = html.rfind("</body>").expect("</body> not found");
        let html_pos = html.rfind("</html>").expect("</html> not found");
        assert!(body_pos < html_pos, "</body> must appear before </html>");
    }

    #[test]
    fn inverted_y_scale_maps_correctly() {
        use crate::render::axes::LinearScale;
        let scale = LinearScale::new(0.0, 100.0, 500.0, 50.0);
        assert!((scale.map(0.0)   - 500.0).abs() < 1e-9, "min should map to pixel bottom");
        assert!((scale.map(100.0) -  50.0).abs() < 1e-9, "max should map to pixel top");
        assert!((scale.map(50.0)  - 275.0).abs() < 1e-9, "midpoint should be mid-pixel");
    }

    #[test]
    fn write_html_for_browser_check() {
        use crate::render::axes::{
            LinearScale, AxisOrientation, nice_ticks, tick_labels_numeric,
            build_tick_marks, compute_axis,
        };
        use crate::render::geometry::circle;
        use crate::render::html::to_inline_html;

        let canvas = default_canvas();
        let theme = ThemeConfig::from(&Theme::Default);
        let ox = canvas.plot_origin_x();
        let oy = canvas.plot_origin_y();
        let pw = canvas.plot_width();
        let ph = canvas.plot_height();

        let x_scale = LinearScale::new(0.0, 10.0, ox, ox + pw);
        let x_vals  = nice_ticks(0.0, 10.0, 6);
        let x_ticks = build_tick_marks(&x_vals, &tick_labels_numeric(&x_vals), &x_scale);
        let x_axis  = compute_axis(&x_scale, &x_ticks, AxisOrientation::Horizontal, ox, oy, pw, ph, &theme);

        let y_scale = LinearScale::new(0.0, 10.0, oy + ph, oy);
        let y_vals  = nice_ticks(0.0, 10.0, 6);
        let y_ticks = build_tick_marks(&y_vals, &tick_labels_numeric(&y_vals), &y_scale);
        let y_axis  = compute_axis(&y_scale, &y_ticks, AxisOrientation::Vertical, ox, oy, pw, ph, &theme);

        let points = [(2.0,3.0),(4.0,7.0),(6.0,5.0),(8.0,9.0),(9.0,2.0)];
        let elements: Vec<String> = points.iter()
            .map(|&(xd,yd)| circle(x_scale.map(xd), y_scale.map(yd), 6.0, "#4e79a7", 0.8))
            .collect();

        let svg  = canvas.render(elements, x_axis, y_axis, "Phase 1 Render Test", "X", "Y",
            Some(vec![("Series A".to_string(), "#4e79a7".to_string())]));
        let html = to_inline_html(&svg, "charcoal render test");

        std::fs::create_dir_all("output").unwrap();
        std::fs::write("output/render_test.html", &html).unwrap();
        println!("\nWritten to output/render_test.html — open in your browser.");
    }
}