ggplot_rs/aes/mod.rs
1pub mod expr;
2pub mod mapping;
3
4pub use mapping::{apply_after_stat, resolve_mappings};
5
6/// All supported aesthetic channels.
7#[derive(Clone, Debug, PartialEq, Eq, Hash)]
8#[non_exhaustive]
9pub enum Aesthetic {
10 X,
11 Y,
12 Color,
13 Fill,
14 Size,
15 Shape,
16 Alpha,
17 Linetype,
18 Group,
19 Ymin,
20 Ymax,
21 Xmin,
22 Xmax,
23 Label,
24 Weight,
25 Xend,
26 Yend,
27 Angle,
28 Radius,
29 /// Stroke width for segment/curve/path/line (R's `linewidth`).
30 Linewidth,
31 /// Per-row font face for `geom_text`/`geom_label` (#228, R's
32 /// `fontface`): `"plain"`/`"normal"`, `"bold"`, `"italic"`/`"oblique"`
33 /// (case-insensitive), the same strings `theme()`'s `face` accepts. An
34 /// unparseable value falls back to the geom's own fixed `fontface`
35 /// (`GeomText`/`GeomLabel`'s `.with_fontface(..)`, default `Plain`) —
36 /// no build warning, since the value is only known per row. Carries its
37 /// value straight through to [`crate::render::backend::TextStyle::face`]
38 /// — no scale, no legend (like `Tooltip`/`Class`).
39 Fontface,
40 /// A custom `<title>` hover tooltip, replacing the geom's own. Routed
41 /// through [`crate::aes::TOOLTIP_INTERNAL_NAME`] in `resolve_mappings`,
42 /// the same way `DataAttr` is, so an unrelated raw column literally
43 /// named `"tooltip"` can never be mistaken for a mapped one.
44 Tooltip,
45 /// A custom `data-<name>` attribute on the mark. The `String` is the
46 /// full attribute name (`"data-<name>"`). [`Aes::data_attr`] validates
47 /// `name` against `[a-z0-9][a-z0-9-]*` (excluding reserved names) before
48 /// constructing this; a `DataAttr` built directly — bypassing that
49 /// builder — is re-validated in `resolve_mappings`
50 /// (`aes::validated_data_attr_internal_name`), the single authoritative
51 /// gate regardless of how the mapping was created.
52 DataAttr(String),
53 /// CSS class tokens on the mark (#221, [`Aes::class`]): a
54 /// space-separated list, each token matching `[A-Za-z][A-Za-z0-9_-]*`
55 /// (invalid tokens are dropped with a build warning). Routed through
56 /// [`CLASS_INTERNAL_NAME`] the same way `Tooltip` is. No scale, no
57 /// legend.
58 Class,
59 /// A caller-named group wrapper (#221, [`Aes::group_wrap`]): every mark
60 /// whose row has the same value — across all layers that map the same
61 /// name — is drawn inside one `<g data-<name>="<value>">`. The `String`
62 /// is the full attribute name (`"data-<name>"`), validated like
63 /// [`DataAttr`](Self::DataAttr)'s. No scale, no legend.
64 GroupWrap(String),
65 /// Financial OHLC aesthetics (`geom_candlestick` / `geom_ohlc`); they
66 /// share the y position scale.
67 Open,
68 High,
69 Low,
70 Close,
71 /// Reference-line aesthetics (`geom_hline` / `geom_vline` /
72 /// `geom_abline`). `xintercept`/`yintercept` share (and train) the x / y
73 /// position scale, as in ggplot2; `slope`/`intercept` get no scale.
74 Xintercept,
75 Yintercept,
76 Slope,
77 Intercept,
78 /// Boxplot `stat="identity"` aesthetics (B3-5; ggplot2 extension, D4):
79 /// the box's lower/middle/upper hinges. Live on the y scale (D-style,
80 /// like `ymin`/`ymax`) — [`crate::scale::ScaleSet::ensure_scale`] gives
81 /// them no scale of their own.
82 Lower,
83 Middle,
84 Upper,
85 /// A comma-separated list of outlier values, optionally bracketed
86 /// (`"7, 9"` or `"[7, 9]"`) — ggplot2 extension, D4. Unparsable parts
87 /// are skipped with one warning. Lives on the y scale, like `Lower`/
88 /// `Middle`/`Upper`.
89 Outliers,
90 /// Edge-list aesthetics for flow / network charts (`geom_sankey`): the
91 /// source and target node of each link. Node names, not positions — no
92 /// scale, no legend.
93 From,
94 To,
95 /// Hierarchy parent of a row (`geom_treemap`): rows sharing a subgroup
96 /// are tiled together inside one group rectangle. A label, not a
97 /// position — no scale, no legend.
98 Subgroup,
99 /// Set combination of a row (`geom_venn`): one set name (`"A"`) or
100 /// several joined by `&` (`"A&B"`). A label — no scale, no legend.
101 Sets,
102}
103
104impl Aesthetic {
105 /// The canonical column name used in the working DataFrame after aes evaluation.
106 pub fn col_name(&self) -> &str {
107 match self {
108 Aesthetic::X => "x",
109 Aesthetic::Y => "y",
110 Aesthetic::Color => "color",
111 Aesthetic::Fill => "fill",
112 Aesthetic::Size => "size",
113 Aesthetic::Shape => "shape",
114 Aesthetic::Alpha => "alpha",
115 Aesthetic::Linetype => "linetype",
116 Aesthetic::Group => "group",
117 Aesthetic::Ymin => "ymin",
118 Aesthetic::Ymax => "ymax",
119 Aesthetic::Xmin => "xmin",
120 Aesthetic::Xmax => "xmax",
121 Aesthetic::Label => "label",
122 Aesthetic::Weight => "weight",
123 Aesthetic::Xend => "xend",
124 Aesthetic::Yend => "yend",
125 Aesthetic::Angle => "angle",
126 Aesthetic::Radius => "radius",
127 Aesthetic::Linewidth => "linewidth",
128 Aesthetic::Fontface => "fontface",
129 Aesthetic::Tooltip => "tooltip",
130 Aesthetic::DataAttr(name) => name,
131 Aesthetic::Class => "class",
132 Aesthetic::GroupWrap(name) => name,
133 Aesthetic::Open => "open",
134 Aesthetic::High => "high",
135 Aesthetic::Low => "low",
136 Aesthetic::Close => "close",
137 Aesthetic::Xintercept => "xintercept",
138 Aesthetic::Yintercept => "yintercept",
139 Aesthetic::Slope => "slope",
140 Aesthetic::Intercept => "intercept",
141 Aesthetic::Lower => "lower",
142 Aesthetic::Middle => "middle",
143 Aesthetic::Upper => "upper",
144 Aesthetic::Outliers => "outliers",
145 Aesthetic::From => "from",
146 Aesthetic::To => "to",
147 Aesthetic::Subgroup => "subgroup",
148 Aesthetic::Sets => "sets",
149 }
150 }
151}
152
153/// When an aesthetic mapping should be resolved.
154#[derive(Clone, Debug, PartialEq)]
155pub enum MappingStage {
156 /// Resolve before stat computation (default — maps from raw data columns).
157 BeforeStat,
158 /// Resolve after stat computation (maps from stat-computed columns like `density`, `count`).
159 AfterStat,
160}
161
162/// Maps a source column to an aesthetic channel.
163#[derive(Clone, Debug)]
164pub struct AesMapping {
165 pub column: String,
166 pub aesthetic: Aesthetic,
167 pub stage: MappingStage,
168}
169
170/// A post-scale aesthetic derivation (R's `after_scale`): the `target` color
171/// aesthetic is set to the `source` aesthetic's *mapped* color, adjusted in
172/// lightness (`+` toward white, `-` toward black, in `-1.0..=1.0`).
173#[derive(Clone, Debug)]
174pub struct AfterScaleSpec {
175 pub target: Aesthetic,
176 pub source: Aesthetic,
177 pub lightness: f64,
178}
179
180/// Builder for aesthetic mappings.
181#[derive(Clone, Debug, Default)]
182pub struct Aes {
183 pub mappings: Vec<AesMapping>,
184 /// Post-scale color derivations (`after_scale`).
185 pub after_scale: Vec<AfterScaleSpec>,
186 /// Non-fatal build warnings (e.g. an invalid [`data_attr`](Self::data_attr)
187 /// name), merged into [`GGPlot`](crate::plot::GGPlot)'s warnings by
188 /// `aes()`/`layer_aes()`.
189 pub(crate) warnings: Vec<String>,
190}
191
192impl Aes {
193 pub fn new() -> Self {
194 Self::default()
195 }
196
197 fn push(mut self, col: &str, aesthetic: Aesthetic) -> Self {
198 self.mappings.push(AesMapping {
199 column: col.to_string(),
200 aesthetic,
201 stage: MappingStage::BeforeStat,
202 });
203 self
204 }
205
206 fn push_after_stat(mut self, col: &str, aesthetic: Aesthetic) -> Self {
207 self.mappings.push(AesMapping {
208 column: col.to_string(),
209 aesthetic,
210 stage: MappingStage::AfterStat,
211 });
212 self
213 }
214
215 // ─── after_scale() — post-scale color derivation ────────────
216
217 /// Set `fill` to the mapped `color` with adjusted lightness (R's
218 /// `aes(fill = after_scale(...))`). `lightness` in `-1.0..=1.0`: positive
219 /// lightens toward white, negative darkens toward black.
220 pub fn after_scale_fill_from_color(mut self, lightness: f64) -> Self {
221 self.after_scale.push(AfterScaleSpec {
222 target: Aesthetic::Fill,
223 source: Aesthetic::Color,
224 lightness,
225 });
226 self
227 }
228
229 /// Set `color` to the mapped `fill` with adjusted lightness — useful for a
230 /// darker border around a filled shape (`color = after_scale(darken(fill))`).
231 pub fn after_scale_color_from_fill(mut self, lightness: f64) -> Self {
232 self.after_scale.push(AfterScaleSpec {
233 target: Aesthetic::Color,
234 source: Aesthetic::Fill,
235 lightness,
236 });
237 self
238 }
239
240 /// `stage(start, after_stat)`: map `aesthetic` from `start` before the stat
241 /// and re-map it from `after_stat` afterwards (R's `stage()`).
242 pub fn stage(mut self, aesthetic: Aesthetic, start: &str, after_stat: &str) -> Self {
243 self.mappings.push(AesMapping {
244 column: start.to_string(),
245 aesthetic: aesthetic.clone(),
246 stage: MappingStage::BeforeStat,
247 });
248 self.mappings.push(AesMapping {
249 column: after_stat.to_string(),
250 aesthetic,
251 stage: MappingStage::AfterStat,
252 });
253 self
254 }
255
256 pub fn x(self, col: &str) -> Self {
257 self.push(col, Aesthetic::X)
258 }
259 pub fn y(self, col: &str) -> Self {
260 self.push(col, Aesthetic::Y)
261 }
262 pub fn color(self, col: &str) -> Self {
263 self.push(col, Aesthetic::Color)
264 }
265 pub fn fill(self, col: &str) -> Self {
266 self.push(col, Aesthetic::Fill)
267 }
268 pub fn size(self, col: &str) -> Self {
269 self.push(col, Aesthetic::Size)
270 }
271 pub fn shape(self, col: &str) -> Self {
272 self.push(col, Aesthetic::Shape)
273 }
274 pub fn alpha(self, col: &str) -> Self {
275 self.push(col, Aesthetic::Alpha)
276 }
277 pub fn group(self, col: &str) -> Self {
278 self.push(col, Aesthetic::Group)
279 }
280 pub fn ymin(self, col: &str) -> Self {
281 self.push(col, Aesthetic::Ymin)
282 }
283 pub fn ymax(self, col: &str) -> Self {
284 self.push(col, Aesthetic::Ymax)
285 }
286 pub fn label(self, col: &str) -> Self {
287 self.push(col, Aesthetic::Label)
288 }
289 pub fn weight(self, col: &str) -> Self {
290 self.push(col, Aesthetic::Weight)
291 }
292 pub fn xend(self, col: &str) -> Self {
293 self.push(col, Aesthetic::Xend)
294 }
295 pub fn yend(self, col: &str) -> Self {
296 self.push(col, Aesthetic::Yend)
297 }
298 pub fn xmin(self, col: &str) -> Self {
299 self.push(col, Aesthetic::Xmin)
300 }
301 pub fn xmax(self, col: &str) -> Self {
302 self.push(col, Aesthetic::Xmax)
303 }
304 pub fn angle(self, col: &str) -> Self {
305 self.push(col, Aesthetic::Angle)
306 }
307 pub fn radius(self, col: &str) -> Self {
308 self.push(col, Aesthetic::Radius)
309 }
310 pub fn linetype(self, col: &str) -> Self {
311 self.push(col, Aesthetic::Linetype)
312 }
313 /// Stroke width for segment/curve/path/line (R's `linewidth`).
314 pub fn linewidth(self, col: &str) -> Self {
315 self.push(col, Aesthetic::Linewidth)
316 }
317 /// Boxplot `stat="identity"` lower hinge (B3-5).
318 pub fn lower(self, col: &str) -> Self {
319 self.push(col, Aesthetic::Lower)
320 }
321 /// Boxplot `stat="identity"` middle (median) line (B3-5).
322 pub fn middle(self, col: &str) -> Self {
323 self.push(col, Aesthetic::Middle)
324 }
325 /// Boxplot `stat="identity"` upper hinge (B3-5).
326 pub fn upper(self, col: &str) -> Self {
327 self.push(col, Aesthetic::Upper)
328 }
329 /// Boxplot `stat="identity"` outlier values, as a comma list with
330 /// optional brackets (`"7, 9"` or `"[7, 9]"`) (B3-5).
331 pub fn outliers(self, col: &str) -> Self {
332 self.push(col, Aesthetic::Outliers)
333 }
334
335 /// A custom `<title>` hover tooltip from `col`, replacing the geom's
336 /// own. `ensure_scale` skips it (no scale, no legend): computing stats
337 /// drop the column (identity-stat layers keep it), as `linetype`/`alpha`
338 /// do.
339 pub fn tooltip(self, col: &str) -> Self {
340 self.push(col, Aesthetic::Tooltip)
341 }
342
343 /// Per-row font face for `geom_text`/`geom_label` from `col` (#228, R's
344 /// `aes(fontface = ...)`): each row's value is parsed the same way
345 /// `theme()`'s `face` is (`"plain"`/`"normal"`, `"bold"`,
346 /// `"italic"`/`"oblique"`, case-insensitive); an unparseable or `NA`
347 /// value falls back to the geom's own fixed `.with_fontface(..)`. No
348 /// scale, no legend (like [`tooltip`](Self::tooltip)).
349 pub fn fontface(self, col: &str) -> Self {
350 self.push(col, Aesthetic::Fontface)
351 }
352
353 /// A custom `data-<name>` attribute on the mark, from `col`. `name` must
354 /// match `[a-z0-9][a-z0-9-]*` and not be a name ggplot-rs itself writes
355 /// via another mechanism (currently just `"part"` — see
356 /// `DrawBackend::set_mark_part`); an invalid or reserved name is skipped
357 /// with a build warning (surfaced via
358 /// [`GGPlot::aes`](crate::plot::GGPlot::aes) / `layer_aes`). A user attr
359 /// replaces a built-in of the same name (`data-x`, `data-series`,
360 /// `data-value`) — never duplicated.
361 pub fn data_attr(mut self, name: &str, col: &str) -> Self {
362 if !is_valid_data_attr_name(name) {
363 let reason = if RESERVED_DATA_ATTR_NAMES.contains(&name) {
364 "reserved (written by ggplot-rs itself)"
365 } else {
366 "invalid (must match [a-z0-9][a-z0-9-]*)"
367 };
368 self.warnings
369 .push(format!("aes: data_attr name {name:?} is {reason}; skipped"));
370 return self;
371 }
372 self.push(col, Aesthetic::DataAttr(format!("data-{name}")))
373 }
374
375 /// CSS class tokens on each mark, from `col` (#221): the row's value is
376 /// split on whitespace and every token must match
377 /// `[A-Za-z][A-Za-z0-9_-]*`; an invalid token is dropped (with one build
378 /// warning per layer), the rest are kept. The tokens are appended to the
379 /// mark's own `class="gg-mark gg-<kind>"` — there is never a second
380 /// `class` attribute, and never an inline `style` (so a strict CSP with
381 /// no `unsafe-inline` still holds: style the classes from an external
382 /// stylesheet). Read by every geom that reads [`data_attr`](Self::data_attr),
383 /// plus `geom_text`/`geom_label`. For one constant class on a whole
384 /// layer use [`GGPlot::layer_svg_attr`](crate::plot::GGPlot::layer_svg_attr)
385 /// `("class", "…")` instead.
386 pub fn class(self, col: &str) -> Self {
387 self.push(col, Aesthetic::Class)
388 }
389
390 /// Wrap marks in caller-named groups (#221): every mark whose row has
391 /// the same `col` value is drawn inside one `<g data-<name>="<value>">`
392 /// — across *all* layers that map `group_wrap` with the same `name` — so
393 /// client code can address (or tween) e.g. a diagram node's box, label
394 /// and badge as one element: `querySelector('[data-of="node-7"]')`.
395 ///
396 /// `name` follows [`data_attr`](Self::data_attr)'s rules
397 /// (`[a-z0-9][a-z0-9-]*`, not reserved); a leading `data-` is accepted
398 /// and stripped, so `group_wrap("of", …)` and `group_wrap("data-of", …)`
399 /// are the same. An invalid name is skipped with a build warning. A row
400 /// whose value is NA is drawn ungrouped.
401 ///
402 /// Paint order: a group is placed where its *first* mark would have
403 /// been drawn, and later marks of the same group are appended inside
404 /// it. So with a box layer then a label layer, both grouped by node,
405 /// the output is `<g data-of="a">box-a label-a</g><g data-of="b">box-b
406 /// label-b</g>` — node `b`'s box now paints over node `a`'s label,
407 /// which only matters if they overlap. Ungrouped marks keep their
408 /// positions. SVG backend only; raster backends ignore grouping.
409 pub fn group_wrap(mut self, name: &str, col: &str) -> Self {
410 let suffix = name.strip_prefix("data-").unwrap_or(name);
411 if !is_valid_data_attr_name(suffix) {
412 let reason = if RESERVED_DATA_ATTR_NAMES.contains(&suffix) {
413 "reserved (written by ggplot-rs itself)"
414 } else {
415 "invalid (must match [a-z0-9][a-z0-9-]*)"
416 };
417 self.warnings.push(format!(
418 "aes: group_wrap name {name:?} is {reason}; skipped"
419 ));
420 return self;
421 }
422 self.push(col, Aesthetic::GroupWrap(format!("data-{suffix}")))
423 }
424 /// Source node of a link (`geom_sankey`).
425 pub fn from(self, col: &str) -> Self {
426 self.push(col, Aesthetic::From)
427 }
428 /// Target node of a link (`geom_sankey`).
429 pub fn to(self, col: &str) -> Self {
430 self.push(col, Aesthetic::To)
431 }
432 /// Set combination of each row (`geom_venn`): `"A"`, `"A&B"`, …
433 pub fn sets(self, col: &str) -> Self {
434 self.push(col, Aesthetic::Sets)
435 }
436 /// Hierarchy parent of each row (`geom_treemap`).
437 pub fn subgroup(self, col: &str) -> Self {
438 self.push(col, Aesthetic::Subgroup)
439 }
440 /// Opening price (`geom_candlestick` / `geom_ohlc`).
441 pub fn open(self, col: &str) -> Self {
442 self.push(col, Aesthetic::Open)
443 }
444 /// Period high (`geom_candlestick` / `geom_ohlc`).
445 pub fn high(self, col: &str) -> Self {
446 self.push(col, Aesthetic::High)
447 }
448 /// Period low (`geom_candlestick` / `geom_ohlc`).
449 pub fn low(self, col: &str) -> Self {
450 self.push(col, Aesthetic::Low)
451 }
452 /// Closing price (`geom_candlestick` / `geom_ohlc`).
453 pub fn close(self, col: &str) -> Self {
454 self.push(col, Aesthetic::Close)
455 }
456 /// Data-mapped `geom_vline` position (one line per row).
457 pub fn xintercept(self, col: &str) -> Self {
458 self.push(col, Aesthetic::Xintercept)
459 }
460 /// Data-mapped `geom_hline` position (one line per row).
461 pub fn yintercept(self, col: &str) -> Self {
462 self.push(col, Aesthetic::Yintercept)
463 }
464 /// Data-mapped `geom_abline` slope (one line per row).
465 pub fn slope(self, col: &str) -> Self {
466 self.push(col, Aesthetic::Slope)
467 }
468 /// Data-mapped `geom_abline` intercept (one line per row).
469 pub fn intercept(self, col: &str) -> Self {
470 self.push(col, Aesthetic::Intercept)
471 }
472
473 // ─── after_stat() mappings ──────────────────────────────────
474 // Map stat-computed columns (e.g., `density`, `count`, `ncount`, `ndensity`)
475 // to an aesthetic. These are resolved after the stat step in the build pipeline.
476
477 /// Map a stat-computed column to the y aesthetic (e.g., `after_stat_y("density")`).
478 pub fn after_stat_y(self, col: &str) -> Self {
479 self.push_after_stat(col, Aesthetic::Y)
480 }
481
482 /// Map a stat-computed column to the x aesthetic.
483 pub fn after_stat_x(self, col: &str) -> Self {
484 self.push_after_stat(col, Aesthetic::X)
485 }
486
487 /// Map a stat-computed column to the fill aesthetic.
488 pub fn after_stat_fill(self, col: &str) -> Self {
489 self.push_after_stat(col, Aesthetic::Fill)
490 }
491
492 /// Map a stat-computed column to the color aesthetic.
493 pub fn after_stat_color(self, col: &str) -> Self {
494 self.push_after_stat(col, Aesthetic::Color)
495 }
496
497 /// Map a stat-computed column to the size aesthetic.
498 pub fn after_stat_size(self, col: &str) -> Self {
499 self.push_after_stat(col, Aesthetic::Size)
500 }
501
502 /// Map a stat-computed column to the alpha aesthetic.
503 pub fn after_stat_alpha(self, col: &str) -> Self {
504 self.push_after_stat(col, Aesthetic::Alpha)
505 }
506
507 /// Map a stat-computed column to the linewidth aesthetic.
508 pub fn after_stat_linewidth(self, col: &str) -> Self {
509 self.push_after_stat(col, Aesthetic::Linewidth)
510 }
511
512 /// Get the column mapped to a specific aesthetic.
513 pub fn get_mapping(&self, aes: &Aesthetic) -> Option<&str> {
514 self.mappings
515 .iter()
516 .find(|m| m.aesthetic == *aes)
517 .map(|m| m.column.as_str())
518 }
519
520 /// Merge another Aes into this one. The other's mappings override on conflict.
521 pub fn merge(&self, other: &Aes) -> Aes {
522 let mut result = self.clone();
523 for m in &other.mappings {
524 // Remove existing mapping for same aesthetic
525 result
526 .mappings
527 .retain(|existing| existing.aesthetic != m.aesthetic);
528 result.mappings.push(m.clone());
529 }
530 result.warnings.extend(other.warnings.iter().cloned());
531 result
532 }
533}
534
535/// Names ggplot-rs itself writes via a mechanism other than `data_attr`'s
536/// `set_mark_attrs` dedup — reserved so a user mapping can never collide and
537/// produce a duplicate attribute. `"part"` is `DrawBackend::set_mark_part`
538/// (arrowheads: `data-part="arrow"`), written directly in `push_mark`, not
539/// through the built-ins list `set_mark_attrs` dedups against. `"geom"` is
540/// `SvgBackend::mark_class`'s `data-geom="<layer geom>"`, written the same
541/// way, always last, alongside the `gg-mark` class. `"fvalue"`/`"fx"` are
542/// `DrawBackend::set_mark_fvalue`/`set_mark_fx` (B2-4), written the same way.
543const RESERVED_DATA_ATTR_NAMES: &[&str] = &["part", "geom", "fvalue", "fx"];
544
545/// `[a-z0-9][a-z0-9-]*`, excluding [`RESERVED_DATA_ATTR_NAMES`] — a valid,
546/// non-colliding HTML custom-data-attribute suffix.
547pub(crate) fn is_valid_data_attr_name(name: &str) -> bool {
548 if RESERVED_DATA_ATTR_NAMES.contains(&name) {
549 return false;
550 }
551 let mut chars = name.chars();
552 match chars.next() {
553 Some(c) if c.is_ascii_lowercase() || c.is_ascii_digit() => {}
554 _ => return false,
555 }
556 chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
557}
558
559/// Internal storage namespace for validated interactive-aesthetic columns
560/// (`data_attr`, `tooltip`) in the built DataFrame. Starts with a NUL byte,
561/// which can't appear in any column name `resolve_mappings` carries over
562/// from a caller's raw source data: that loop explicitly drops a raw column
563/// whose name contains a NUL (or this prefix) rather than carrying it
564/// through unchanged — see its doc. So in practice no caller-supplied
565/// column collides with a name under this prefix, but the real guarantee is
566/// that drop, not merely that a legitimate column "wouldn't" be named this
567/// way (`GGPlot::new` accepts any `String`, including one with a NUL byte
568/// in it, deliberately crafted to collide).
569pub(crate) const INTERNAL_PREFIX: &str = "\u{0}ggplot-rs:";
570
571/// Internal storage prefix for validated `data_attr` columns — see
572/// [`INTERNAL_PREFIX`]. `geom::set_row_extras` looks for *only* this
573/// prefix instead of scanning for anything that merely looks like a
574/// `data-*` column, which would also match an unrelated raw source column
575/// a caller never mapped through `Aes::data_attr` (the injection this
576/// guards against: see `validated_data_attr_internal_name`).
577pub(crate) const DATA_ATTR_INTERNAL_PREFIX: &str = "\u{0}ggplot-rs:data-attr:";
578
579/// Internal storage name for a validated `Aes::tooltip` mapping — see
580/// [`INTERNAL_PREFIX`]. Without this, an unmapped raw column literally
581/// named `"tooltip"` would drive every mark's hover title (the same class
582/// of bug `DATA_ATTR_INTERNAL_PREFIX` fixes for `data_attr`); routing it
583/// through the same internal-prefix scheme closes that for tooltips too.
584pub(crate) const TOOLTIP_INTERNAL_NAME: &str = "\u{0}ggplot-rs:tooltip";
585
586/// Internal storage name for a validated `Aes::class` mapping (#221) — see
587/// [`INTERNAL_PREFIX`]; same reasoning as [`TOOLTIP_INTERNAL_NAME`].
588pub(crate) const CLASS_INTERNAL_NAME: &str = "\u{0}ggplot-rs:class";
589
590/// Internal storage prefix for a validated `Aes::group_wrap` mapping
591/// (#221), followed by the full `data-<name>` attribute — see
592/// [`INTERNAL_PREFIX`]; same reasoning as [`DATA_ATTR_INTERNAL_PREFIX`].
593pub(crate) const GROUP_WRAP_INTERNAL_PREFIX: &str = "\u{0}ggplot-rs:group-wrap:";
594
595/// One CSS class token (#221): `^[A-Za-z][A-Za-z0-9_-]*$`. Deliberately
596/// narrower than CSS allows (no escapes, no leading digit or `-`), so a
597/// token can never break out of the attribute or need escaping.
598pub(crate) fn is_valid_class_token(token: &str) -> bool {
599 let mut chars = token.chars();
600 match chars.next() {
601 Some(c) if c.is_ascii_alphabetic() => {}
602 _ => return false,
603 }
604 chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
605}
606
607/// Split `value` on whitespace into `(valid tokens, rejected tokens)` —
608/// see [`is_valid_class_token`]. Duplicate valid tokens are kept once.
609pub(crate) fn split_class_tokens(value: &str) -> (Vec<String>, Vec<String>) {
610 let (mut ok, mut bad) = (Vec::<String>::new(), Vec::new());
611 for t in value.split_whitespace() {
612 if !is_valid_class_token(t) {
613 bad.push(t.to_string());
614 } else if !ok.iter().any(|o| o == t) {
615 ok.push(t.to_string());
616 }
617 }
618 (ok, bad)
619}
620
621/// Validate a `group_wrap` mapping's target (`"data-<name>"`, as stored in
622/// [`Aesthetic::GroupWrap`]) and return its internal column name — the
623/// same single authoritative gate [`validated_data_attr_internal_name`] is.
624pub(crate) fn validated_group_wrap_internal_name(target: &str) -> Option<String> {
625 let suffix = target.strip_prefix("data-")?;
626 is_valid_data_attr_name(suffix).then(|| format!("{GROUP_WRAP_INTERNAL_PREFIX}{target}"))
627}
628
629/// Internal storage names for `GeomBoxplot::setup_data`'s outlier-extent
630/// columns — see [`INTERNAL_PREFIX`] (review #158 finding 5: these used to
631/// be plain `"ymin_final"`/`"ymax_final"`, trained into the y scale for
632/// *every* layer at build Step 8b regardless of which geom produced them;
633/// `resolve_mappings` carries over any raw source column with a
634/// not-otherwise-mapped canonical name, so a raw column literally named
635/// `ymin_final` — e.g. a SQL alias — on an unrelated geom like `geom_point`
636/// silently widened its y domain. Routing them through the internal-prefix
637/// scheme means only `GeomBoxplot::setup_data` itself can ever produce
638/// these columns; a raw column with this name is already stripped by
639/// `is_forged_internal_name` before it reaches the built data.
640pub(crate) const BOXPLOT_YMIN_FINAL: &str = "\u{0}ggplot-rs:ymin_final";
641pub(crate) const BOXPLOT_YMAX_FINAL: &str = "\u{0}ggplot-rs:ymax_final";
642
643/// Validate a `data_attr` mapping's target (`"data-<name>"`, as stored in
644/// [`Aesthetic::DataAttr`]) and, if valid, return the internal column name
645/// it should be written under. This is the single authoritative gate: it
646/// runs in `resolve_mappings` regardless of *how* the `DataAttr` mapping was
647/// created — the validated `Aes::data_attr` builder, or a `DataAttr`
648/// constructed directly and pushed into the public `Aes.mappings` field,
649/// bypassing the builder's own check.
650pub(crate) fn validated_data_attr_internal_name(data_attr_target: &str) -> Option<String> {
651 let suffix = data_attr_target.strip_prefix("data-")?;
652 if is_valid_data_attr_name(suffix) {
653 Some(format!("{DATA_ATTR_INTERNAL_PREFIX}{data_attr_target}"))
654 } else {
655 None
656 }
657}
658
659#[cfg(test)]
660mod data_attr_name_tests {
661 use super::{is_valid_data_attr_name, validated_data_attr_internal_name};
662
663 #[test]
664 fn accepts_lowercase_alnum_and_hyphen() {
665 for ok in ["x", "row", "data-ish", "a1", "0a", "value"] {
666 assert!(is_valid_data_attr_name(ok), "{ok} should be valid");
667 }
668 }
669
670 #[test]
671 fn rejects_empty_uppercase_and_other_punctuation() {
672 for bad in ["", "-x", "X", "a_b", "a.b", "a b", "déjà"] {
673 assert!(!is_valid_data_attr_name(bad), "{bad} should be invalid");
674 }
675 }
676
677 #[test]
678 fn rejects_the_reserved_part_name() {
679 assert!(!is_valid_data_attr_name("part"));
680 assert_eq!(validated_data_attr_internal_name("data-part"), None);
681 }
682
683 #[test]
684 fn rejects_the_reserved_geom_fvalue_and_fx_names() {
685 // B2-0's `data-geom` and B2-4's `data-fvalue`/`data-fx` are written
686 // directly in `push_mark`, the same way `data-part` is — a
687 // `data_attr` mapping under any of these names would duplicate it.
688 for name in ["geom", "fvalue", "fx"] {
689 assert!(!is_valid_data_attr_name(name), "{name} should be reserved");
690 assert_eq!(
691 validated_data_attr_internal_name(&format!("data-{name}")),
692 None
693 );
694 }
695 }
696
697 #[test]
698 fn rejects_a_malformed_injection_attempt_even_with_the_data_prefix() {
699 // Space, `=`, parens: none of these are legal in the suffix.
700 assert_eq!(
701 validated_data_attr_internal_name("data-a onmouseover=alert(1) b"),
702 None
703 );
704 }
705
706 #[test]
707 fn valid_target_maps_to_the_internal_prefix_plus_itself() {
708 let internal = validated_data_attr_internal_name("data-orig").unwrap();
709 assert!(internal.starts_with(super::DATA_ATTR_INTERNAL_PREFIX));
710 assert!(internal.ends_with("data-orig"));
711 }
712}
713
714#[cfg(test)]
715mod aesthetic_and_aes_tests {
716 use super::{Aes, Aesthetic};
717
718 /// `col_name()` for `Tooltip`/`DataAttr` is never actually used for
719 /// storage (both are special-cased in `aes::mapping`), but it should
720 /// still return a sane, documented fallback for a direct caller.
721 #[test]
722 fn col_name_for_tooltip_and_data_attr() {
723 assert_eq!(Aesthetic::Tooltip.col_name(), "tooltip");
724 assert_eq!(
725 Aesthetic::DataAttr("data-orig".to_string()).col_name(),
726 "data-orig"
727 );
728 }
729
730 #[test]
731 fn data_attr_warning_text_distinguishes_invalid_from_reserved() {
732 let invalid = Aes::new().data_attr("Not Valid!", "col");
733 assert_eq!(invalid.warnings.len(), 1);
734 assert!(invalid.warnings[0].contains("invalid"));
735 assert!(!invalid.warnings[0].contains("reserved"));
736
737 let reserved = Aes::new().data_attr("part", "col");
738 assert_eq!(reserved.warnings.len(), 1);
739 assert!(reserved.warnings[0].contains("reserved"));
740 }
741
742 #[test]
743 fn after_stat_linewidth_maps_a_stat_computed_column() {
744 let aes = Aes::new().after_stat_linewidth("weight");
745 assert_eq!(aes.get_mapping(&Aesthetic::Linewidth), Some("weight"));
746 }
747}