Skip to main content

euv_ui/component/chart/scale/
impl.rs

1use super::*;
2
3/// Projection and inverse-mapping methods for `EuvChartAxisScale`.
4impl EuvChartAxisScale {
5    /// Normalizes a domain value into `[0.0, 1.0]` respecting `Category`, `Value`, `Time`, `Log`, and `inverse`.
6    ///
7    /// # Arguments
8    ///
9    /// - `&Self` - Computed axis scale.
10    /// - `f32` - Domain value or category index.
11    ///
12    /// # Returns
13    ///
14    /// - `f32` - Normalized coordinate in `[0.0, 1.0]` (unclamped when outside range).
15    #[must_use]
16    pub fn normalize(&self, value: f32) -> f32 {
17        let min_v: f32 = self.get_min();
18        let max_v: f32 = self.get_max();
19        let raw_t: f32 = match self.get_axis_type() {
20            EuvChartAxisType::Log => {
21                let lo: f32 = min_v.max(SCALE_LOG_MIN_POSITIVE).log10();
22                let hi: f32 = max_v.max(SCALE_LOG_MIN_POSITIVE * 10.0).log10();
23                let span: f32 = (hi - lo).max(1e-6);
24                let v_log: f32 = value.max(SCALE_LOG_MIN_POSITIVE).log10();
25                (v_log - lo) / span
26            }
27            EuvChartAxisType::Category => {
28                let win_span: f32 = self.get_window_span();
29                if win_span > 1e-4 {
30                    (value + 0.5 - self.get_window_start()) / win_span
31                } else {
32                    let count: usize = self.get_categories().len();
33                    if count == 0 {
34                        0.5
35                    } else {
36                        (value + 0.5) / (count as f32)
37                    }
38                }
39            }
40            EuvChartAxisType::Value | EuvChartAxisType::Time => {
41                let span: f32 = max_v - min_v;
42                if span.abs() < 1e-6 {
43                    0.5
44                } else {
45                    (value - min_v) / span
46                }
47            }
48        };
49        if self.get_inverse() {
50            1.0 - raw_t
51        } else {
52            raw_t
53        }
54    }
55
56    /// Projects a domain value onto a horizontal pixel coordinate inside `plot_rect`.
57    ///
58    /// # Arguments
59    ///
60    /// - `&Self` - Horizontal axis scale.
61    /// - `f32` - Domain value or category index.
62    /// - `Rect` - Target plot rectangle.
63    ///
64    /// # Returns
65    ///
66    /// - `f32` - Logical X pixel coordinate.
67    #[must_use]
68    pub fn map_x(&self, value: f32, plot_rect: Rect) -> f32 {
69        plot_rect.get_x() + self.normalize(value) * plot_rect.get_width()
70    }
71
72    /// Projects a domain value onto a vertical pixel coordinate inside `plot_rect` (bottom-up for numeric axes, top-down for category bars).
73    ///
74    /// # Arguments
75    ///
76    /// - `&Self` - Vertical axis scale.
77    /// - `f32` - Domain value or category index.
78    /// - `Rect` - Target plot rectangle.
79    ///
80    /// # Returns
81    ///
82    /// - `f32` - Logical Y pixel coordinate.
83    #[must_use]
84    pub fn map_y(&self, value: f32, plot_rect: Rect) -> f32 {
85        let t: f32 = self.normalize(value);
86        match self.get_axis_type() {
87            EuvChartAxisType::Category => plot_rect.get_y() + t * plot_rect.get_height(),
88            EuvChartAxisType::Value | EuvChartAxisType::Time | EuvChartAxisType::Log => {
89                plot_rect.get_y() + (1.0 - t) * plot_rect.get_height()
90            }
91        }
92    }
93
94    /// Returns the baseline pixel Y corresponding to `0.0` (clamped inside `plot_rect`).
95    ///
96    /// # Arguments
97    ///
98    /// - `&Self` - Vertical numeric axis scale.
99    /// - `Rect` - Target plot rectangle.
100    ///
101    /// # Returns
102    ///
103    /// - `f32` - Baseline Y coordinate in logical pixels.
104    #[must_use]
105    pub fn baseline_y(&self, plot_rect: Rect) -> f32 {
106        let zero_val: f32 = if self.get_axis_type() == EuvChartAxisType::Log {
107            self.get_min().max(SCALE_LOG_MIN_POSITIVE)
108        } else {
109            0.0_f32.clamp(self.get_min(), self.get_max())
110        };
111        self.map_y(zero_val, plot_rect).clamp(
112            plot_rect.get_y(),
113            plot_rect.get_y() + plot_rect.get_height(),
114        )
115    }
116
117    /// Returns the baseline pixel X corresponding to `0.0` (clamped inside `plot_rect`) for horizontal bar charts.
118    ///
119    /// # Arguments
120    ///
121    /// - `&Self` - Horizontal numeric axis scale.
122    /// - `Rect` - Target plot rectangle.
123    ///
124    /// # Returns
125    ///
126    /// - `f32` - Baseline X coordinate in logical pixels.
127    #[must_use]
128    pub fn baseline_x(&self, plot_rect: Rect) -> f32 {
129        let zero_val: f32 = if self.get_axis_type() == EuvChartAxisType::Log {
130            self.get_min().max(SCALE_LOG_MIN_POSITIVE)
131        } else {
132            0.0_f32.clamp(self.get_min(), self.get_max())
133        };
134        self.map_x(zero_val, plot_rect)
135            .clamp(plot_rect.get_x(), plot_rect.get_x() + plot_rect.get_width())
136    }
137
138    /// Returns the continuous visible category slot count for stable candle/bar width computation during panning.
139    ///
140    /// # Arguments
141    ///
142    /// - `&Self` - Axis scale reference.
143    ///
144    /// # Returns
145    ///
146    /// - `f32` - Positive visible category slot count.
147    #[must_use]
148    pub fn visible_slot_count(&self) -> f32 {
149        let win_span: f32 = self.get_window_span();
150        if win_span > 1e-4 {
151            win_span
152        } else {
153            (self.get_categories().len().max(1)) as f32
154        }
155    }
156
157    /// Resolves the category label for a global sample index when inside the active slice.
158    ///
159    /// # Arguments
160    ///
161    /// - `&Self` - Category axis scale reference.
162    /// - `usize` - Global zero-based category index.
163    ///
164    /// # Returns
165    ///
166    /// - `Option<&str>` - Matching category label when available.
167    #[must_use]
168    pub fn category_label_at(&self, global_idx: usize) -> Option<&str> {
169        let local_idx: usize = global_idx.checked_sub(self.get_category_base_index())?;
170        self.get_categories().get(local_idx).map(String::as_str)
171    }
172}
173
174/// Continuous window helpers for `EuvChartZoomSlice`.
175impl EuvChartZoomSlice {
176    /// Returns `true` when the active zoom window covers strictly less than the full `[0%, 100%]` domain.
177    ///
178    /// # Arguments
179    ///
180    /// - `&Self` - Zoom slice reference.
181    ///
182    /// # Returns
183    ///
184    /// - `bool` - True when zoomed in.
185    #[must_use]
186    pub fn is_zoomed(&self) -> bool {
187        (self.get_end_pct() - self.get_start_pct()) < 99.9
188    }
189
190    /// Returns the padded `[render_start, render_end)` index range covering visible plus one neighbor on each side for smooth clipped panning.
191    ///
192    /// # Arguments
193    ///
194    /// - `&Self` - Zoom slice reference.
195    /// - `usize` - Total series sample count.
196    ///
197    /// # Returns
198    ///
199    /// - `(usize, usize)` - Half-open global index range clamped to `[0, total_len]`.
200    #[must_use]
201    pub fn render_index_range(&self, total_len: usize) -> (usize, usize) {
202        if total_len == 0 {
203            return (0, 0);
204        }
205        let s: usize = (self.get_start_f().floor() as usize)
206            .saturating_sub(1)
207            .min(total_len.saturating_sub(1));
208        let e: usize = ((self.get_end_f().ceil() as usize) + 1)
209            .min(total_len)
210            .max((s + 1).min(total_len));
211        (s, e)
212    }
213
214    /// Computes the smooth fractional overlap weight in `[0.0, 1.0]` of sample slot `[idx, idx + 1]` against `[start_f, end_f]`.
215    ///
216    /// # Arguments
217    ///
218    /// - `&Self` - Zoom slice reference.
219    /// - `usize` - Global zero-based sample index.
220    ///
221    /// # Returns
222    ///
223    /// - `f32` - Smoothstep visibility weight in `[0.0, 1.0]`.
224    #[must_use]
225    pub fn sample_visibility_weight(&self, idx: usize) -> f32 {
226        let a: f32 = idx as f32;
227        let b: f32 = a + 1.0;
228        let overlap: f32 = (b.min(self.get_end_f()) - a.max(self.get_start_f())).clamp(0.0, 1.0);
229        overlap * overlap * (3.0 - 2.0 * overlap)
230    }
231}
232
233/// Color interpolation methods for `EuvChartVisualEvaluator`.
234impl EuvChartVisualEvaluator {
235    /// Resolves a numeric `value` into its mapped `Color` under `Continuous` or `Piecewise` rules.
236    ///
237    /// # Arguments
238    ///
239    /// - `&Self` - Visual-map evaluator.
240    /// - `f32` - Scalar data value.
241    ///
242    /// # Returns
243    ///
244    /// - `Color` - Interpolated or bucketed RGBA color.
245    #[must_use]
246    pub fn map_color(&self, value: f32) -> Color {
247        if self.get_kind() == EuvChartVisualMapKind::Piecewise {
248            for piece in self.get_pieces().iter() {
249                let ge_min: bool = piece.min_opt().is_none_or(|lo: f32| value >= lo);
250                let le_max: bool = piece.max_opt().is_none_or(|hi: f32| value <= hi);
251                if ge_min && le_max {
252                    return piece.get_color();
253                }
254            }
255            if let Some(last) = self.get_pieces().last() {
256                return last.get_color();
257            }
258        }
259        let stops: &[Color] = self.get_stops().as_slice();
260        if stops.is_empty() {
261            return Color::hex(ECHART_PALETTE_LIGHT[0]);
262        }
263        if stops.len() == 1 {
264            return stops[0];
265        }
266        let span: f32 = (self.get_max() - self.get_min()).max(1e-6);
267        let t: f32 = ((value - self.get_min()) / span).clamp(0.0, 1.0);
268        let scaled: f32 = t * ((stops.len() - 1) as f32);
269        let idx: usize = (scaled.floor() as usize).min(stops.len() - 2);
270        let local_t: f32 = (scaled - (idx as f32)).clamp(0.0, 1.0);
271        stops[idx].lerp(stops[idx + 1], local_t)
272    }
273}