Skip to main content

lumen_dioxus/charts/
geometry.rs

1// cspell:words srgb
2//! Geometry for the series charts: line paths, bars, pie slices, scatter points, heatmap cells,
3//! and range intervals. Ported from lumen-core's `charts.ts` and `chart-models.ts`.
4
5use std::collections::{HashMap, HashSet};
6
7use dioxus::prelude::*;
8
9use super::format::{js_equals, js_number, js_to_fixed};
10use super::model::{
11    ChartBounds, ChartDatum, ChartDomain, ChartSeries, ChartTone, ChartX, format_with,
12};
13use super::scale::{
14    CategoryTick, CategoryTickOptions, LabelContext, align_series, axis_domain, axis_padding,
15    category_label, category_ticks, chart_categories, chart_domain, chart_ticks,
16    estimate_chart_label_width, fitted_label, format_ticks, nice_domain, resolve_domain,
17    scale_value, value_ratio,
18};
19
20/// How a [`LineChart`](crate::LineChart) places x values.
21#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
22#[non_exhaustive]
23pub enum LineChartScale {
24    /// Evenly spaced categories in data order.
25    #[default]
26    Categorical,
27    /// Numeric x values on a linear scale.
28    Linear,
29    /// ISO 8601 dates (or millisecond timestamps) on a time scale.
30    Time,
31}
32
33/// Days from 1970-01-01 to a proleptic Gregorian date.
34fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
35    let year = if month <= 2 { year - 1 } else { year };
36    let era = year.div_euclid(400);
37    let year_of_era = year - era * 400;
38    let month_index = (month + 9) % 12;
39    let day_of_year = (153 * month_index + 2) / 5 + day - 1;
40    let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
41
42    era * 146_097 + day_of_era - 719_468
43}
44
45fn is_leap_year(year: i64) -> bool {
46    (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
47}
48
49fn days_in_month(year: i64, month: i64) -> i64 {
50    match month {
51        2 if is_leap_year(year) => 29,
52        2 => 28,
53        4 | 6 | 9 | 11 => 30,
54        _ => 31,
55    }
56}
57
58/// Reads exactly `count` ASCII digits starting at `index`.
59fn read_digits(bytes: &[u8], index: usize, count: usize) -> Option<i64> {
60    let slice = bytes.get(index..index + count)?;
61
62    slice.iter().try_fold(0_i64, |total, byte| {
63        byte.is_ascii_digit()
64            .then(|| total * 10 + i64::from(byte - b'0'))
65    })
66}
67
68/// `Date.parse` for ISO 8601 strings, in one linear pass: `YYYY`, `YYYY-MM`, `YYYY-MM-DD`, and
69/// date-times `YYYY-MM-DDTHH:mm[:ss[.sss]][Z|±HH:mm]`. Date-times without an offset are read as
70/// UTC so every renderer agrees (JavaScript reads them in the device time zone).
71pub(crate) fn parse_iso_timestamp(text: &str) -> Option<f64> {
72    let bytes = text.as_bytes();
73
74    if bytes.len() > 40 {
75        return None;
76    }
77
78    let year = read_digits(bytes, 0, 4)?;
79    let mut index = 4;
80    let mut month = 1;
81    let mut day = 1;
82
83    if bytes.get(index) == Some(&b'-') {
84        month = read_digits(bytes, index + 1, 2)?;
85        index += 3;
86
87        if bytes.get(index) == Some(&b'-') {
88            day = read_digits(bytes, index + 1, 2)?;
89            index += 3;
90        }
91    }
92
93    if !(1..=12).contains(&month) || day < 1 || day > days_in_month(year, month) {
94        return None;
95    }
96
97    let mut milliseconds = 0_i64;
98
99    if index < bytes.len() {
100        if bytes[index] != b'T' || index != 10 {
101            return None;
102        }
103
104        let hours = read_digits(bytes, index + 1, 2)?;
105        let minutes = (bytes.get(index + 3) == Some(&b':'))
106            .then(|| read_digits(bytes, index + 4, 2))
107            .flatten()?;
108        index += 6;
109        let mut seconds = 0;
110        let mut fraction = 0;
111
112        if bytes.get(index) == Some(&b':') {
113            seconds = read_digits(bytes, index + 1, 2)?;
114            index += 3;
115
116            if bytes.get(index) == Some(&b'.') {
117                fraction = read_digits(bytes, index + 1, 3)?;
118                index += 4;
119            }
120        }
121
122        if hours > 24
123            || minutes > 59
124            || seconds > 59
125            || (hours == 24 && (minutes, seconds, fraction) != (0, 0, 0))
126        {
127            return None;
128        }
129
130        let mut offset = 0;
131
132        match bytes.get(index) {
133            None => {}
134            Some(b'Z') if index + 1 == bytes.len() => {}
135            Some(sign @ (b'+' | b'-')) if index + 6 == bytes.len() && bytes[index + 3] == b':' => {
136                let offset_hours = read_digits(bytes, index + 1, 2)?;
137                let offset_minutes = read_digits(bytes, index + 4, 2)?;
138
139                if offset_hours > 23 || offset_minutes > 59 {
140                    return None;
141                }
142
143                let total = (offset_hours * 60 + offset_minutes) * 60_000;
144                offset = if *sign == b'+' { total } else { -total };
145            }
146            Some(_) => return None,
147        }
148
149        milliseconds = ((hours * 60 + minutes) * 60 + seconds) * 1000 + fraction - offset;
150    }
151
152    let days = days_from_civil(year, month, day);
153    #[allow(clippy::cast_precision_loss)]
154    let timestamp = (days * 86_400_000 + milliseconds) as f64;
155
156    Some(timestamp)
157}
158
159/// `getLumenChartNumericX`: the numeric position of `x` on a linear or time scale.
160pub(crate) fn numeric_x(value: &ChartX, scale: LineChartScale) -> Option<f64> {
161    match value {
162        ChartX::Number(number) => number.is_finite().then_some(*number),
163        ChartX::Text(text) => match scale {
164            LineChartScale::Categorical | LineChartScale::Linear => {
165                let trimmed = text.trim();
166
167                if trimmed.is_empty() {
168                    return None;
169                }
170
171                parse_js_number(trimmed).filter(|number| number.is_finite())
172            }
173            LineChartScale::Time => parse_iso_timestamp(text),
174        },
175    }
176}
177
178/// `Number(text)` for trimmed decimal text (hex and binary prefixes are also accepted).
179fn parse_js_number(text: &str) -> Option<f64> {
180    let lower = text.to_ascii_lowercase();
181
182    for (prefix, radix) in [("0x", 16), ("0o", 8), ("0b", 2)] {
183        if let Some(digits) = lower.strip_prefix(prefix) {
184            #[allow(clippy::cast_precision_loss)]
185            return u64::from_str_radix(digits, radix)
186                .ok()
187                .map(|value| value as f64);
188        }
189    }
190
191    // Rust also reads `inf` and `NaN`; JavaScript's `Number` does not (it reads `Infinity`, which
192    // is not finite anyway).
193    if lower.contains("inf") || lower.contains("nan") {
194        return None;
195    }
196
197    text.parse::<f64>().ok()
198}
199
200/// A point of a line, with its SVG coordinates.
201#[derive(Clone, Debug, PartialEq)]
202pub(crate) struct GeometryPoint {
203    pub(crate) datum: ChartDatum,
204    pub(crate) x: f64,
205    pub(crate) y: f64,
206}
207
208/// `LumenLineGeometry`.
209#[derive(Clone, Debug, PartialEq)]
210pub(crate) struct LineGeometry {
211    pub(crate) area_paths: Vec<String>,
212    pub(crate) domain: ChartDomain,
213    pub(crate) path: String,
214    pub(crate) points: Vec<GeometryPoint>,
215}
216
217/// `LumenLineGeometryOptions`.
218#[derive(Clone, Copy, Debug)]
219pub(crate) struct LineGeometryOptions {
220    pub(crate) domain: Option<ChartBounds>,
221    pub(crate) height: f64,
222    pub(crate) include_zero: bool,
223    /// Horizontal space between the plot edges and the first and last x positions, so end markers
224    /// and their centred labels are not clipped. Capped at a quarter of the plot width.
225    pub(crate) inset: Option<f64>,
226    pub(crate) padding_bottom: f64,
227    pub(crate) padding_left: f64,
228    pub(crate) padding_right: f64,
229    pub(crate) padding_top: f64,
230    pub(crate) width: f64,
231    pub(crate) x_domain: Option<ChartBounds>,
232    pub(crate) x_scale: LineChartScale,
233}
234
235impl LineGeometryOptions {
236    /// The lumen-core defaults: a 100 × 100 frame with 4 units of padding.
237    pub(crate) fn new(width: f64, height: f64, padding: f64) -> Self {
238        Self {
239            domain: None,
240            height,
241            include_zero: false,
242            inset: None,
243            padding_bottom: padding,
244            padding_left: padding,
245            padding_right: padding,
246            padding_top: padding,
247            width,
248            x_domain: None,
249            x_scale: LineChartScale::Categorical,
250        }
251    }
252}
253
254fn segment_path(points: &[GeometryPoint]) -> String {
255    points
256        .iter()
257        .enumerate()
258        .map(|(index, point)| {
259            format!(
260                "{} {} {}",
261                if index == 0 { "M" } else { "L" },
262                js_to_fixed(point.x, 3),
263                js_to_fixed(point.y, 3)
264            )
265        })
266        .collect::<Vec<_>>()
267        .join(" ")
268}
269
270fn area_path(points: &[GeometryPoint], baseline: f64) -> String {
271    let (Some(first), Some(last)) = (points.first(), points.last()) else {
272        return String::new();
273    };
274
275    [
276        segment_path(points),
277        "L".to_string(),
278        js_to_fixed(last.x, 3),
279        js_to_fixed(baseline, 3),
280        "L".to_string(),
281        js_to_fixed(first.x, 3),
282        js_to_fixed(baseline, 3),
283        "Z".to_string(),
284    ]
285    .join(" ")
286}
287
288/// `resolveLumenChartInset`: non-negative, and never more than a quarter of the plot width.
289fn resolve_inset(inset: Option<f64>, plot_width: f64) -> f64 {
290    match inset {
291        Some(inset) if inset.is_finite() && inset > 0.0 => inset.min(plot_width.max(0.0) / 4.0),
292        _ => 0.0,
293    }
294}
295
296/// `createLumenLineGeometry`: one path per run of available points; missing values break lines.
297pub(crate) fn line_geometry(data: &[ChartDatum], options: LineGeometryOptions) -> LineGeometry {
298    let inset = resolve_inset(
299        options.inset,
300        options.width - options.padding_left - options.padding_right,
301    );
302    let options = LineGeometryOptions {
303        padding_left: options.padding_left + inset,
304        padding_right: options.padding_right + inset,
305        ..options
306    };
307    let scale = options.x_scale;
308    let domain_values: Vec<Option<f64>> = data
309        .iter()
310        .filter(|datum| {
311            scale == LineChartScale::Categorical || numeric_x(&datum.x, scale).is_some()
312        })
313        .map(|datum| datum.y)
314        .collect();
315    let domain = resolve_domain(domain_values, options.domain, options.include_zero);
316    let x_domain = (scale != LineChartScale::Categorical).then(|| {
317        resolve_domain(
318            data.iter().map(|datum| numeric_x(&datum.x, scale)),
319            options.x_domain,
320            false,
321        )
322    });
323    let drawable_width = (options.width - options.padding_left - options.padding_right).max(0.0);
324    let drawable_height = (options.height - options.padding_top - options.padding_bottom).max(0.0);
325    let mut segments: Vec<Vec<GeometryPoint>> = Vec::new();
326    let mut current: Vec<GeometryPoint> = Vec::new();
327
328    for (index, datum) in data.iter().enumerate() {
329        let x = match (scale, x_domain) {
330            (LineChartScale::Categorical, _) => {
331                #[allow(clippy::cast_precision_loss)]
332                let ratio = if data.len() == 1 {
333                    0.5
334                } else {
335                    index as f64 / (data.len().max(2) - 1) as f64
336                };
337
338                Some(options.padding_left + ratio * drawable_width)
339            }
340            (_, Some(x_domain)) => numeric_x(&datum.x, scale).map(|value| {
341                scale_value(
342                    value,
343                    x_domain,
344                    options.padding_left,
345                    options.padding_left + drawable_width,
346                )
347            }),
348            (_, None) => None,
349        };
350
351        match (datum.value(), x) {
352            (Some(value), Some(x)) => current.push(GeometryPoint {
353                datum: datum.clone(),
354                x,
355                y: scale_value(
356                    value,
357                    domain,
358                    options.padding_top + drawable_height,
359                    options.padding_top,
360                ),
361            }),
362            _ => {
363                if !current.is_empty() {
364                    segments.push(std::mem::take(&mut current));
365                }
366            }
367        }
368    }
369
370    if !current.is_empty() {
371        segments.push(current);
372    }
373
374    let baseline = scale_value(
375        domain.min.max(domain.max.min(0.0)),
376        domain,
377        options.height - options.padding_bottom,
378        options.padding_top,
379    );
380
381    LineGeometry {
382        area_paths: segments
383            .iter()
384            .map(|points| area_path(points, baseline))
385            .filter(|path| !path.is_empty())
386            .collect(),
387        domain,
388        path: segments
389            .iter()
390            .map(|points| segment_path(points))
391            .collect::<Vec<_>>()
392            .join(" "),
393        points: segments.into_iter().flatten().collect(),
394    }
395}
396
397/// How a [`BarChart`](crate::BarChart) arranges several series.
398#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
399#[non_exhaustive]
400pub enum BarChartLayout {
401    /// Side by side within each category.
402    #[default]
403    Grouped,
404    /// Stacked, positive values upward and negative values downward.
405    Stacked,
406}
407
408/// Which way the bars of a [`BarChart`](crate::BarChart) grow.
409#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
410pub enum BarChartOrientation {
411    /// Bars grow upward from a horizontal category axis.
412    #[default]
413    Vertical,
414    /// Bars grow rightward from a vertical category axis.
415    Horizontal,
416}
417
418/// `LumenBarGeometryMark`.
419#[derive(Clone, Debug, PartialEq)]
420pub(crate) struct BarMark {
421    pub(crate) category: ChartX,
422    pub(crate) datum_id: Option<String>,
423    pub(crate) height: f64,
424    pub(crate) series_id: String,
425    pub(crate) series_label: String,
426    pub(crate) tone: ChartTone,
427    pub(crate) value: f64,
428    pub(crate) width: f64,
429    pub(crate) x: f64,
430    pub(crate) y: f64,
431}
432
433/// `LumenBarGeometryCategory`.
434#[derive(Clone, Debug, PartialEq)]
435pub(crate) struct BarCategory {
436    pub(crate) category: ChartX,
437    pub(crate) label: String,
438    pub(crate) x: f64,
439    pub(crate) y: f64,
440}
441
442/// Plot margins.
443#[derive(Clone, Copy, Debug, PartialEq)]
444pub(crate) struct Margin {
445    pub(crate) bottom: f64,
446    pub(crate) left: f64,
447    pub(crate) right: f64,
448    pub(crate) top: f64,
449}
450
451/// `LumenBarGeometry`.
452#[derive(Clone, Debug, PartialEq)]
453pub(crate) struct BarGeometry {
454    pub(crate) categories: Vec<BarCategory>,
455    pub(crate) domain: ChartDomain,
456    pub(crate) height: f64,
457    pub(crate) marks: Vec<BarMark>,
458    pub(crate) margin: Margin,
459    /// Value-axis labels for `ticks`, formatted with [`TickFormatter`].
460    pub(crate) tick_labels: Vec<String>,
461    /// Value-axis ticks; the automatic domain starts and ends on one of them.
462    pub(crate) ticks: Vec<f64>,
463    pub(crate) width: f64,
464}
465
466/// `LumenBarGeometryOptions`.
467#[derive(Clone)]
468pub(crate) struct BarGeometryOptions<'a> {
469    pub(crate) axis_font_size: Option<f64>,
470    pub(crate) category_width: Option<f64>,
471    /// Finite bounds are kept exactly; omitted bounds round outward to the next tick.
472    pub(crate) domain: Option<ChartBounds>,
473    pub(crate) format_category: Option<&'a Callback<ChartX, String>>,
474    pub(crate) format_value: Option<&'a Callback<f64, String>>,
475    pub(crate) height: f64,
476    pub(crate) layout: BarChartLayout,
477    pub(crate) orientation: BarChartOrientation,
478    pub(crate) width: f64,
479}
480
481impl Default for BarGeometryOptions<'_> {
482    fn default() -> Self {
483        Self {
484            axis_font_size: None,
485            category_width: None,
486            domain: None,
487            format_category: None,
488            format_value: None,
489            height: 320.0,
490            layout: BarChartLayout::Grouped,
491            orientation: BarChartOrientation::Vertical,
492            width: 640.0,
493        }
494    }
495}
496
497fn index_series(series: &ChartSeries) -> HashMap<String, &ChartDatum> {
498    let mut indexed = HashMap::new();
499
500    for datum in &series.data {
501        indexed.insert(datum.x.key(), datum);
502    }
503
504    indexed
505}
506
507/// Values in a JavaScript `Map`'s insertion order: each key's first position with its last value.
508fn indexed_values(series: &ChartSeries) -> Vec<Option<f64>> {
509    let mut order: Vec<String> = Vec::new();
510    let mut values: HashMap<String, Option<f64>> = HashMap::new();
511
512    for datum in &series.data {
513        let key = datum.x.key();
514
515        if !values.contains_key(&key) {
516            order.push(key.clone());
517        }
518
519        values.insert(key, datum.y);
520    }
521
522    order
523        .into_iter()
524        .map(|key| values.get(&key).copied().flatten())
525        .collect()
526}
527
528/// `getStackedTotals`: the negative and positive stack totals of every category.
529fn stacked_totals(series: &[ChartSeries], categories: &[ChartX]) -> Vec<Option<f64>> {
530    let indexed: Vec<HashMap<String, &ChartDatum>> = series.iter().map(index_series).collect();
531    let mut totals = Vec::new();
532
533    for category in categories {
534        let key = category.key();
535        let mut positive = 0.0;
536        let mut negative = 0.0;
537
538        for item in &indexed {
539            let value = item
540                .get(&key)
541                .and_then(|datum| datum.value())
542                .unwrap_or(0.0);
543
544            if value >= 0.0 {
545                positive += value;
546            } else {
547                negative += value;
548            }
549        }
550
551        totals.push(Some(negative));
552        totals.push(Some(positive));
553    }
554
555    totals
556}
557
558/// `createLumenBarGeometry`.
559#[allow(clippy::too_many_lines)]
560pub(crate) fn bar_geometry(
561    series: &[ChartSeries],
562    options: &BarGeometryOptions<'_>,
563) -> BarGeometry {
564    let width = options.width;
565    let height = options.height;
566    let horizontal = options.orientation == BarChartOrientation::Horizontal;
567    let stacked = options.layout == BarChartLayout::Stacked;
568    let categories = chart_categories(series);
569    let indexed: Vec<HashMap<String, &ChartDatum>> = series.iter().map(index_series).collect();
570    let values: Vec<Option<f64>> = if stacked {
571        stacked_totals(series, &categories)
572    } else {
573        series.iter().flat_map(indexed_values).collect()
574    };
575    let domain = axis_domain(&values, options.domain, true);
576    let ticks = chart_ticks(domain);
577    let tick_labels = format_ticks(&ticks, options.format_value);
578    let margin = if horizontal {
579        let labels: Vec<String> = categories
580            .iter()
581            .map(|category| {
582                category_label(
583                    series,
584                    category,
585                    options.format_category,
586                    LabelContext::Axis,
587                )
588            })
589            .collect();
590
591        Margin {
592            bottom: 24.0,
593            left: options
594                .category_width
595                .unwrap_or_else(|| axis_padding(&labels, 112.0, None))
596                .clamp(64.0, 240.0)
597                .max(64.0),
598            right: 20.0,
599            top: 16.0,
600        }
601    } else {
602        Margin {
603            bottom: 52.0,
604            left: (width - 56.0).min(axis_padding(&tick_labels, 52.0, options.axis_font_size)),
605            right: 16.0,
606            top: 16.0,
607        }
608    };
609    let plot_width = (width - margin.left - margin.right).max(1.0);
610    let plot_height = (height - margin.top - margin.bottom).max(1.0);
611    #[allow(clippy::cast_precision_loss)]
612    let category_size =
613        if horizontal { plot_height } else { plot_width } / categories.len().max(1) as f64;
614    let category_gap = (category_size * 0.24).min(16.0);
615    let usable = (category_size - category_gap).max(1.0);
616    #[allow(clippy::cast_precision_loss)]
617    let series_size = usable / series.len().max(1) as f64;
618    let mut marks = Vec::new();
619    let mut positions = Vec::new();
620
621    for (category_index, category) in categories.iter().enumerate() {
622        #[allow(clippy::cast_precision_loss)]
623        let category_start = if horizontal { margin.top } else { margin.left }
624            + category_index as f64 * category_size
625            + category_gap / 2.0;
626        let mut positive_offset = 0.0;
627        let mut negative_offset = 0.0;
628
629        positions.push(BarCategory {
630            category: category.clone(),
631            label: category_label(
632                series,
633                category,
634                options.format_category,
635                LabelContext::Axis,
636            ),
637            x: if horizontal {
638                margin.left - 8.0
639            } else {
640                category_start + usable / 2.0
641            },
642            y: if horizontal {
643                category_start + usable / 2.0
644            } else {
645                height - 20.0
646            },
647        });
648
649        let key = category.key();
650
651        for (series_index, item) in series.iter().enumerate() {
652            let Some(datum) = indexed[series_index].get(&key) else {
653                continue;
654            };
655            let Some(value) = datum.value() else {
656                continue;
657            };
658            let datum_id = datum.id.clone();
659            let tone = ChartTone::resolve(item.tone, series_index);
660            let start_value = if !stacked {
661                0.0
662            } else if value >= 0.0 {
663                positive_offset
664            } else {
665                negative_offset
666            };
667            let end_value = start_value + value;
668            #[allow(clippy::cast_precision_loss)]
669            let offset = if stacked {
670                0.0
671            } else {
672                series_index as f64 * series_size + 1.0
673            };
674            let thickness = if stacked {
675                usable
676            } else {
677                (series_size - 2.0).max(1.0)
678            };
679
680            if horizontal {
681                let start = scale_value(start_value, domain, margin.left, margin.left + plot_width);
682                let end = scale_value(end_value, domain, margin.left, margin.left + plot_width);
683
684                marks.push(BarMark {
685                    category: category.clone(),
686                    datum_id: datum_id.clone(),
687                    height: thickness,
688                    series_id: item.id.clone(),
689                    series_label: item.label.clone(),
690                    tone,
691                    value,
692                    width: (end - start).abs(),
693                    x: start.min(end),
694                    y: category_start + offset,
695                });
696            } else {
697                let start = scale_value(start_value, domain, margin.top + plot_height, margin.top);
698                let end = scale_value(end_value, domain, margin.top + plot_height, margin.top);
699
700                marks.push(BarMark {
701                    category: category.clone(),
702                    datum_id,
703                    height: (end - start).abs(),
704                    series_id: item.id.clone(),
705                    series_label: item.label.clone(),
706                    tone,
707                    value,
708                    width: thickness,
709                    x: category_start + offset,
710                    y: start.min(end),
711                });
712            }
713
714            if stacked {
715                if value >= 0.0 {
716                    positive_offset += value;
717                } else {
718                    negative_offset += value;
719                }
720            }
721        }
722    }
723
724    BarGeometry {
725        categories: positions,
726        domain,
727        height,
728        marks,
729        margin,
730        tick_labels,
731        ticks,
732        width,
733    }
734}
735
736/// The donut or pie form of a [`PieChart`](crate::PieChart).
737#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
738#[non_exhaustive]
739pub enum PieChartVariant {
740    /// A ring with an optional center label.
741    #[default]
742    Donut,
743    /// A filled circle.
744    Pie,
745}
746
747impl PieChartVariant {
748    /// The variant class.
749    pub fn class_name(self) -> &'static str {
750        match self {
751            Self::Donut => "ui-pie-chart--donut",
752            Self::Pie => "ui-pie-chart--pie",
753        }
754    }
755}
756
757/// `LumenPieGeometrySlice`.
758#[derive(Clone, Debug, PartialEq)]
759pub(crate) struct PieSlice {
760    pub(crate) datum: ChartDatum,
761    pub(crate) label: String,
762    pub(crate) path: String,
763    pub(crate) percentage: f64,
764    pub(crate) tone: ChartTone,
765    pub(crate) value: f64,
766}
767
768/// `LumenPieGeometry`.
769#[derive(Clone, Debug, PartialEq)]
770pub(crate) struct PieGeometry {
771    pub(crate) size: f64,
772    pub(crate) slices: Vec<PieSlice>,
773    pub(crate) total: f64,
774}
775
776fn polar(center: f64, radius: f64, angle: f64) -> (f64, f64) {
777    let radians = (angle * std::f64::consts::PI) / 180.0;
778
779    (
780        center + radians.cos() * radius,
781        center + radians.sin() * radius,
782    )
783}
784
785fn pie_arc(radius: f64, large: bool, sweep: u8, point: (f64, f64)) -> String {
786    format!(
787        "A {} {} 0 {} {sweep} {} {}",
788        js_to_fixed(radius, 3),
789        js_to_fixed(radius, 3),
790        u8::from(large),
791        js_to_fixed(point.0, 3),
792        js_to_fixed(point.1, 3)
793    )
794}
795
796fn move_to(command: &str, point: (f64, f64)) -> String {
797    format!(
798        "{command} {} {}",
799        js_to_fixed(point.0, 3),
800        js_to_fixed(point.1, 3)
801    )
802}
803
804fn full_pie_path(center: f64, outer: f64, inner: f64) -> String {
805    let top = polar(center, outer, -90.0);
806    let bottom = polar(center, outer, 90.0);
807    let mut parts = vec![
808        move_to("M", top),
809        pie_arc(outer, true, 1, bottom),
810        pie_arc(outer, true, 1, top),
811        "Z".to_string(),
812    ];
813
814    if inner != 0.0 {
815        let inner_top = polar(center, inner, -90.0);
816        let inner_bottom = polar(center, inner, 90.0);
817        parts.extend([
818            move_to("M", inner_top),
819            pie_arc(inner, true, 0, inner_bottom),
820            pie_arc(inner, true, 0, inner_top),
821            "Z".to_string(),
822        ]);
823    }
824
825    parts.join(" ")
826}
827
828fn pie_slice_path(center: f64, outer: f64, inner: f64, start: f64, end: f64) -> String {
829    if end - start >= 359.999 {
830        return full_pie_path(center, outer, inner);
831    }
832
833    let outer_start = polar(center, outer, start);
834    let outer_end = polar(center, outer, end);
835    let large = end - start > 180.0;
836
837    if inner == 0.0 {
838        return [
839            move_to("M", (center, center)),
840            move_to("L", outer_start),
841            pie_arc(outer, large, 1, outer_end),
842            "Z".to_string(),
843        ]
844        .join(" ");
845    }
846
847    let inner_start = polar(center, inner, start);
848    let inner_end = polar(center, inner, end);
849
850    [
851        move_to("M", outer_start),
852        pie_arc(outer, large, 1, outer_end),
853        move_to("L", inner_end),
854        pie_arc(inner, large, 0, inner_start),
855        "Z".to_string(),
856    ]
857    .join(" ")
858}
859
860/// Pie data keeps only finite, positive values.
861pub(crate) fn pie_values(data: &[ChartDatum]) -> Vec<ChartDatum> {
862    data.iter()
863        .filter(|datum| datum.value().is_some_and(|value| value > 0.0))
864        .cloned()
865        .collect()
866}
867
868/// `createLumenPieGeometry` with the default 320 size and 12 padding.
869pub(crate) fn pie_geometry(data: &[ChartDatum], variant: PieChartVariant) -> PieGeometry {
870    let size: f64 = 320.0;
871    let padding = 12.0;
872    let center = size / 2.0;
873    let outer = (center - padding).max(0.0);
874    let inner = if variant == PieChartVariant::Pie {
875        0.0
876    } else {
877        outer * 0.58
878    };
879    let available = pie_values(data);
880    let total: f64 = available.iter().filter_map(ChartDatum::value).sum();
881    let mut angle = -90.0;
882    let count = available.len();
883    let slices = available
884        .into_iter()
885        .enumerate()
886        .map(|(index, datum)| {
887            let value = datum.value().unwrap_or(0.0);
888            let percentage = if total == 0.0 { 0.0 } else { value / total };
889            let start = angle;
890            let end = if index == count - 1 {
891                270.0
892            } else {
893                start + percentage * 360.0
894            };
895            angle = end;
896
897            PieSlice {
898                label: datum
899                    .label
900                    .clone()
901                    .or_else(|| datum.x_label.clone())
902                    .unwrap_or_else(|| datum.x.display()),
903                path: pie_slice_path(center, outer, inner, start, end),
904                percentage,
905                tone: ChartTone::resolve(datum.tone, index),
906                value,
907                datum,
908            }
909        })
910        .collect();
911
912    PieGeometry {
913        size,
914        slices,
915        total,
916    }
917}
918
919/// The x scale of a [`ScatterChart`](crate::ScatterChart).
920#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
921#[non_exhaustive]
922pub enum ScatterChartScale {
923    /// Linear numeric x values.
924    #[default]
925    Linear,
926    /// Base-10 logarithmic x values; non-positive values are skipped.
927    Log,
928    /// ISO 8601 dates or millisecond timestamps.
929    Time,
930}
931
932/// A reference line or region drawn behind the points of a [`ScatterChart`](crate::ScatterChart).
933#[derive(Clone, Debug, Default, PartialEq)]
934pub struct ScatterChartReference {
935    /// A unique id.
936    pub id: String,
937    /// The visible label.
938    pub label: String,
939    /// A vertical line (or region start) at this x value.
940    pub x: Option<f64>,
941    /// A horizontal line (or region start) at this y value.
942    pub y: Option<f64>,
943    /// With `y_end`, turns the reference into a region ending at this x value.
944    pub x_end: Option<f64>,
945    /// With `x_end`, turns the reference into a region ending at this y value.
946    pub y_end: Option<f64>,
947}
948
949/// `LumenScatterGeometryPoint`.
950#[derive(Clone, Debug, PartialEq)]
951pub(crate) struct ScatterPoint {
952    pub(crate) datum: ChartDatum,
953    pub(crate) radius: f64,
954    pub(crate) series_id: String,
955    pub(crate) series_label: String,
956    pub(crate) tone: ChartTone,
957    pub(crate) x: f64,
958    pub(crate) y: f64,
959}
960
961/// `LumenChartPlotFrame`: the edges of a chart's plotting area in SVG coordinates.
962#[derive(Clone, Copy, Debug, PartialEq)]
963pub(crate) struct PlotFrame {
964    pub(crate) bottom: f64,
965    pub(crate) left: f64,
966    pub(crate) right: f64,
967    pub(crate) top: f64,
968}
969
970impl PlotFrame {
971    /// The plot of a `width` × `height` chart with per-side `padding`.
972    pub(crate) fn new(width: f64, height: f64, padding: Margin) -> Self {
973        Self {
974            bottom: height - padding.bottom,
975            left: padding.left,
976            right: width - padding.right,
977            top: padding.top,
978        }
979    }
980
981    /// Whether a point lies inside the plot, edges included.
982    pub(crate) fn contains(&self, x: f64, y: f64) -> bool {
983        x >= self.left && x <= self.right && y >= self.top && y <= self.bottom
984    }
985}
986
987/// `LumenScatterGeometry`.
988#[derive(Clone, Debug, PartialEq)]
989pub(crate) struct ScatterGeometry {
990    pub(crate) domain: ChartDomain,
991    pub(crate) height: f64,
992    /// Edges of the plotting area that gridlines, clipping, and references share.
993    pub(crate) plot: PlotFrame,
994    pub(crate) points: Vec<ScatterPoint>,
995    pub(crate) width: f64,
996    pub(crate) x_domain: ChartDomain,
997}
998
999fn scatter_numeric_x(value: &ChartX, scale: ScatterChartScale) -> Option<f64> {
1000    let line_scale = match scale {
1001        ScatterChartScale::Time => LineChartScale::Time,
1002        ScatterChartScale::Linear | ScatterChartScale::Log => LineChartScale::Linear,
1003    };
1004    let numeric = numeric_x(value, line_scale)?;
1005
1006    (scale != ScatterChartScale::Log || numeric > 0.0).then_some(numeric)
1007}
1008
1009fn valid_scatter_domain(domain: ChartDomain, scale: ScatterChartScale) -> bool {
1010    domain.min.is_finite()
1011        && domain.max.is_finite()
1012        && domain.max > domain.min
1013        && (scale != ScatterChartScale::Log || domain.min > 0.0)
1014}
1015
1016/// `scaleLumenScatterX`.
1017pub(crate) fn scale_scatter_x(
1018    value: f64,
1019    domain: ChartDomain,
1020    start: f64,
1021    end: f64,
1022    scale: ScatterChartScale,
1023) -> f64 {
1024    if scale != ScatterChartScale::Log {
1025        return scale_value(value, domain, start, end);
1026    }
1027
1028    if value <= 0.0 || !value.is_finite() {
1029        return f64::NAN;
1030    }
1031
1032    scale_value(
1033        value.log10(),
1034        ChartDomain::new(domain.min.log10(), domain.max.log10()),
1035        start,
1036        end,
1037    )
1038}
1039
1040fn pad_scatter_domain(
1041    domain: ChartDomain,
1042    values: &[f64],
1043    requested: Option<ChartBounds>,
1044    extent: f64,
1045    radius: f64,
1046    scale: ScatterChartScale,
1047) -> ChartDomain {
1048    if values.is_empty() || extent <= 0.0 {
1049        return domain;
1050    }
1051
1052    let log = scale == ScatterChartScale::Log;
1053    let project = |value: f64| if log { value.log10() } else { value };
1054    let from_scale = |value: f64| if log { 10f64.powf(value) } else { value };
1055    let min = project(domain.min);
1056    let max = project(domain.max);
1057    let inset = (radius + 2.0).min(extent / 4.0);
1058    let extra = (max - min) * inset / (extent - 2.0 * inset);
1059    let (bound_min, bound_max) = values
1060        .iter()
1061        .map(|value| project(*value))
1062        .fold((f64::INFINITY, f64::NEG_INFINITY), |(low, high), value| {
1063            (low.min(value), high.max(value))
1064        });
1065    let padded_min = from_scale(min.min(bound_min - extra));
1066    let padded_max = from_scale(max.max(bound_max + extra));
1067    let finite = |value: f64, fallback: f64| {
1068        if value.is_finite() && (!log || value > 0.0) {
1069            value
1070        } else {
1071            fallback
1072        }
1073    };
1074    let requested = requested.unwrap_or_default();
1075
1076    ChartDomain::new(
1077        requested
1078            .min
1079            .unwrap_or_else(|| finite(padded_min, domain.min)),
1080        requested
1081            .max
1082            .unwrap_or_else(|| finite(padded_max, domain.max)),
1083    )
1084}
1085
1086/// `niceLumenScatterDomain`: linear extents end on nice ticks, except at requested bounds; log
1087/// and time axes keep their padded data extents.
1088fn nice_scatter_domain(
1089    domain: ChartDomain,
1090    requested: Option<ChartBounds>,
1091    scale: ScatterChartScale,
1092) -> ChartDomain {
1093    if scale != ScatterChartScale::Linear {
1094        return domain;
1095    }
1096
1097    let nice = nice_domain(domain);
1098    let requested = requested.unwrap_or_default();
1099    let finite = |value: Option<f64>| value.is_some_and(f64::is_finite);
1100
1101    ChartDomain::new(
1102        if finite(requested.min) {
1103            domain.min
1104        } else {
1105            nice.min
1106        },
1107        if finite(requested.max) {
1108            domain.max
1109        } else {
1110            nice.max
1111        },
1112    )
1113}
1114
1115/// The scatter x domain before padding: each requested bound, or the data's extent where a bound
1116/// is missing. An empty log axis spans 1 to 10.
1117fn requested_scatter_x_domain(
1118    x_values: &[f64],
1119    scale: ScatterChartScale,
1120    bounds: Option<ChartBounds>,
1121) -> ChartDomain {
1122    let automatic = if scale == ScatterChartScale::Log && x_values.is_empty() {
1123        ChartDomain::new(1.0, 10.0)
1124    } else {
1125        chart_domain(x_values.iter().copied().map(Some), false)
1126    };
1127    let requested = bounds.unwrap_or_default();
1128
1129    ChartDomain::new(
1130        requested.min.unwrap_or(automatic.min),
1131        requested.max.unwrap_or(automatic.max),
1132    )
1133}
1134
1135/// `createLumenScatterGeometry` with the default 640 × 320 frame and per-side `padding`. Returns
1136/// `None` where lumen-core throws a `RangeError` (an empty, reversed, or non-positive log domain).
1137pub(crate) fn scatter_geometry(
1138    series: &[ChartSeries],
1139    scale: ScatterChartScale,
1140    x_bounds: Option<ChartBounds>,
1141    y_bounds: Option<ChartBounds>,
1142    padding: Margin,
1143    axis_font_size: Option<f64>,
1144    format_value: Option<&Callback<f64, String>>,
1145) -> Option<ScatterGeometry> {
1146    let (width, height) = (640.0, 320.0);
1147    let mut plot = PlotFrame::new(width, height, padding);
1148    let (minimum_radius, maximum_radius): (f64, f64) = (4.0, 18.0);
1149    let projected: Vec<&ChartDatum> = series
1150        .iter()
1151        .flat_map(|item| item.data.iter())
1152        .filter(|datum| scatter_numeric_x(&datum.x, scale).is_some() && datum.value().is_some())
1153        .collect();
1154    let calculated = resolve_domain(projected.iter().map(|datum| datum.y), y_bounds, false);
1155
1156    if !valid_scatter_domain(calculated, ScatterChartScale::Linear) {
1157        return None;
1158    }
1159
1160    let x_values: Vec<f64> = projected
1161        .iter()
1162        .filter_map(|datum| scatter_numeric_x(&datum.x, scale))
1163        .collect();
1164    let calculated_x = requested_scatter_x_domain(&x_values, scale, x_bounds);
1165
1166    if !valid_scatter_domain(calculated_x, scale) {
1167        return None;
1168    }
1169
1170    let size_domain = chart_domain(
1171        projected
1172            .iter()
1173            .map(|datum| datum.size.filter(|size| *size >= 0.0)),
1174        false,
1175    );
1176    let minimum_radius = minimum_radius.max(1.0);
1177    let maximum_radius = maximum_radius.max(minimum_radius);
1178    let y_values: Vec<f64> = projected.iter().filter_map(|datum| datum.y).collect();
1179    let domain = nice_scatter_domain(
1180        pad_scatter_domain(
1181            calculated,
1182            &y_values,
1183            y_bounds,
1184            plot.bottom - plot.top,
1185            maximum_radius,
1186            ScatterChartScale::Linear,
1187        ),
1188        y_bounds,
1189        ScatterChartScale::Linear,
1190    );
1191    if axis_font_size.is_some() {
1192        // Scatter's React adapter always supplies formatY, defaulting to String rather than
1193        // the compact axis formatter used by the other chart families.
1194        let tick_labels: Vec<String> = chart_ticks(domain)
1195            .into_iter()
1196            .map(|tick| format_with(format_value, tick))
1197            .collect();
1198        plot.left = (plot.right - 40.0).min(axis_padding(&tick_labels, plot.left, axis_font_size));
1199    }
1200    let x_domain = nice_scatter_domain(
1201        pad_scatter_domain(
1202            calculated_x,
1203            &x_values,
1204            x_bounds,
1205            plot.right - plot.left,
1206            maximum_radius,
1207            scale,
1208        ),
1209        x_bounds,
1210        scale,
1211    );
1212    let mut points = Vec::new();
1213
1214    for (series_index, item) in series.iter().enumerate() {
1215        for datum in &item.data {
1216            let (Some(numeric), Some(value)) = (scatter_numeric_x(&datum.x, scale), datum.value())
1217            else {
1218                continue;
1219            };
1220            let radius = match datum.size {
1221                Some(size) if size.is_finite() && size >= 0.0 => {
1222                    scale_value(size, size_domain, minimum_radius, maximum_radius)
1223                }
1224                _ => minimum_radius,
1225            };
1226
1227            points.push(ScatterPoint {
1228                datum: datum.clone(),
1229                radius,
1230                series_id: item.id.clone(),
1231                series_label: item.label.clone(),
1232                tone: ChartTone::resolve(datum.tone.or(item.tone), series_index),
1233                x: scale_scatter_x(numeric, x_domain, plot.left, plot.right, scale),
1234                y: scale_value(value, domain, plot.bottom, plot.top),
1235            });
1236        }
1237    }
1238
1239    Some(ScatterGeometry {
1240        domain,
1241        height,
1242        plot,
1243        points,
1244        width,
1245        x_domain,
1246    })
1247}
1248
1249/// `LumenScatterReferenceGeometry`.
1250#[derive(Clone, Debug, PartialEq)]
1251pub(crate) struct ScatterReferenceGeometry {
1252    pub(crate) id: String,
1253    pub(crate) label: String,
1254    pub(crate) region: bool,
1255    pub(crate) x1: f64,
1256    pub(crate) x2: f64,
1257    pub(crate) y1: f64,
1258    pub(crate) y2: f64,
1259}
1260
1261/// `createLumenScatterReferences`: projects references with the geometry's own plot frame and
1262/// skips references with non-finite coordinates.
1263pub(crate) fn scatter_references(
1264    references: &[ScatterChartReference],
1265    geometry: &ScatterGeometry,
1266    scale: ScatterChartScale,
1267) -> Vec<ScatterReferenceGeometry> {
1268    let frame = geometry.plot;
1269    let x = |value: f64| scale_scatter_x(value, geometry.x_domain, frame.left, frame.right, scale);
1270    let y = |value: f64| scale_value(value, geometry.domain, frame.bottom, frame.top);
1271    let finite = |value: Option<f64>| value.is_none_or(f64::is_finite);
1272
1273    references
1274        .iter()
1275        .filter(|reference| {
1276            finite(reference.x)
1277                && finite(reference.y)
1278                && finite(reference.x_end)
1279                && finite(reference.y_end)
1280        })
1281        .filter_map(|reference| {
1282            let x1 = reference.x.map_or(frame.left, x);
1283            let y1 = reference.y.map_or(frame.top, y);
1284            let x2 = reference.x_end.map_or(
1285                if reference.x.is_none() {
1286                    frame.right
1287                } else {
1288                    x1
1289                },
1290                x,
1291            );
1292            let y2 = reference.y_end.map_or(
1293                if reference.y.is_none() {
1294                    frame.bottom
1295                } else {
1296                    y1
1297                },
1298                y,
1299            );
1300
1301            [x1, x2, y1, y2]
1302                .iter()
1303                .all(|value| value.is_finite())
1304                .then(|| ScatterReferenceGeometry {
1305                    id: reference.id.clone(),
1306                    label: reference.label.clone(),
1307                    region: reference.x_end.is_some() && reference.y_end.is_some(),
1308                    x1,
1309                    x2,
1310                    y1,
1311                    y2,
1312                })
1313        })
1314        .collect()
1315}
1316
1317/// One cell of a [`Heatmap`](crate::Heatmap).
1318#[derive(Clone, Debug, PartialEq)]
1319pub struct HeatmapDatum {
1320    /// The column identity.
1321    pub x: ChartX,
1322    /// The row identity.
1323    pub y: ChartX,
1324    /// The measurement. `None` or a non-finite number is a missing cell.
1325    pub value: Option<f64>,
1326    /// A stable id.
1327    pub id: Option<String>,
1328    /// A formatted value label that replaces the formatted value.
1329    pub label: Option<String>,
1330    /// A display label for the column.
1331    pub x_label: Option<String>,
1332    /// A display label for the row.
1333    pub y_label: Option<String>,
1334    /// A tone for consumers that present one.
1335    pub tone: Option<ChartTone>,
1336}
1337
1338impl HeatmapDatum {
1339    /// A cell at column `x` and row `y`.
1340    pub fn new(x: impl Into<ChartX>, y: impl Into<ChartX>, value: impl Into<Option<f64>>) -> Self {
1341        Self {
1342            x: x.into(),
1343            y: y.into(),
1344            value: value.into(),
1345            id: None,
1346            label: None,
1347            x_label: None,
1348            y_label: None,
1349            tone: None,
1350        }
1351    }
1352
1353    /// Sets the stable id.
1354    #[must_use]
1355    pub fn with_id(mut self, id: impl Into<String>) -> Self {
1356        self.id = Some(id.into());
1357        self
1358    }
1359
1360    /// Sets the formatted value label.
1361    #[must_use]
1362    pub fn with_label(mut self, label: impl Into<String>) -> Self {
1363        self.label = Some(label.into());
1364        self
1365    }
1366
1367    /// Sets the column and row display labels.
1368    #[must_use]
1369    pub fn with_axis_labels(
1370        mut self,
1371        x_label: impl Into<String>,
1372        y_label: impl Into<String>,
1373    ) -> Self {
1374        self.x_label = Some(x_label.into());
1375        self.y_label = Some(y_label.into());
1376        self
1377    }
1378
1379    pub(crate) fn finite_value(&self) -> Option<f64> {
1380        self.value.filter(|value| value.is_finite())
1381    }
1382}
1383
1384/// How a [`Heatmap`](crate::Heatmap) maps values to color.
1385#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1386#[non_exhaustive]
1387pub enum HeatmapColorScale {
1388    /// Low to high in one hue.
1389    #[default]
1390    Sequential,
1391    /// Two hues around a midpoint.
1392    Diverging,
1393}
1394
1395/// A positioned heatmap cell.
1396#[derive(Clone, Debug, PartialEq)]
1397pub(crate) struct HeatmapCell {
1398    pub(crate) datum: HeatmapDatum,
1399    pub(crate) height: f64,
1400    pub(crate) width: f64,
1401    pub(crate) x: f64,
1402    pub(crate) y: f64,
1403}
1404
1405/// A heatmap row label.
1406#[derive(Clone, Debug, PartialEq)]
1407pub(crate) struct HeatmapRowTick {
1408    pub(crate) label: String,
1409    pub(crate) position: f64,
1410    pub(crate) value: ChartX,
1411}
1412
1413/// `createLumenHeatmapModel`.
1414#[derive(Clone, Debug, PartialEq)]
1415pub(crate) struct HeatmapModel {
1416    pub(crate) cells: Vec<HeatmapCell>,
1417    pub(crate) domain: ChartDomain,
1418    pub(crate) legend_background: String,
1419    pub(crate) midpoint: f64,
1420    pub(crate) midpoint_percent: f64,
1421    pub(crate) x_ticks: Vec<CategoryTick>,
1422    pub(crate) y_ticks: Vec<HeatmapRowTick>,
1423}
1424
1425/// `resolveDomain` in chart-models: finite requested bounds win when they stay ordered.
1426fn resolve_ordered_domain(automatic: ChartDomain, requested: Option<ChartBounds>) -> ChartDomain {
1427    let requested = requested.unwrap_or_default();
1428    let min = requested
1429        .min
1430        .filter(|value| value.is_finite())
1431        .unwrap_or(automatic.min);
1432    let max = requested
1433        .max
1434        .filter(|value| value.is_finite())
1435        .unwrap_or(automatic.max);
1436
1437    if min < max {
1438        ChartDomain::new(min, max)
1439    } else {
1440        automatic
1441    }
1442}
1443
1444fn heatmap_scale(
1445    automatic: ChartDomain,
1446    color_scale: HeatmapColorScale,
1447    midpoint: f64,
1448    requested: Option<ChartBounds>,
1449) -> (ChartDomain, f64) {
1450    let midpoint = if midpoint.is_finite() { midpoint } else { 0.0 };
1451
1452    if color_scale != HeatmapColorScale::Diverging {
1453        return (resolve_ordered_domain(automatic, requested), midpoint);
1454    }
1455
1456    let radius = (automatic.min - midpoint)
1457        .abs()
1458        .max((automatic.max - midpoint).abs())
1459        .max(1.0);
1460    let symmetric = ChartDomain::new(midpoint - radius, midpoint + radius);
1461    let resolved = resolve_ordered_domain(symmetric, requested);
1462    let finite = |domain: ChartDomain| domain.min.is_finite() && domain.max.is_finite();
1463
1464    if finite(resolved) && resolved.min < midpoint && resolved.max > midpoint {
1465        return (resolved, midpoint);
1466    }
1467
1468    if finite(symmetric) {
1469        return (symmetric, midpoint);
1470    }
1471
1472    let fallback = automatic.min.abs().max(automatic.max.abs()).max(1.0);
1473
1474    (ChartDomain::new(-fallback, fallback), 0.0)
1475}
1476
1477fn unique_categories<'a>(values: impl Iterator<Item = &'a ChartX>) -> Vec<ChartX> {
1478    let mut seen = HashSet::new();
1479    let mut categories = Vec::new();
1480
1481    for value in values {
1482        if seen.insert(value.key()) {
1483            categories.push(value.clone());
1484        }
1485    }
1486
1487    categories
1488}
1489
1490/// `createLumenHeatmapModel`: one cell per coordinate (first wins), on a 496 × 248 grid offset by
1491/// 120 × 24 inside a 640 × 320 frame. Cells with a non-finite coordinate make the data invalid.
1492pub(crate) fn heatmap_model(
1493    data: &[HeatmapDatum],
1494    color_scale: HeatmapColorScale,
1495    midpoint: f64,
1496    domain: Option<ChartBounds>,
1497) -> HeatmapModel {
1498    let valid = data
1499        .iter()
1500        .all(|datum| datum.x.is_axis_value() && datum.y.is_axis_value());
1501    let mut seen = HashSet::new();
1502    let cells: Vec<&HeatmapDatum> = if valid {
1503        data.iter()
1504            .filter(|datum| seen.insert(format!("{}|{}", datum.x.json(), datum.y.json())))
1505            .collect()
1506    } else {
1507        Vec::new()
1508    };
1509    let x_categories = unique_categories(cells.iter().map(|cell| &cell.x));
1510    let y_categories = unique_categories(cells.iter().map(|cell| &cell.y));
1511    #[allow(clippy::cast_precision_loss)]
1512    let cell_width = 496.0 / x_categories.len().max(1) as f64;
1513    #[allow(clippy::cast_precision_loss)]
1514    let cell_height = 248.0 / y_categories.len().max(1) as f64;
1515    let x_index: HashMap<String, usize> = x_categories
1516        .iter()
1517        .enumerate()
1518        .map(|(index, category)| (category.key(), index))
1519        .collect();
1520    let y_index: HashMap<String, usize> = y_categories
1521        .iter()
1522        .enumerate()
1523        .map(|(index, category)| (category.key(), index))
1524        .collect();
1525    let automatic = chart_domain(cells.iter().map(|cell| cell.finite_value()), false);
1526    let (domain, midpoint) = heatmap_scale(automatic, color_scale, midpoint, domain);
1527    let midpoint_percent = scale_value(midpoint, domain, 0.0, 100.0);
1528    let label_for_x = |value: &ChartX| {
1529        cells
1530            .iter()
1531            .find(|cell| cell.x == *value)
1532            .and_then(|cell| cell.x_label.clone())
1533            .unwrap_or_else(|| value.display())
1534    };
1535    let label_for_y = |value: &ChartX| {
1536        cells
1537            .iter()
1538            .find(|cell| cell.y == *value)
1539            .and_then(|cell| cell.y_label.clone())
1540            .unwrap_or_else(|| value.display())
1541    };
1542    #[allow(clippy::cast_precision_loss)]
1543    let column_positions: Vec<f64> = (0..x_categories.len())
1544        .map(|index| 120.0 + (index as f64 + 0.5) * 496.0 / x_categories.len() as f64)
1545        .collect();
1546    let column_labels: Vec<String> = x_categories.iter().map(label_for_x).collect();
1547    let x_ticks = category_ticks(
1548        &column_labels,
1549        CategoryTickOptions::new(120.0, 616.0)
1550            .bounds(0.0, 640.0)
1551            .positions(&column_positions),
1552    );
1553    #[allow(clippy::cast_precision_loss)]
1554    let y_ticks = y_categories
1555        .iter()
1556        .enumerate()
1557        .map(|(index, value)| HeatmapRowTick {
1558            label: fitted_label(&label_for_y(value), 104.0),
1559            position: 24.0 + (index as f64 + 0.5) * 248.0 / y_categories.len() as f64,
1560            value: value.clone(),
1561        })
1562        .collect();
1563    #[allow(clippy::cast_precision_loss)]
1564    let positioned = cells
1565        .iter()
1566        .filter_map(|datum| {
1567            let column = x_index.get(&datum.x.key())?;
1568            let row = y_index.get(&datum.y.key())?;
1569
1570            Some(HeatmapCell {
1571                datum: (*datum).clone(),
1572                height: cell_height,
1573                width: cell_width,
1574                x: *column as f64 * cell_width + 120.0,
1575                y: *row as f64 * cell_height + 24.0,
1576            })
1577        })
1578        .collect();
1579    let legend_background = if color_scale == HeatmapColorScale::Diverging {
1580        format!(
1581            "linear-gradient(to right, hsl(var(--chart-diverging-negative)), hsl(var(--chart-diverging-mid)) {}%, hsl(var(--chart-diverging-positive)))",
1582            js_number(midpoint_percent)
1583        )
1584    } else {
1585        "linear-gradient(to right, hsl(var(--chart-sequential-low)), hsl(var(--chart-sequential-high)))".to_string()
1586    };
1587
1588    HeatmapModel {
1589        cells: positioned,
1590        domain,
1591        legend_background,
1592        midpoint,
1593        midpoint_percent,
1594        x_ticks,
1595        y_ticks,
1596    }
1597}
1598
1599/// `getLumenHeatmapColor`: a `color-mix()` fill from the chart color tokens.
1600pub(crate) fn heatmap_color(
1601    value: Option<f64>,
1602    domain: ChartDomain,
1603    color_scale: HeatmapColorScale,
1604    midpoint: f64,
1605) -> String {
1606    let Some(value) = value.filter(|value| value.is_finite()) else {
1607        return "hsl(var(--surface-muted))".to_string();
1608    };
1609    let ratio = |start: f64, end: f64| {
1610        if js_equals(end, start) {
1611            0.5
1612        } else {
1613            value_ratio(value, ChartDomain::new(start, end))
1614        }
1615    };
1616    let (overlay, base, amount) = if color_scale == HeatmapColorScale::Diverging {
1617        if value < midpoint {
1618            (
1619                "diverging-negative",
1620                "diverging-mid",
1621                1.0 - ratio(domain.min, midpoint),
1622            )
1623        } else {
1624            (
1625                "diverging-positive",
1626                "diverging-mid",
1627                ratio(midpoint, domain.max),
1628            )
1629        }
1630    } else {
1631        (
1632            "sequential-high",
1633            "sequential-low",
1634            ratio(domain.min, domain.max),
1635        )
1636    };
1637
1638    format!(
1639        "color-mix(in srgb, hsl(var(--chart-{overlay})) {}%, hsl(var(--chart-{base})))",
1640        js_number(amount * 100.0)
1641    )
1642}
1643
1644/// One interval of a [`RangeChart`](crate::RangeChart).
1645#[derive(Clone, Debug, PartialEq)]
1646pub struct RangeChartDatum {
1647    /// The x identity.
1648    pub x: ChartX,
1649    /// The lower value; `None` or non-finite breaks the band.
1650    pub low: Option<f64>,
1651    /// The upper value; `None` or non-finite breaks the band.
1652    pub high: Option<f64>,
1653    /// A stable id.
1654    pub id: Option<String>,
1655    /// A formatted label that replaces the formatted range.
1656    pub label: Option<String>,
1657    /// A display label for `x`.
1658    pub x_label: Option<String>,
1659}
1660
1661impl RangeChartDatum {
1662    /// An interval at `x` from `low` to `high`.
1663    pub fn new(
1664        x: impl Into<ChartX>,
1665        low: impl Into<Option<f64>>,
1666        high: impl Into<Option<f64>>,
1667    ) -> Self {
1668        Self {
1669            x: x.into(),
1670            low: low.into(),
1671            high: high.into(),
1672            id: None,
1673            label: None,
1674            x_label: None,
1675        }
1676    }
1677
1678    /// Sets the stable id.
1679    #[must_use]
1680    pub fn with_id(mut self, id: impl Into<String>) -> Self {
1681        self.id = Some(id.into());
1682        self
1683    }
1684
1685    /// Sets the formatted label.
1686    #[must_use]
1687    pub fn with_label(mut self, label: impl Into<String>) -> Self {
1688        self.label = Some(label.into());
1689        self
1690    }
1691
1692    /// Sets the x display label.
1693    #[must_use]
1694    pub fn with_x_label(mut self, label: impl Into<String>) -> Self {
1695        self.x_label = Some(label.into());
1696        self
1697    }
1698}
1699
1700/// A positioned range interval.
1701#[derive(Clone, Debug, PartialEq)]
1702pub(crate) struct RangePoint {
1703    pub(crate) datum: RangeChartDatum,
1704    pub(crate) high: f64,
1705    pub(crate) low: f64,
1706    pub(crate) x: f64,
1707}
1708
1709/// `LumenRangeGeometry`.
1710#[derive(Clone, Debug, PartialEq)]
1711pub(crate) struct RangeGeometry {
1712    pub(crate) area_path: String,
1713    pub(crate) domain: ChartDomain,
1714    /// The frame gridlines span; points sit [`RANGE_INSET`] inside its left and right edges.
1715    pub(crate) plot: PlotFrame,
1716    pub(crate) points: Vec<RangePoint>,
1717    /// Value-axis ticks; the automatic domain starts and ends on one of them.
1718    pub(crate) ticks: Vec<f64>,
1719}
1720
1721/// `defaultLumenRangeInset`: keeps the first and last intervals and their labels centred.
1722const RANGE_INSET: f64 = 8.0;
1723
1724/// `createLumenRangeGeometry` with per-side `padding`: automatic value bounds round outward
1725/// to nice ticks. The chart adapter validates its coordinate dimensions before calling this.
1726pub(crate) fn range_geometry(
1727    data: &[RangeChartDatum],
1728    padding: Margin,
1729    width: f64,
1730    height: f64,
1731    axis_font_size: Option<f64>,
1732    format_value: Option<&Callback<f64, String>>,
1733) -> RangeGeometry {
1734    let finite = |datum: &RangeChartDatum| match (
1735        datum.low.filter(|v| v.is_finite()),
1736        datum.high.filter(|v| v.is_finite()),
1737    ) {
1738        (Some(low), Some(high)) => Some((low, high)),
1739        _ => None,
1740    };
1741    let values: Vec<Option<f64>> = data
1742        .iter()
1743        .filter_map(finite)
1744        .flat_map(|(low, high)| [Some(low), Some(high)])
1745        .collect();
1746    let domain = axis_domain(&values, None, false);
1747    let mut plot = PlotFrame::new(width, height, padding);
1748    if axis_font_size.is_some() {
1749        let tick_labels = format_ticks(&chart_ticks(domain), format_value);
1750        plot.left = (plot.right - 40.0).min(axis_padding(&tick_labels, plot.left, axis_font_size));
1751    }
1752    let inset = resolve_inset(Some(RANGE_INSET), plot.right - plot.left);
1753    let (point_left, point_right) = (plot.left + inset, plot.right - inset);
1754    let mut segments: Vec<Vec<RangePoint>> = Vec::new();
1755    let mut current: Vec<RangePoint> = Vec::new();
1756
1757    for (index, datum) in data.iter().enumerate() {
1758        let Some((low, high)) = finite(datum) else {
1759            if !current.is_empty() {
1760                segments.push(std::mem::take(&mut current));
1761            }
1762
1763            continue;
1764        };
1765        #[allow(clippy::cast_precision_loss)]
1766        let ratio = if data.len() == 1 {
1767            0.5
1768        } else {
1769            index as f64 / (data.len().max(2) - 1) as f64
1770        };
1771
1772        current.push(RangePoint {
1773            datum: datum.clone(),
1774            high: scale_value(high, domain, plot.bottom, plot.top),
1775            low: scale_value(low, domain, plot.bottom, plot.top),
1776            x: point_left + ratio * (point_right - point_left),
1777        });
1778    }
1779
1780    if !current.is_empty() {
1781        segments.push(current);
1782    }
1783
1784    let area_path = segments
1785        .iter()
1786        .map(|segment| {
1787            let mut parts: Vec<String> = segment
1788                .iter()
1789                .enumerate()
1790                .map(|(index, point)| {
1791                    format!(
1792                        "{} {} {}",
1793                        if index == 0 { "M" } else { "L" },
1794                        js_to_fixed(point.x, 3),
1795                        js_to_fixed(point.high, 3)
1796                    )
1797                })
1798                .collect();
1799            parts.extend(segment.iter().rev().map(|point| {
1800                format!(
1801                    "L {} {}",
1802                    js_to_fixed(point.x, 3),
1803                    js_to_fixed(point.low, 3)
1804                )
1805            }));
1806            parts.push("Z".to_string());
1807            parts.join(" ")
1808        })
1809        .collect::<Vec<_>>()
1810        .join(" ");
1811
1812    RangeGeometry {
1813        area_path,
1814        domain,
1815        plot,
1816        points: segments.into_iter().flatten().collect(),
1817        ticks: chart_ticks(domain),
1818    }
1819}
1820
1821/// Which axis a [`LineChartAnnotation`] marks.
1822#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1823pub enum LineChartAnnotationAxis {
1824    /// A horizontal line at a y value.
1825    #[default]
1826    Y,
1827    /// A vertical line at an x identity.
1828    X,
1829}
1830
1831/// A labelled reference line on a [`LineChart`](crate::LineChart).
1832#[derive(Clone, Debug, PartialEq)]
1833pub struct LineChartAnnotation {
1834    /// A unique id; later duplicates are ignored.
1835    pub id: String,
1836    /// The visible label.
1837    pub label: String,
1838    /// A y value, or an x identity when `axis` is `X`.
1839    pub value: ChartX,
1840    /// The marked axis.
1841    pub axis: LineChartAnnotationAxis,
1842    /// The line color.
1843    pub tone: Option<ChartTone>,
1844}
1845
1846impl LineChartAnnotation {
1847    /// A horizontal annotation at y `value`.
1848    pub fn y(id: impl Into<String>, label: impl Into<String>, value: f64) -> Self {
1849        Self {
1850            id: id.into(),
1851            label: label.into(),
1852            value: ChartX::Number(value),
1853            axis: LineChartAnnotationAxis::Y,
1854            tone: None,
1855        }
1856    }
1857
1858    /// A vertical annotation at the x identity `value`.
1859    pub fn x(id: impl Into<String>, label: impl Into<String>, value: impl Into<ChartX>) -> Self {
1860        Self {
1861            id: id.into(),
1862            label: label.into(),
1863            value: value.into(),
1864            axis: LineChartAnnotationAxis::X,
1865            tone: None,
1866        }
1867    }
1868
1869    /// Sets the tone.
1870    #[must_use]
1871    pub fn with_tone(mut self, tone: ChartTone) -> Self {
1872        self.tone = Some(tone);
1873        self
1874    }
1875}
1876
1877/// A positioned annotation.
1878#[derive(Clone, Debug, PartialEq)]
1879pub(crate) struct AnnotationMark {
1880    pub(crate) annotation: LineChartAnnotation,
1881    pub(crate) coordinate: f64,
1882}
1883
1884/// `LumenChartRect`: a rectangle in SVG user units.
1885#[derive(Clone, Copy, Debug, PartialEq)]
1886pub(crate) struct ChartRect {
1887    pub(crate) height: f64,
1888    pub(crate) width: f64,
1889    pub(crate) x: f64,
1890    pub(crate) y: f64,
1891}
1892
1893/// `createLumenLineChartModel`.
1894#[derive(Clone, Debug, PartialEq)]
1895pub(crate) struct LineChartModel {
1896    pub(crate) annotation_marks: Vec<AnnotationMark>,
1897    pub(crate) categories: Vec<ChartX>,
1898    pub(crate) category_ticks: Vec<CategoryTick>,
1899    /// The plot extended vertically by a marker's reach, for the clipping viewport.
1900    pub(crate) clip: ChartRect,
1901    pub(crate) domain: ChartDomain,
1902    pub(crate) geometries: Vec<LineGeometry>,
1903    pub(crate) height: f64,
1904    /// Space between the plot edges and the first and last points.
1905    pub(crate) inset: f64,
1906    pub(crate) padding_bottom: f64,
1907    pub(crate) padding_left: f64,
1908    pub(crate) padding_right: f64,
1909    pub(crate) padding_top: f64,
1910    pub(crate) positions: Vec<f64>,
1911    pub(crate) series: Vec<ChartSeries>,
1912    pub(crate) tick_labels: Vec<String>,
1913    pub(crate) ticks: Vec<f64>,
1914    pub(crate) width: f64,
1915}
1916
1917/// Room above the top gridline for its centred tick label.
1918const LINE_PADDING_TOP: f64 = 16.0;
1919/// Extra room above the plot for x-axis annotation labels.
1920const LINE_ANNOTATION_LABEL_SPACE: f64 = 16.0;
1921/// Room right of the plot for the final category label, centred on its inset point.
1922const LINE_PADDING_RIGHT: f64 = 24.0;
1923/// Room below the plot for category labels, including the larger compact-width label size.
1924const LINE_PADDING_BOTTOM: f64 = 44.0;
1925/// Keeps the first and last points (and their centred labels) clear of the plot edges.
1926const LINE_PLOT_INSET: f64 = 8.0;
1927/// Lets markers and strokes on the top and bottom gridlines draw outside the plot clip.
1928const LINE_MARKER_ALLOWANCE: f64 = 6.0;
1929/// Web line, range, and interval charts draw axis text at 1.375rem in compact containers.
1930pub(crate) const COMPACT_AXIS_LABEL_SIZE: f64 = 22.0;
1931
1932/// `LumenLineChartOptions`.
1933#[derive(Clone, Default)]
1934pub(crate) struct LineChartModelOptions<'a> {
1935    pub(crate) annotations: &'a [LineChartAnnotation],
1936    pub(crate) domain: Option<ChartBounds>,
1937    pub(crate) format_category: Option<&'a Callback<ChartX, String>>,
1938    pub(crate) format_value: Option<&'a Callback<f64, String>>,
1939    pub(crate) height: Option<f64>,
1940    pub(crate) reference_value: Option<f64>,
1941    pub(crate) width: Option<f64>,
1942    pub(crate) x_domain: Option<ChartBounds>,
1943    pub(crate) x_scale: LineChartScale,
1944}
1945
1946/// `SameValueZero`, the equality of JavaScript `Map` keys: like `===`, but `NaN` equals `NaN`.
1947fn same_value_zero(a: &ChartX, b: &ChartX) -> bool {
1948    match (a, b) {
1949        (ChartX::Number(left), ChartX::Number(right)) => {
1950            js_equals(*left, *right) || (left.is_nan() && right.is_nan())
1951        }
1952        _ => a == b,
1953    }
1954}
1955
1956pub(crate) fn chart_size(value: Option<f64>, fallback: f64) -> f64 {
1957    match value {
1958        Some(value) if value.is_finite() => value.max(240.0),
1959        _ => fallback,
1960    }
1961}
1962
1963/// `createLumenLineChartModel`: aligns every series to the same categories and frame.
1964#[allow(clippy::too_many_lines)]
1965pub(crate) fn line_chart_model(
1966    input: &[ChartSeries],
1967    options: &LineChartModelOptions<'_>,
1968) -> LineChartModel {
1969    let scale = options.x_scale;
1970    let width = chart_size(options.width, 640.0);
1971    let height = chart_size(options.height, 240.0);
1972    let mut categories: Vec<ChartX> = chart_categories(input)
1973        .into_iter()
1974        .filter(|value| scale == LineChartScale::Categorical || numeric_x(value, scale).is_some())
1975        .collect();
1976
1977    if scale != LineChartScale::Categorical {
1978        // A stable sort on the numeric difference, like `Array.prototype.sort` in lumen-core.
1979        categories.sort_by(|a, b| {
1980            numeric_x(a, scale)
1981                .unwrap_or(0.0)
1982                .partial_cmp(&numeric_x(b, scale).unwrap_or(0.0))
1983                .unwrap_or(std::cmp::Ordering::Equal)
1984        });
1985    }
1986
1987    let series: Vec<ChartSeries> = input
1988        .iter()
1989        .map(|item| align_series(item, &categories))
1990        .collect();
1991    let mut annotation_ids = HashSet::new();
1992    let annotations: Vec<&LineChartAnnotation> = options
1993        .annotations
1994        .iter()
1995        .filter(|annotation| annotation.value.is_axis_value())
1996        .filter(|annotation| annotation_ids.insert(annotation.id.clone()))
1997        .collect();
1998    let values: Vec<Option<f64>> = series
1999        .iter()
2000        .flat_map(|item| item.data.iter().map(|datum| datum.y))
2001        .chain(std::iter::once(options.reference_value))
2002        .collect();
2003    // Finite requested bounds are kept exactly; the automatic sides end on nice ticks.
2004    let domain = resolve_ordered_domain(
2005        axis_domain(&values, None, false),
2006        Some(axis_domain(&values, options.domain, false).into()),
2007    );
2008    let ticks = chart_ticks(domain);
2009    let tick_labels = format_ticks(&ticks, options.format_value);
2010    let has_x_annotation = annotations
2011        .iter()
2012        .any(|annotation| annotation.axis == LineChartAnnotationAxis::X);
2013    let padding_top = LINE_PADDING_TOP
2014        + if has_x_annotation {
2015            LINE_ANNOTATION_LABEL_SPACE
2016        } else {
2017            0.0
2018        };
2019    let category_labels: Vec<String> = categories
2020        .iter()
2021        .map(|value| category_label(&series, value, options.format_category, LabelContext::Axis))
2022        .collect();
2023    // Edge category labels stay centred on their points even at the compact label size, so the
2024    // outer padding grows (within a fifth of the chart) instead of the labels shifting inward.
2025    let edge_label_reach = |label: Option<&String>| {
2026        (width / 5.0).min(
2027            estimate_chart_label_width(label.map_or("", String::as_str), COMPACT_AXIS_LABEL_SIZE)
2028                / 2.0
2029                - LINE_PLOT_INSET,
2030        )
2031    };
2032    let padding_right = LINE_PADDING_RIGHT.max(edge_label_reach(category_labels.last()));
2033    let padding_bottom = LINE_PADDING_BOTTOM;
2034    // Compact containers draw tick labels at twice the regular size, so reserve that width plus
2035    // the 8-unit label offset instead of doubling a fixed minimum gutter.
2036    let padding_left = (width - padding_right - 40.0).min(
2037        40f64
2038            .max(axis_padding(
2039                &tick_labels,
2040                0.0,
2041                Some(COMPACT_AXIS_LABEL_SIZE),
2042            ))
2043            .max(edge_label_reach(category_labels.first())),
2044    );
2045    let plot_right = width - padding_right;
2046    let plot_bottom = height - padding_bottom;
2047    let inset = LINE_PLOT_INSET.min((plot_right - padding_left).max(0.0) / 4.0);
2048    let point_start = padding_left + inset;
2049    let point_end = plot_right - inset;
2050    let numeric: Vec<Option<f64>> = categories
2051        .iter()
2052        .filter_map(|value| {
2053            (scale != LineChartScale::Categorical)
2054                .then(|| numeric_x(value, scale))
2055                .flatten()
2056                .map(Some)
2057        })
2058        .collect();
2059    let x_domain = resolve_ordered_domain(chart_domain(numeric, false), options.x_domain);
2060    let category_count = categories.len();
2061    let position_for = |value: &ChartX| -> Option<f64> {
2062        if scale != LineChartScale::Categorical {
2063            return numeric_x(value, scale)
2064                .map(|number| scale_value(number, x_domain, point_start, point_end));
2065        }
2066
2067        let index = categories
2068            .iter()
2069            .position(|category| same_value_zero(category, value))?;
2070        #[allow(clippy::cast_precision_loss)]
2071        let ratio = if category_count == 1 {
2072            0.5
2073        } else {
2074            index as f64 / category_count.saturating_sub(1).max(1) as f64
2075        };
2076
2077        Some(point_start + ratio * (point_end - point_start))
2078    };
2079    let positions: Vec<f64> = categories
2080        .iter()
2081        .map(|value| position_for(value).unwrap_or(point_start))
2082        .collect();
2083    let geometries = series
2084        .iter()
2085        .map(|item| {
2086            let geometry_options = LineGeometryOptions {
2087                domain: Some(domain.into()),
2088                height,
2089                include_zero: false,
2090                inset: Some(inset),
2091                padding_bottom,
2092                padding_left,
2093                padding_right,
2094                padding_top,
2095                width,
2096                x_domain: Some(x_domain.into()),
2097                x_scale: scale,
2098            };
2099
2100            line_geometry(&item.data, geometry_options)
2101        })
2102        .collect();
2103    // Categories outside an explicit x viewport keep their data but get no axis label.
2104    let visible: Vec<(usize, f64)> = positions
2105        .iter()
2106        .enumerate()
2107        .filter(|(_, position)| **position >= padding_left && **position <= plot_right)
2108        .map(|(index, position)| (index, *position))
2109        .collect();
2110    let visible_labels: Vec<&str> = visible
2111        .iter()
2112        .map(|(index, _)| category_labels[*index].as_str())
2113        .collect();
2114    let visible_positions: Vec<f64> = visible.iter().map(|(_, position)| *position).collect();
2115    let category_ticks = category_ticks(
2116        &visible_labels,
2117        CategoryTickOptions::new(padding_left, plot_right)
2118            .bounds(0.0, width)
2119            .maximum_font_size(COMPACT_AXIS_LABEL_SIZE)
2120            .positions(&visible_positions),
2121    )
2122    .into_iter()
2123    .map(|tick| CategoryTick {
2124        index: visible
2125            .get(tick.index)
2126            .map_or(tick.index, |(index, _)| *index),
2127        ..tick
2128    })
2129    .collect();
2130    let annotation_marks = annotations
2131        .into_iter()
2132        .filter_map(|annotation| {
2133            let coordinate = match annotation.axis {
2134                LineChartAnnotationAxis::X => position_for(&annotation.value)?,
2135                LineChartAnnotationAxis::Y => match annotation.value {
2136                    ChartX::Number(value) if value.is_finite() => {
2137                        scale_value(value, domain, plot_bottom, padding_top)
2138                    }
2139                    _ => return None,
2140                },
2141            };
2142            let in_bounds = match annotation.axis {
2143                LineChartAnnotationAxis::X => {
2144                    coordinate >= padding_left && coordinate <= plot_right
2145                }
2146                LineChartAnnotationAxis::Y => {
2147                    coordinate >= padding_top && coordinate <= plot_bottom
2148                }
2149            };
2150
2151            in_bounds.then(|| AnnotationMark {
2152                annotation: annotation.clone(),
2153                coordinate,
2154            })
2155        })
2156        .collect();
2157    let marker_allowance = LINE_MARKER_ALLOWANCE.min(padding_top);
2158    let clip = ChartRect {
2159        height: (plot_bottom - padding_top).max(0.0) + marker_allowance * 2.0,
2160        width: (plot_right - padding_left).max(0.0),
2161        x: padding_left,
2162        y: padding_top - marker_allowance,
2163    };
2164
2165    LineChartModel {
2166        annotation_marks,
2167        categories,
2168        category_ticks,
2169        clip,
2170        domain,
2171        geometries,
2172        height,
2173        inset,
2174        padding_bottom,
2175        padding_left,
2176        padding_right,
2177        padding_top,
2178        positions,
2179        series,
2180        tick_labels,
2181        ticks,
2182        width,
2183    }
2184}
2185
2186#[cfg(test)]
2187mod tests {
2188    use super::{
2189        BarChartLayout, BarChartOrientation, BarGeometryOptions, ChartRect, HeatmapColorScale,
2190        HeatmapDatum, LineChartAnnotation, LineChartModelOptions, LineChartScale,
2191        LineGeometryOptions, Margin, PieChartVariant, PlotFrame, RangeChartDatum,
2192        ScatterChartReference, ScatterChartScale, bar_geometry, heatmap_color, heatmap_model,
2193        line_chart_model, line_geometry, numeric_x, parse_iso_timestamp, pie_geometry,
2194        range_geometry, scatter_geometry, scatter_references,
2195    };
2196    use crate::charts::model::{ChartBounds, ChartDatum, ChartDomain, ChartSeries, ChartX};
2197
2198    fn uniform(padding: f64) -> Margin {
2199        Margin {
2200            bottom: padding,
2201            left: padding,
2202            right: padding,
2203            top: padding,
2204        }
2205    }
2206
2207    fn react_frame() -> Margin {
2208        Margin {
2209            top: 16.0,
2210            right: 24.0,
2211            ..uniform(44.0)
2212        }
2213    }
2214
2215    fn sparkline(values: &[f64]) -> super::LineGeometry {
2216        let data: Vec<ChartDatum> = values
2217            .iter()
2218            .enumerate()
2219            .map(|(index, value)| ChartDatum::new(i32::try_from(index).unwrap_or(0), *value))
2220            .collect();
2221
2222        line_geometry(&data, LineGeometryOptions::new(120.0, 40.0, 3.0))
2223    }
2224
2225    #[test]
2226    fn line_paths_use_fixed_coordinates_and_break_at_gaps() {
2227        let geometry = sparkline(&[1.0, 3.0, 2.0]);
2228        assert_eq!(
2229            geometry.path,
2230            "M 3.000 37.000 L 60.000 3.000 L 117.000 20.000"
2231        );
2232        let data = vec![
2233            ChartDatum::new("a", 1.0),
2234            ChartDatum::missing("b"),
2235            ChartDatum::new("c", f64::NAN),
2236            ChartDatum::new("d", 2.0),
2237            ChartDatum::new("e", 4.0),
2238        ];
2239        let gapped = line_geometry(&data, LineGeometryOptions::new(100.0, 100.0, 4.0));
2240        assert_eq!(gapped.path.matches('M').count(), 2);
2241        assert_eq!(gapped.area_paths.len(), 2);
2242        assert_eq!(gapped.points.len(), 3);
2243    }
2244
2245    #[test]
2246    fn line_edge_cases_stay_finite() {
2247        assert_eq!(sparkline(&[]).path, "");
2248        let single = sparkline(&[5.0]);
2249        assert_eq!(single.path, "M 60.000 20.000");
2250        let negative = sparkline(&[-4.0, -1.0]);
2251        assert!(negative.points.iter().all(|point| point.y.is_finite()));
2252        let flat = sparkline(&[2.0, 2.0, 2.0]);
2253        assert!(
2254            flat.points
2255                .iter()
2256                .all(|point| (point.y - 20.0).abs() < 1e-9)
2257        );
2258    }
2259
2260    #[test]
2261    fn bars_stack_positive_and_negative_values() {
2262        let series = vec![
2263            ChartSeries::new(
2264                "a",
2265                "A",
2266                [ChartDatum::new("x", 4.0), ChartDatum::new("y", -2.0)],
2267            ),
2268            ChartSeries::new(
2269                "b",
2270                "B",
2271                [ChartDatum::new("x", 6.0), ChartDatum::missing("y")],
2272            ),
2273        ];
2274        let grouped = bar_geometry(&series, &BarGeometryOptions::default());
2275        assert_eq!(grouped.marks.len(), 3);
2276        assert_eq!(grouped.domain, ChartDomain::new(-2.0, 6.0));
2277        assert_eq!(grouped.ticks, vec![-2.0, 0.0, 2.0, 4.0, 6.0]);
2278        assert_eq!(grouped.tick_labels, ["-2", "0", "2", "4", "6"]);
2279        let stacked = bar_geometry(
2280            &series,
2281            &BarGeometryOptions {
2282                layout: BarChartLayout::Stacked,
2283                ..BarGeometryOptions::default()
2284            },
2285        );
2286        // The stack totals of -2 and 10 round out to the nearest ticks.
2287        assert_eq!(stacked.domain, ChartDomain::new(-5.0, 10.0));
2288        assert_eq!(stacked.ticks, vec![-5.0, 0.0, 5.0, 10.0]);
2289        let horizontal = bar_geometry(
2290            &series,
2291            &BarGeometryOptions {
2292                orientation: BarChartOrientation::Horizontal,
2293                ..BarGeometryOptions::default()
2294            },
2295        );
2296        assert!((horizontal.margin.left - 112.0).abs() < 1e-9);
2297        assert_eq!(bar_geometry(&[], &BarGeometryOptions::default()).marks, []);
2298    }
2299
2300    #[test]
2301    fn bars_round_automatic_domains_and_keep_requested_ones() {
2302        let series = vec![ChartSeries::new(
2303            "downloads",
2304            "Downloads",
2305            [ChartDatum::new("Lumen", 18_420.0)],
2306        )];
2307        let bars = bar_geometry(
2308            &series,
2309            &BarGeometryOptions {
2310                orientation: BarChartOrientation::Horizontal,
2311                ..BarGeometryOptions::default()
2312            },
2313        );
2314
2315        assert_eq!(bars.domain, ChartDomain::new(0.0, 20_000.0));
2316        assert_eq!(bars.ticks, vec![0.0, 5_000.0, 10_000.0, 15_000.0, 20_000.0]);
2317        assert_eq!(bars.tick_labels, ["0", "5K", "10K", "15K", "20K"]);
2318
2319        let exact = bar_geometry(
2320            &series,
2321            &BarGeometryOptions {
2322                domain: Some(ChartBounds::new(0.0, 18_420.0)),
2323                ..BarGeometryOptions::default()
2324            },
2325        );
2326
2327        assert_eq!(exact.domain, ChartDomain::new(0.0, 18_420.0));
2328    }
2329
2330    #[test]
2331    fn pie_slices_cover_the_circle_and_skip_invalid_values() {
2332        let data = vec![
2333            ChartDatum::new("a", 1.0),
2334            ChartDatum::new("b", -3.0),
2335            ChartDatum::new("c", f64::INFINITY),
2336            ChartDatum::new("d", 3.0),
2337        ];
2338        let geometry = pie_geometry(&data, PieChartVariant::Donut);
2339        assert_eq!(geometry.slices.len(), 2);
2340        assert!((geometry.total - 4.0).abs() < 1e-12);
2341        assert!(
2342            geometry.slices[0]
2343                .path
2344                .starts_with("M 160.000 12.000 A 148.000 148.000 0 0 1")
2345        );
2346        let full = pie_geometry(&[ChartDatum::new("only", 2.0)], PieChartVariant::Pie);
2347        assert_eq!(
2348            full.slices[0].path,
2349            "M 160.000 12.000 A 148.000 148.000 0 1 1 160.000 308.000 A 148.000 148.000 0 1 1 160.000 12.000 Z"
2350        );
2351        assert_eq!(pie_geometry(&[], PieChartVariant::Pie).slices, []);
2352    }
2353
2354    #[test]
2355    fn scatter_rejects_invalid_domains_instead_of_panicking() {
2356        let series = vec![ChartSeries::new(
2357            "a",
2358            "A",
2359            [ChartDatum::new(1, 2.0), ChartDatum::new(10, 4.0)],
2360        )];
2361        let padding = uniform(44.0);
2362        assert!(
2363            scatter_geometry(
2364                &series,
2365                ScatterChartScale::Linear,
2366                None,
2367                None,
2368                padding,
2369                None,
2370                None,
2371            )
2372            .is_some()
2373        );
2374        let log = scatter_geometry(
2375            &series,
2376            ScatterChartScale::Log,
2377            None,
2378            None,
2379            padding,
2380            None,
2381            None,
2382        );
2383        // Log axes keep their padded extent; the linear y axis still rounds to nice ticks.
2384        assert!(
2385            log.is_some_and(|geometry| geometry.domain == ChartDomain::new(1.0, 5.0)
2386                && (geometry.x_domain.min - 0.913_981_699_465_490_5).abs() < 1e-12)
2387        );
2388        assert!(
2389            scatter_geometry(
2390                &series,
2391                ScatterChartScale::Linear,
2392                None,
2393                Some(ChartBounds::new(5.0, 1.0)),
2394                padding,
2395                None,
2396                None,
2397            )
2398            .is_none()
2399        );
2400        assert!(
2401            scatter_geometry(
2402                &series,
2403                ScatterChartScale::Log,
2404                Some(ChartBounds::new(-1.0, 10.0)),
2405                None,
2406                padding,
2407                None,
2408                None,
2409            )
2410            .is_none()
2411        );
2412        let empty = scatter_geometry(
2413            &[],
2414            ScatterChartScale::Linear,
2415            None,
2416            None,
2417            padding,
2418            None,
2419            None,
2420        );
2421        assert!(empty.is_some_and(|geometry| geometry.points.is_empty()));
2422    }
2423
2424    #[test]
2425    fn scatter_domains_end_on_ticks_and_share_the_plot_with_references() {
2426        let cohorts = vec![ChartSeries::new(
2427            "cohorts",
2428            "Cohorts",
2429            [
2430                ChartDatum::new(18, 12.0).with_size(44.0),
2431                ChartDatum::new(91, 84.0).with_size(30.0),
2432            ],
2433        )];
2434        let nice = scatter_geometry(
2435            &cohorts,
2436            ScatterChartScale::Linear,
2437            None,
2438            None,
2439            uniform(44.0),
2440            None,
2441            None,
2442        );
2443
2444        assert!(
2445            nice.is_some_and(|geometry| geometry.domain == ChartDomain::new(0.0, 100.0)
2446                && geometry.x_domain == ChartDomain::new(0.0, 100.0))
2447        );
2448
2449        let series = vec![ChartSeries::new(
2450            "a",
2451            "A",
2452            [ChartDatum::new(0, 0.0), ChartDatum::new(100, 100.0)],
2453        )];
2454        let Some(geometry) = scatter_geometry(
2455            &series,
2456            ScatterChartScale::Linear,
2457            Some(ChartBounds::new(0.0, 100.0)),
2458            Some(ChartBounds::new(0.0, 100.0)),
2459            Margin {
2460                top: 16.0,
2461                ..uniform(44.0)
2462            },
2463            None,
2464            None,
2465        ) else {
2466            panic!("valid scatter domains");
2467        };
2468        let goal = ScatterChartReference {
2469            id: "goal".into(),
2470            label: "Goal".into(),
2471            y: Some(100.0),
2472            ..ScatterChartReference::default()
2473        };
2474        let references = scatter_references(&[goal], &geometry, ScatterChartScale::Linear);
2475
2476        assert_eq!(
2477            geometry.plot,
2478            PlotFrame {
2479                bottom: 276.0,
2480                left: 44.0,
2481                right: 596.0,
2482                top: 16.0,
2483            }
2484        );
2485        assert_eq!(
2486            geometry
2487                .points
2488                .iter()
2489                .map(|point| (point.x, point.y))
2490                .collect::<Vec<_>>(),
2491            [(44.0, 276.0), (596.0, 16.0)]
2492        );
2493        assert_eq!(
2494            references
2495                .iter()
2496                .map(|reference| (reference.x1, reference.x2, reference.y1, reference.y2))
2497                .collect::<Vec<_>>(),
2498            [(44.0, 596.0, 16.0, 16.0)]
2499        );
2500    }
2501
2502    #[test]
2503    fn heatmaps_keep_the_first_cell_and_mix_colors() {
2504        let data = vec![
2505            HeatmapDatum::new("Mon", 1, 2.0),
2506            HeatmapDatum::new("Mon", 1, 9.0),
2507            HeatmapDatum::new("Tue", 1, None),
2508            HeatmapDatum::new("Tue", 2, -1.0),
2509        ];
2510        let model = heatmap_model(&data, HeatmapColorScale::Sequential, 0.0, None);
2511        assert_eq!(model.cells.len(), 3);
2512        assert_eq!(model.domain, ChartDomain::new(-1.0, 2.0));
2513        let diverging = heatmap_model(&data, HeatmapColorScale::Diverging, 0.0, None);
2514        assert_eq!(diverging.domain, ChartDomain::new(-2.0, 2.0));
2515        assert_eq!(
2516            heatmap_color(
2517                Some(2.0),
2518                ChartDomain::new(0.0, 4.0),
2519                HeatmapColorScale::Sequential,
2520                0.0
2521            ),
2522            "color-mix(in srgb, hsl(var(--chart-sequential-high)) 50%, hsl(var(--chart-sequential-low)))"
2523        );
2524        assert_eq!(
2525            heatmap_color(
2526                None,
2527                ChartDomain::new(0.0, 4.0),
2528                HeatmapColorScale::Sequential,
2529                0.0
2530            ),
2531            "hsl(var(--surface-muted))"
2532        );
2533        let invalid = heatmap_model(
2534            &[HeatmapDatum::new(f64::NAN, 1, 1.0)],
2535            HeatmapColorScale::Sequential,
2536            0.0,
2537            None,
2538        );
2539        assert_eq!(invalid.cells, []);
2540    }
2541
2542    #[test]
2543    fn ranges_break_on_missing_bounds() {
2544        let data = vec![
2545            RangeChartDatum::new("a", 1.0, 3.0),
2546            RangeChartDatum::new("b", None, 3.0),
2547            RangeChartDatum::new("c", 2.0, 5.0),
2548        ];
2549        let geometry = range_geometry(&data, uniform(44.0), 640.0, 320.0, None, None);
2550        assert_eq!(geometry.points.len(), 2);
2551        assert_eq!(geometry.area_path.matches('Z').count(), 2);
2552        assert_eq!(geometry.domain, ChartDomain::new(1.0, 5.0));
2553        assert_eq!(geometry.ticks, vec![1.0, 2.0, 3.0, 4.0, 5.0]);
2554        assert_eq!(
2555            range_geometry(&[], uniform(44.0), 640.0, 320.0, None, None).area_path,
2556            ""
2557        );
2558    }
2559
2560    #[test]
2561    fn ranges_inset_intervals_and_report_their_plot_frame() {
2562        let week = [
2563            RangeChartDatum::new("Mon", 14.0, 24.0),
2564            RangeChartDatum::new("Wed", 19.0, 31.0),
2565            RangeChartDatum::new("Sun", 12.0, 24.0),
2566        ];
2567        let geometry = range_geometry(&week, uniform(44.0), 640.0, 320.0, None, None);
2568
2569        assert_eq!(geometry.domain, ChartDomain::new(10.0, 35.0));
2570        assert_eq!(geometry.ticks, vec![10.0, 15.0, 20.0, 25.0, 30.0, 35.0]);
2571
2572        let pair = [
2573            RangeChartDatum::new("Mon", 14.0, 24.0),
2574            RangeChartDatum::new("Sun", 13.0, 24.0),
2575        ];
2576        let geometry = range_geometry(
2577            &pair,
2578            Margin {
2579                top: 16.0,
2580                ..uniform(44.0)
2581            },
2582            640.0,
2583            320.0,
2584            None,
2585            None,
2586        );
2587
2588        assert_eq!(
2589            geometry.plot,
2590            PlotFrame {
2591                bottom: 276.0,
2592                left: 44.0,
2593                right: 596.0,
2594                top: 16.0,
2595            }
2596        );
2597        assert_eq!(
2598            geometry
2599                .points
2600                .iter()
2601                .map(|point| point.x)
2602                .collect::<Vec<_>>(),
2603            [52.0, 588.0]
2604        );
2605        assert!(geometry.points[0].high >= 16.0);
2606        assert_eq!(
2607            range_geometry(&pair, react_frame(), 640.0, 320.0, None, None).plot,
2608            PlotFrame {
2609                bottom: 276.0,
2610                left: 44.0,
2611                right: 616.0,
2612                top: 16.0,
2613            }
2614        );
2615    }
2616
2617    #[test]
2618    fn line_insets_are_capped_to_keep_usable_width() {
2619        let data = [ChartDatum::new("A", 1.0), ChartDatum::new("B", 2.0)];
2620        let x = |inset: Option<f64>| {
2621            let options = LineGeometryOptions {
2622                inset,
2623                ..LineGeometryOptions::new(40.0, 100.0, 0.0)
2624            };
2625
2626            line_geometry(&data, options)
2627                .points
2628                .iter()
2629                .map(|point| point.x)
2630                .collect::<Vec<_>>()
2631        };
2632
2633        assert_eq!(x(Some(1_000.0)), [10.0, 30.0]);
2634        assert_eq!(x(Some(f64::NAN)), [0.0, 40.0]);
2635        assert_eq!(x(None), [0.0, 40.0]);
2636    }
2637
2638    #[test]
2639    fn line_models_reserve_room_for_centred_edge_labels_and_markers() {
2640        let series = vec![ChartSeries::new(
2641            "a",
2642            "A",
2643            [
2644                ChartDatum::new("Mon", 18_420.0),
2645                ChartDatum::new("Tue", 9_870.0),
2646                ChartDatum::new("September 30", 6_320.0),
2647            ],
2648        )];
2649        let annotations = [
2650            LineChartAnnotation::x("n", "Launch", "Tue"),
2651            LineChartAnnotation::x("n", "Duplicate", "Mon"),
2652            LineChartAnnotation::y("g", "Goal", 15_000.0),
2653        ];
2654        let model = line_chart_model(
2655            &series,
2656            &LineChartModelOptions {
2657                annotations: &annotations,
2658                ..LineChartModelOptions::default()
2659            },
2660        );
2661
2662        // The last label reaches min(640 / 5, 168 / 2 - 8) = 76 units past its point.
2663        assert!((model.padding_right - 76.0).abs() < 1e-12);
2664        assert!((model.padding_left - 58.0).abs() < 1e-12);
2665        // An x annotation adds room for its label above the plot.
2666        assert!((model.padding_top - 32.0).abs() < 1e-12);
2667        assert!((model.padding_bottom - 44.0).abs() < 1e-12);
2668        assert!((model.inset - 8.0).abs() < 1e-12);
2669        assert_eq!(
2670            model.clip,
2671            ChartRect {
2672                height: 176.0,
2673                width: 506.0,
2674                x: 58.0,
2675                y: 26.0,
2676            }
2677        );
2678        assert_eq!(model.positions, [66.0, 311.0, 556.0]);
2679        assert_eq!(model.domain, ChartDomain::new(5_000.0, 20_000.0));
2680        assert_eq!(model.tick_labels, ["5K", "10K", "15K", "20K"]);
2681        assert_eq!(
2682            model
2683                .category_ticks
2684                .iter()
2685                .map(|tick| (tick.index, tick.position))
2686                .collect::<Vec<_>>(),
2687            [(0, 66.0), (1, 311.0), (2, 556.0)]
2688        );
2689        assert_eq!(
2690            model
2691                .annotation_marks
2692                .iter()
2693                .map(|mark| mark.annotation.id.as_str())
2694                .collect::<Vec<_>>(),
2695            ["n", "g"]
2696        );
2697        assert!((model.annotation_marks[1].coordinate - 86.666_666_666_666_67).abs() < 1e-9);
2698        assert!((model.geometries[0].points[0].y - 49.274_666_666_666_66).abs() < 1e-9);
2699
2700        let empty = line_chart_model(&[], &LineChartModelOptions::default());
2701
2702        assert!((empty.padding_right - 24.0).abs() < 1e-12);
2703        assert!((empty.padding_top - 16.0).abs() < 1e-12);
2704        assert_eq!(empty.tick_labels, ["0", "0.2", "0.4", "0.6", "0.8", "1"]);
2705        assert_eq!(
2706            empty.clip,
2707            ChartRect {
2708                height: 192.0,
2709                width: 558.0,
2710                x: 58.0,
2711                y: 10.0,
2712            }
2713        );
2714    }
2715
2716    #[test]
2717    fn line_models_label_only_categories_inside_an_explicit_viewport() {
2718        let series = vec![ChartSeries::new(
2719            "a",
2720            "A",
2721            [
2722                ChartDatum::new(1, 2.0),
2723                ChartDatum::new(5, 3.0),
2724                ChartDatum::new(9, 4.0),
2725            ],
2726        )];
2727        let model = line_chart_model(
2728            &series,
2729            &LineChartModelOptions {
2730                domain: Some(ChartBounds::min(0.0)),
2731                x_domain: Some(ChartBounds::new(4.0, 10.0)),
2732                x_scale: LineChartScale::Linear,
2733                ..LineChartModelOptions::default()
2734            },
2735        );
2736
2737        assert_eq!(model.domain, ChartDomain::new(0.0, 4.0));
2738        assert!((model.positions[0] + 232.0).abs() < 1e-9);
2739        assert_eq!(
2740            model
2741                .category_ticks
2742                .iter()
2743                .map(|tick| (tick.index, tick.label.as_str()))
2744                .collect::<Vec<_>>(),
2745            [(1, "5"), (2, "9")]
2746        );
2747    }
2748
2749    #[test]
2750    fn iso_dates_parse_strictly_in_linear_time() {
2751        assert_eq!(parse_iso_timestamp("1970-01-01"), Some(0.0));
2752        assert_eq!(parse_iso_timestamp("2024-02-29"), Some(1_709_164_800_000.0));
2753        assert_eq!(parse_iso_timestamp("2023-02-29"), None);
2754        assert_eq!(
2755            parse_iso_timestamp("2024-01-01T12:30:00Z"),
2756            Some(1_704_112_200_000.0)
2757        );
2758        assert_eq!(
2759            parse_iso_timestamp("2024-01-01T12:30+02:00"),
2760            Some(1_704_105_000_000.0)
2761        );
2762        assert_eq!(parse_iso_timestamp("2024"), Some(1_704_067_200_000.0));
2763        assert_eq!(parse_iso_timestamp("2024-13-01"), None);
2764        assert_eq!(parse_iso_timestamp("Jan 1"), None);
2765        assert_eq!(parse_iso_timestamp(&"9".repeat(100_000)), None);
2766        assert_eq!(
2767            numeric_x(&ChartX::from(" 42 "), LineChartScale::Linear),
2768            Some(42.0)
2769        );
2770        assert_eq!(numeric_x(&ChartX::from(""), LineChartScale::Linear), None);
2771        assert_eq!(
2772            numeric_x(&ChartX::from("Infinity"), LineChartScale::Linear),
2773            None
2774        );
2775        assert_eq!(
2776            numeric_x(&ChartX::from(f64::NAN), LineChartScale::Time),
2777            None
2778        );
2779    }
2780}