teksilo_charts/pattern.rs
1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4//! Drawing the non-colour series channel — WCAG 1.4.1.
5//!
6//! [`SeriesPattern`] (in `teksilo-data`) says *what* a series' second channel
7//! is; this module draws it. Three renderings, one per shape a chart uses:
8//!
9//! - [`stroke_style`] — the dash pattern for a line chart's series line.
10//! - [`draw_marker`] — the glyph at a data point, and in a legend swatch.
11//! - [`fill_hatch`] — the hatch laid over a bar, an area fill, or a legend
12//! swatch.
13//!
14//! # When a chart draws it
15//!
16//! [`PatternPolicy::Auto`] — the default — draws the channel exactly when
17//! colour is doing identification work: from the **second visible series**
18//! onwards. A chart with one series has nothing to tell apart, so dashing its
19//! line and hatching its bars would add visual noise carrying no information;
20//! a chart with two or more cannot be read without it by anyone who does not
21//! see the palette. `Always` and `Never` override the judgement — `Never` is a
22//! deliberate accessibility regression and is named plainly so it reads as one
23//! at the call site.
24//!
25//! # Hatch geometry
26//!
27//! Hatches are parallel strokes clipped to the region being filled. The canvas
28//! clips to rectangles only, so hatching works on bars and swatches (both
29//! rectangles) and on anything a caller can bound by one. A pie slice is not a
30//! rectangle, which is why `PieChart` carries its channel as a centroid marker
31//! instead of a hatch.
32//!
33//! The hatch colour is derived from the fill rather than taken from the theme:
34//! a token would have to be either light or dark and would vanish against half
35//! the palette. [`hatch_color`] picks black or white by the fill's luminance,
36//! at an alpha low enough to read as texture rather than as a second series.
37
38use teksilo_canvas::{Canvas, Path, Point, Rect, StrokeStyle};
39use teksilo_data::{SeriesHatch, SeriesMarker, SeriesPattern};
40use teksilo_tokens::Color;
41
42/// Spacing between adjacent hatch strokes, in logical pixels. Wide enough that
43/// a 4 dp bar still shows the pattern rather than turning into a solid block.
44const HATCH_SPACING: f32 = 6.0;
45/// Hatch stroke width.
46const HATCH_WIDTH: f32 = 1.5;
47/// Hatch alpha over the fill — texture, not a second colour.
48const HATCH_ALPHA: f32 = 0.55;
49
50/// Whether a chart draws its series' non-colour channel.
51///
52/// See the [module docs](self) — `Auto` is the default and the accessible one.
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
54pub enum PatternPolicy {
55 /// Draw the channel once more than one series is visible. Default.
56 #[default]
57 Auto,
58 /// Always draw it, even for a single series.
59 Always,
60 /// Never draw it.
61 ///
62 /// This leaves colour as the only means of telling series apart, which
63 /// fails WCAG 1.4.1 for any chart with more than one series. Reach for it
64 /// only where something else in the design already carries the distinction
65 /// — direct series labels on the plot, one series per chart in a small
66 /// multiple.
67 Never,
68}
69
70impl PatternPolicy {
71 /// Whether to draw the channel with `visible_series` series on the plot.
72 pub fn applies(self, visible_series: usize) -> bool {
73 match self {
74 Self::Auto => visible_series > 1,
75 Self::Always => true,
76 Self::Never => false,
77 }
78 }
79}
80
81/// The pattern for the series at `index`: its own, or the one its position
82/// implies.
83pub fn resolve(explicit: Option<SeriesPattern>, index: usize) -> SeriesPattern {
84 explicit.unwrap_or_else(|| SeriesPattern::for_index(index))
85}
86
87/// The stroke style for a series line: `pattern`'s dash at `width`, or a plain
88/// solid stroke when the chart is not drawing the channel.
89pub fn stroke_style(pattern: SeriesPattern, width: f32, enabled: bool) -> StrokeStyle {
90 match enabled.then(|| pattern.dash(width)).flatten() {
91 Some((dash, gap)) => StrokeStyle::dashed(width, dash, gap),
92 None => StrokeStyle::solid(width),
93 }
94}
95
96/// A hatch stroke colour that reads against `fill`.
97///
98/// Black over a light fill, white over a dark one, both translucent. Derived
99/// rather than themed: a fixed token would disappear against half of any
100/// palette, and the hatch exists precisely to stay visible.
101pub fn hatch_color(fill: Color) -> Color {
102 // Rec. 601 luma — the same weighting the tokens crate uses for contrast
103 // decisions, and close enough for a "is this fill light or dark" test.
104 let luma = 0.299 * fill.r() + 0.587 * fill.g() + 0.114 * fill.b();
105 let base = if luma > 0.55 {
106 Color::BLACK
107 } else {
108 Color::WHITE
109 };
110 base.with_alpha(HATCH_ALPHA)
111}
112
113/// Lay `pattern`'s hatch over the rectangle `rect`, already filled with `fill`.
114///
115/// A no-op for [`SeriesHatch::None`] (the `Solid` pattern) and for a rectangle
116/// too small to show one. Clips to `rect`, then restores the previous clip
117/// state by clearing it — callers that rely on an outer clip must re-establish
118/// it afterwards.
119pub fn fill_hatch(canvas: &mut Canvas, rect: Rect, pattern: SeriesPattern, fill: Color) {
120 let hatch = pattern.hatch();
121 if hatch == SeriesHatch::None || rect.width < 1.0 || rect.height < 1.0 {
122 return;
123 }
124 let color = hatch_color(fill);
125 canvas.set_clip(rect);
126 for path in hatch_paths(rect, hatch) {
127 canvas.stroke_path(&path, color, StrokeStyle::solid(HATCH_WIDTH));
128 }
129 canvas.clear_clip();
130}
131
132/// The unclipped stroke paths making up `hatch` across `rect`.
133///
134/// Split out from [`fill_hatch`] so the geometry is testable without a canvas.
135fn hatch_paths(rect: Rect, hatch: SeriesHatch) -> Vec<Path> {
136 let mut paths = Vec::new();
137 let (x0, y0) = (rect.x, rect.y);
138 let (x1, y1) = (rect.x + rect.width, rect.y + rect.height);
139
140 match hatch {
141 SeriesHatch::None => {}
142 SeriesHatch::Horizontal => {
143 let mut y = y0 + HATCH_SPACING * 0.5;
144 while y < y1 {
145 paths.push(Path::line(Point::new(x0, y), Point::new(x1, y)));
146 y += HATCH_SPACING;
147 }
148 }
149 SeriesHatch::Vertical => {
150 let mut x = x0 + HATCH_SPACING * 0.5;
151 while x < x1 {
152 paths.push(Path::line(Point::new(x, y0), Point::new(x, y1)));
153 x += HATCH_SPACING;
154 }
155 }
156 SeriesHatch::Forward | SeriesHatch::Backward | SeriesHatch::Cross => {
157 // A 45° family is swept by walking the x-intercept from
158 // `-height` to `width`, so every line that crosses the rectangle
159 // is emitted regardless of aspect ratio. Each segment is drawn
160 // corner-to-corner past the edges and clipped by the caller.
161 let span = rect.width + rect.height;
162 let step = HATCH_SPACING * std::f32::consts::SQRT_2;
163 let mut offset = -rect.height;
164 while offset < rect.width {
165 if matches!(hatch, SeriesHatch::Forward | SeriesHatch::Cross) {
166 paths.push(Path::line(
167 Point::new(x0 + offset, y1),
168 Point::new(x0 + offset + span, y1 - span),
169 ));
170 }
171 if matches!(hatch, SeriesHatch::Backward | SeriesHatch::Cross) {
172 paths.push(Path::line(
173 Point::new(x0 + offset, y0),
174 Point::new(x0 + offset + span, y0 + span),
175 ));
176 }
177 offset += step;
178 }
179 }
180 }
181 paths
182}
183
184/// Draw `pattern`'s marker glyph centred at `center` with radius `radius`.
185///
186/// Filled, in the series' own colour — the *shape* is the channel, so the
187/// colour stays the series' own and the glyph reads as part of the line.
188pub fn draw_marker(
189 canvas: &mut Canvas,
190 center: Point,
191 radius: f32,
192 marker: SeriesMarker,
193 color: Color,
194) {
195 let r = radius.max(1.0);
196 match marker {
197 SeriesMarker::Circle => canvas.fill_circle(center, r, color),
198 SeriesMarker::Square => canvas.fill_rect(
199 Rect::new(center.x - r, center.y - r, r * 2.0, r * 2.0),
200 color,
201 ),
202 SeriesMarker::Triangle => {
203 // Slightly enlarged: an equilateral triangle inscribed in a circle
204 // of radius r covers about half the area of the circle, so at the
205 // same r it reads as a smaller mark than the others.
206 let t = r * 1.25;
207 canvas.fill_path(
208 &Path::polygon(&[
209 Point::new(center.x, center.y - t),
210 Point::new(center.x + t * 0.87, center.y + t * 0.5),
211 Point::new(center.x - t * 0.87, center.y + t * 0.5),
212 ]),
213 color,
214 );
215 }
216 SeriesMarker::Diamond => {
217 let t = r * 1.25;
218 canvas.fill_path(
219 &Path::polygon(&[
220 Point::new(center.x, center.y - t),
221 Point::new(center.x + t, center.y),
222 Point::new(center.x, center.y + t),
223 Point::new(center.x - t, center.y),
224 ]),
225 color,
226 );
227 }
228 SeriesMarker::Cross => {
229 let t = r * 1.2;
230 let w = StrokeStyle::solid((r * 0.8).max(1.0));
231 canvas.stroke_path(
232 &Path::line(
233 Point::new(center.x - t, center.y - t),
234 Point::new(center.x + t, center.y + t),
235 ),
236 color,
237 w.clone(),
238 );
239 canvas.stroke_path(
240 &Path::line(
241 Point::new(center.x - t, center.y + t),
242 Point::new(center.x + t, center.y - t),
243 ),
244 color,
245 w,
246 );
247 }
248 SeriesMarker::Plus => {
249 let t = r * 1.3;
250 let w = StrokeStyle::solid((r * 0.8).max(1.0));
251 canvas.stroke_path(
252 &Path::line(
253 Point::new(center.x - t, center.y),
254 Point::new(center.x + t, center.y),
255 ),
256 color,
257 w.clone(),
258 );
259 canvas.stroke_path(
260 &Path::line(
261 Point::new(center.x, center.y - t),
262 Point::new(center.x, center.y + t),
263 ),
264 color,
265 w,
266 );
267 }
268 }
269}
270
271/// How a legend swatch samples its series.
272///
273/// The swatch has to look like what the plot draws, or the legend hands the
274/// reader a second mapping to learn — which is the whole failure the pattern
275/// channel exists to fix.
276#[derive(Debug, Clone, Copy, PartialEq, Eq)]
277pub enum LegendSwatch {
278 /// A filled chip carrying the series' hatch. Matches a bar or a pie slice.
279 Block,
280 /// A short line sample carrying the series' dash, with the marker glyph at
281 /// its centre when the plot draws markers. Matches a line series.
282 Line {
283 /// Whether the plot draws point markers (`LineChart::show_points`).
284 marker: bool,
285 },
286 /// A filled chip stamped with the marker glyph in a contrasting tone.
287 /// Matches a pie slice, which carries the same glyph at its centroid — a
288 /// wedge is not a rectangle, so it cannot be hatched by the rect clip.
289 Marked,
290}
291
292/// Draw one legend swatch for `pattern` in `color` inside `rect`.
293///
294/// `patterned` is the chart's live [`PatternPolicy`] verdict: `false` falls
295/// back to the plain colour chip this drew before the channel existed, so the
296/// legend never advertises a distinction the plot is not making.
297pub fn draw_legend_swatch(
298 canvas: &mut Canvas,
299 rect: Rect,
300 swatch: LegendSwatch,
301 pattern: SeriesPattern,
302 color: Color,
303 patterned: bool,
304) {
305 use teksilo_tokens::CornerRadius;
306
307 match swatch {
308 LegendSwatch::Block => {
309 canvas.fill_rounded_rect(rect, CornerRadius::uniform(2.0), color);
310 if patterned {
311 fill_hatch(canvas, rect, pattern, color);
312 }
313 }
314 LegendSwatch::Marked => {
315 canvas.fill_rounded_rect(rect, CornerRadius::uniform(2.0), color);
316 if patterned {
317 draw_marker(
318 canvas,
319 Point::new(rect.x + rect.width * 0.5, rect.y + rect.height * 0.5),
320 rect.height * 0.28,
321 pattern.marker(),
322 hatch_color(color),
323 );
324 }
325 }
326 LegendSwatch::Line { marker } => {
327 let center = Point::new(rect.x + rect.width * 0.5, rect.y + rect.height * 0.5);
328 let width = (rect.height * 0.22).max(1.5);
329 // The sample is short, so the dash is scaled to the sample rather
330 // than to the plot's line width — at 10 dp a plot-scale dash shows
331 // barely one segment and every pattern looks alike.
332 let stroke = stroke_style(pattern, width, patterned);
333 canvas.stroke_path(
334 &Path::line(
335 Point::new(rect.x, center.y),
336 Point::new(rect.x + rect.width, center.y),
337 ),
338 color,
339 stroke,
340 );
341 if marker {
342 draw_marker(
343 canvas,
344 center,
345 rect.height * 0.3,
346 if patterned {
347 pattern.marker()
348 } else {
349 SeriesMarker::Circle
350 },
351 color,
352 );
353 }
354 }
355 }
356}
357
358#[cfg(test)]
359mod tests {
360 use super::*;
361
362 #[test]
363 fn auto_holds_off_until_colour_is_doing_work() {
364 assert!(
365 !PatternPolicy::Auto.applies(1),
366 "a single-series chart has nothing to disambiguate"
367 );
368 assert!(
369 PatternPolicy::Auto.applies(2),
370 "two series cannot be told apart by colour alone (WCAG 1.4.1)"
371 );
372 assert!(PatternPolicy::Always.applies(1));
373 assert!(!PatternPolicy::Never.applies(9));
374 }
375
376 #[test]
377 fn an_unset_pattern_falls_back_to_the_series_position() {
378 assert_eq!(resolve(None, 1), SeriesPattern::for_index(1));
379 assert_eq!(
380 resolve(Some(SeriesPattern::Dotted), 1),
381 SeriesPattern::Dotted,
382 "an explicit pattern must survive the series' position"
383 );
384 }
385
386 #[test]
387 fn a_disabled_channel_strokes_solid_whatever_the_pattern_says() {
388 assert_eq!(
389 stroke_style(SeriesPattern::Dashed, 2.0, false).dash_pattern,
390 None
391 );
392 assert!(
393 stroke_style(SeriesPattern::Dashed, 2.0, true)
394 .dash_pattern
395 .is_some()
396 );
397 assert_eq!(
398 stroke_style(SeriesPattern::Solid, 2.0, true).dash_pattern,
399 None,
400 "the Solid pattern is solid even when the channel is on"
401 );
402 }
403
404 #[test]
405 fn the_hatch_contrasts_with_the_fill_it_covers() {
406 assert_eq!(hatch_color(Color::WHITE).r(), Color::BLACK.r());
407 assert_eq!(hatch_color(Color::BLACK).r(), Color::WHITE.r());
408 assert!(
409 hatch_color(Color::WHITE).a() < 1.0,
410 "a fully opaque hatch would read as a second series, not a texture"
411 );
412 }
413
414 /// The union of every stroke's bounds.
415 fn swept(paths: &[Path]) -> Rect {
416 paths.iter().fold(paths[0].bounds(), |acc, p| {
417 let b = p.bounds();
418 let x0 = acc.x.min(b.x);
419 let y0 = acc.y.min(b.y);
420 let x1 = (acc.x + acc.width).max(b.x + b.width);
421 let y1 = (acc.y + acc.height).max(b.y + b.height);
422 Rect::new(x0, y0, x1 - x0, y1 - y0)
423 })
424 }
425
426 #[test]
427 fn the_diagonal_sweep_reaches_every_corner_of_a_tall_rectangle() {
428 // The failure this pins: a 45° sweep whose x-intercept starts at the
429 // rectangle's own left edge misses the whole bottom-left region of a
430 // rectangle taller than it is wide — the exact shape of a bar. The
431 // sweep must therefore start a full `height` to the left.
432 let rect = Rect::new(10.0, 20.0, 30.0, 120.0);
433 for hatch in [
434 SeriesHatch::Forward,
435 SeriesHatch::Backward,
436 SeriesHatch::Cross,
437 ] {
438 let paths = hatch_paths(rect, hatch);
439 assert!(!paths.is_empty(), "{hatch:?} produced no strokes");
440 let union = swept(&paths);
441 assert!(
442 union.x <= rect.x
443 && union.y <= rect.y
444 && union.x + union.width >= rect.x + rect.width
445 && union.y + union.height >= rect.y + rect.height,
446 "{hatch:?} sweeps {union:?}, which does not cover {rect:?}"
447 );
448 }
449 }
450
451 #[test]
452 fn axis_aligned_hatches_are_evenly_spread_across_the_rectangle() {
453 // These are inset by half a period at each end by design — evenly
454 // distributed lines, not lines flush with the edges — so the property
455 // is that no run of bare pixels exceeds one hatch period.
456 let rect = Rect::new(10.0, 20.0, 30.0, 120.0);
457 for hatch in [SeriesHatch::Horizontal, SeriesHatch::Vertical] {
458 let paths = hatch_paths(rect, hatch);
459 assert!(paths.len() > 1, "{hatch:?} produced too few strokes");
460 let union = swept(&paths);
461 assert!(
462 union.x >= rect.x - 0.01 && union.y >= rect.y - 0.01,
463 "{hatch:?} strokes outside the rectangle: {union:?}"
464 );
465 assert!(
466 union.x - rect.x <= HATCH_SPACING
467 && union.y - rect.y <= HATCH_SPACING
468 && (rect.x + rect.width) - (union.x + union.width) <= HATCH_SPACING
469 && (rect.y + rect.height) - (union.y + union.height) <= HATCH_SPACING,
470 "{hatch:?} leaves a bare band wider than one period: {union:?} vs {rect:?}"
471 );
472 }
473 }
474
475 #[test]
476 fn a_degenerate_rectangle_draws_nothing() {
477 assert!(hatch_paths(Rect::new(0.0, 0.0, 0.0, 0.0), SeriesHatch::Cross).is_empty());
478 assert!(hatch_paths(Rect::new(0.0, 0.0, 40.0, 10.0), SeriesHatch::None).is_empty());
479 }
480}