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