rgpui 1.3.0

GUI UI framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
//! 迷你走势图组件(Sparkline):以折线、柱状或面积图展示一维数据序列。

use crate::{prelude::FluentBuilder as _, *};

/// 默认折线颜色(蓝色)。
const DEFAULT_LINE_COLOR: u32 = 0x3b82f6;
/// 上升趋势颜色(绿色)。
const TREND_UP_COLOR: u32 = 0x22c55e;
/// 下降趋势颜色(红色)。
const TREND_DOWN_COLOR: u32 = 0xef4444;

/// 走势图绘制样式。
#[derive(Copy, Clone, Default, PartialEq, Eq)]
pub enum SparklineVariant {
    /// 折线。
    #[default]
    Line,
    /// 柱状。
    Bar,
    /// 面积。
    Area,
}

/// 走势图尺寸档位。
#[derive(Copy, Clone, Default, PartialEq, Eq)]
pub enum SparklineSize {
    /// 小尺寸(60x20)。
    Sm,
    /// 中等尺寸(100x32)。
    #[default]
    Md,
    /// 大尺寸(150x48)。
    Lg,
}

impl SparklineSize {
    /// 返回默认宽高(像素)。
    fn dimensions(self) -> (Pixels, Pixels) {
        match self {
            SparklineSize::Sm => (px(60.0), px(20.0)),
            SparklineSize::Md => (px(100.0), px(32.0)),
            SparklineSize::Lg => (px(150.0), px(48.0)),
        }
    }

    /// 返回线条宽度(像素)。
    fn line_width(self) -> Pixels {
        match self {
            SparklineSize::Sm => px(1.0),
            SparklineSize::Md => px(1.5),
            SparklineSize::Lg => px(2.0),
        }
    }

    /// 返回端点圆点半径(像素)。
    fn point_radius(self) -> Pixels {
        match self {
            SparklineSize::Sm => px(2.0),
            SparklineSize::Md => px(3.0),
            SparklineSize::Lg => px(4.0),
        }
    }

    /// 返回柱状图的间隙(像素)。
    fn bar_gap(self) -> f32 {
        match self {
            SparklineSize::Sm => 1.0,
            SparklineSize::Md => 2.0,
            SparklineSize::Lg => 3.0,
        }
    }
}

/// 走势趋势。
#[derive(Copy, Clone, PartialEq, Eq)]
pub enum SparklineTrend {
    /// 上升。
    Up,
    /// 下降。
    Down,
    /// 持平。
    Neutral,
}

/// 数据取值范围。
struct DataRange {
    /// 最小值。
    min: f64,
    /// 最大值。
    max: f64,
    /// 最小值所在索引。
    min_index: usize,
    /// 最大值所在索引。
    max_index: usize,
}

impl DataRange {
    /// 从数据计算取值范围。
    fn from_data(data: &[f64]) -> Self {
        if data.is_empty() {
            return Self {
                min: 0.0,
                max: 1.0,
                min_index: 0,
                max_index: 0,
            };
        }

        let mut min = f64::MAX;
        let mut max = f64::MIN;
        let mut min_index = 0;
        let mut max_index = 0;

        for (i, &value) in data.iter().enumerate() {
            if value < min {
                min = value;
                min_index = i;
            }
            if value > max {
                max = value;
                max_index = i;
            }
        }

        if (max - min).abs() < f64::EPSILON {
            max = min + 1.0;
        }

        Self {
            min,
            max,
            min_index,
            max_index,
        }
    }

    /// 将数值归一化到 [0, 1] 区间。
    fn normalize(&self, value: f64) -> f32 {
        ((value - self.min) / (self.max - self.min)) as f32
    }
}

/// 根据首尾数据点计算走势趋势。
fn compute_trend(data: &[f64]) -> SparklineTrend {
    if data.len() < 2 {
        return SparklineTrend::Neutral;
    }

    let first = data[0];
    let last = data[data.len() - 1];

    if (last - first).abs() < f64::EPSILON * 10.0 {
        SparklineTrend::Neutral
    } else if last > first {
        SparklineTrend::Up
    } else {
        SparklineTrend::Down
    }
}

/// 走势图绘制所需的数据。
#[derive(Clone)]
struct SparklinePaintData {
    /// 原始数据序列。
    data: Vec<f64>,
    /// 绘制样式。
    variant: SparklineVariant,
    /// 线条颜色。
    line_color: Hsla,
    /// 填充颜色。
    fill_color: Hsla,
    /// 是否高亮最小值与最大值。
    show_min_max: bool,
    /// 最小/最大值高亮颜色。
    min_max_color: Hsla,
    /// 尺寸档位。
    size: SparklineSize,
}

/// 迷你走势图组件。
#[derive(IntoElement)]
pub struct Sparkline {
    /// 数据序列。
    data: Vec<f64>,
    /// 绘制样式。
    variant: SparklineVariant,
    /// 尺寸档位。
    size: SparklineSize,
    /// 线条颜色(默认蓝色)。
    line_color: Option<Hsla>,
    /// 填充颜色(默认线条色的 20% 透明度)。
    fill_color: Option<Hsla>,
    /// 是否高亮最小/最大值。
    show_min_max: bool,
    /// 最小/最大值高亮颜色(默认主题前景色)。
    min_max_color: Option<Hsla>,
    /// 是否显示趋势箭头。
    show_trend: bool,
    /// 自定义宽度。
    custom_width: Option<Pixels>,
    /// 自定义高度。
    custom_height: Option<Pixels>,
    /// 用户样式。
    style: StyleRefinement,
}

impl Sparkline {
    /// 创建走势图组件。
    pub fn new(data: Vec<f64>) -> Self {
        Self {
            data,
            variant: SparklineVariant::Line,
            size: SparklineSize::Md,
            line_color: None,
            fill_color: None,
            show_min_max: false,
            min_max_color: None,
            show_trend: false,
            custom_width: None,
            custom_height: None,
            style: StyleRefinement::default(),
        }
    }

    /// 创建折线走势图。
    pub fn line(data: Vec<f64>) -> Self {
        Self::new(data).variant(SparklineVariant::Line)
    }

    /// 创建柱状走势图。
    pub fn bar(data: Vec<f64>) -> Self {
        Self::new(data).variant(SparklineVariant::Bar)
    }

    /// 创建面积走势图。
    pub fn area(data: Vec<f64>) -> Self {
        Self::new(data).variant(SparklineVariant::Area)
    }

    /// 设置绘制样式。
    pub fn variant(mut self, variant: SparklineVariant) -> Self {
        self.variant = variant;
        self
    }

    /// 设置尺寸档位。
    pub fn size(mut self, size: SparklineSize) -> Self {
        self.size = size;
        self
    }

    /// 设置自定义宽度。
    pub fn width(mut self, width: Pixels) -> Self {
        self.custom_width = Some(width);
        self
    }

    /// 设置自定义高度。
    pub fn height(mut self, height: Pixels) -> Self {
        self.custom_height = Some(height);
        self
    }

    /// 设置线条颜色。
    pub fn line_color(mut self, color: Hsla) -> Self {
        self.line_color = Some(color);
        self
    }

    /// 设置填充颜色。
    pub fn fill_color(mut self, color: Hsla) -> Self {
        self.fill_color = Some(color);
        self
    }

    /// 设置是否高亮最小/最大值。
    pub fn show_min_max(mut self, show: bool) -> Self {
        self.show_min_max = show;
        self
    }

    /// 设置最小/最大值高亮颜色。
    pub fn min_max_color(mut self, color: Hsla) -> Self {
        self.min_max_color = Some(color);
        self
    }

    /// 设置是否显示趋势箭头。
    pub fn show_trend(mut self, show: bool) -> Self {
        self.show_trend = show;
        self
    }

    /// 返回实际宽高(自定义值优先,否则用尺寸档位默认值)。
    fn get_dimensions(&self) -> (Pixels, Pixels) {
        let (default_width, default_height) = self.size.dimensions();
        (
            self.custom_width.unwrap_or(default_width),
            self.custom_height.unwrap_or(default_height),
        )
    }

    /// 根据趋势返回对应的颜色。
    fn get_trend_color(&self) -> Hsla {
        match compute_trend(&self.data) {
            SparklineTrend::Up => rgb(TREND_UP_COLOR).into(),
            SparklineTrend::Down => rgb(TREND_DOWN_COLOR).into(),
            SparklineTrend::Neutral => self
                .line_color
                .unwrap_or_else(|| rgb(DEFAULT_LINE_COLOR).into()),
        }
    }
}

impl Styled for Sparkline {
    fn style(&mut self) -> &mut StyleRefinement {
        &mut self.style
    }
}

impl RenderOnce for Sparkline {
    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
        let theme = cx.theme();
        let (width, height) = self.get_dimensions();
        let trend_color = self.get_trend_color();

        let effective_line_color = if self.show_trend {
            trend_color
        } else {
            self.line_color
                .unwrap_or_else(|| rgb(DEFAULT_LINE_COLOR).into())
        };

        let effective_fill_color = self
            .fill_color
            .unwrap_or_else(|| effective_line_color.opacity(0.2));

        let effective_min_max_color = self
            .min_max_color
            .unwrap_or_else(|| *theme.tokens.foreground);

        let trend = if self.show_trend {
            Some(compute_trend(&self.data))
        } else {
            None
        };

        let paint_data = SparklinePaintData {
            data: self.data,
            variant: self.variant,
            line_color: effective_line_color,
            fill_color: effective_fill_color,
            show_min_max: self.show_min_max,
            min_max_color: effective_min_max_color,
            size: self.size,
        };

        // 纯 DOM 模式下 canvas 隐藏,需为 canvas 元素附加等价 SVG 的 DOM 节点。
        #[cfg(feature = "dom-backend")]
        let dom_data = paint_data.clone();

        let user_style = self.style;

        let trend_icon = trend.map(|t| {
            let (icon_char, color) = match t {
                SparklineTrend::Up => ("", rgb(TREND_UP_COLOR).into()),
                SparklineTrend::Down => ("", rgb(TREND_DOWN_COLOR).into()),
                SparklineTrend::Neutral => ("", *theme.tokens.muted_foreground),
            };
            (icon_char, color)
        });

        let mut chart = canvas(
            move |_bounds, _window, _cx| paint_data,
            move |bounds, paint_data, window, _cx| {
                paint_sparkline(bounds, &paint_data, window);
            },
        )
        .w(width)
        .h(height);

        // 纯 DOM 模式下用 data URI 的 `<img>` 呈现走势图。
        #[cfg(feature = "dom-backend")]
        {
            chart = chart.with_dom(move |bounds, _window, _cx| {
                let svg = sparkline_svg(bounds, &dom_data);
                crate::components::dom_svg::svg_img_node(bounds, svg)
            });
        }

        let mut root = div()
            .flex()
            .items_center()
            .gap(px(4.0))
            .child(chart)
            .when_some(trend_icon, |this, (icon, color)| {
                this.child(
                    div()
                        .text_xs()
                        .font_weight(FontWeight::BOLD)
                        .text_color(color)
                        .child(icon),
                )
            });
        root.style().refine(&user_style);
        root
    }
}

/// 根据样式分派绘制函数。
fn paint_sparkline(bounds: Bounds<Pixels>, data: &SparklinePaintData, window: &mut Window) {
    if bounds.size.width <= px(0.0) || bounds.size.height <= px(0.0) {
        return;
    }

    if data.data.is_empty() {
        return;
    }

    match data.variant {
        SparklineVariant::Line => paint_line_sparkline(bounds, data, window),
        SparklineVariant::Bar => paint_bar_sparkline(bounds, data, window),
        SparklineVariant::Area => paint_area_sparkline(bounds, data, window),
    }
}

/// 把走势图数据转为等价的 SVG 字符串(纯 DOM 模式显示用)。
///
/// 内容坐标按元素自身 0..宽 × 0..高 生成本地坐标,与 paint 函数的绝对坐标
/// 计算保持一致(仅去掉 bounds 原点),配合 `viewBox` 由浏览器等比缩放。
#[cfg(feature = "dom-backend")]
fn sparkline_svg(bounds: Bounds<Pixels>, data: &SparklinePaintData) -> String {
    use crate::components::dom_svg::css_color;

    let width = bounds.size.width / px(1.0);
    let height = bounds.size.height / px(1.0);
    let mut svg = format!(
        "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 {} {}\">",
        width, height
    );
    let line_color = css_color(data.line_color);
    let fill_color = css_color(data.fill_color);
    let min_max_color = css_color(data.min_max_color);

    match data.variant {
        SparklineVariant::Line => {
            if let Some(points) = sparkline_points(bounds, data) {
                svg.push_str(&format!(
                    "<polyline points=\"{}\" fill=\"none\" stroke=\"{}\" stroke-width=\"{}\" stroke-linejoin=\"round\" stroke-linecap=\"round\"/>",
                    points,
                    line_color,
                    data.size.line_width() / px(1.0)
                ));
            }
        }
        SparklineVariant::Area => {
            if let Some(points) = sparkline_points(bounds, data) {
                // 面积填充:从底部起始、沿折线绕回底部闭合。
                let pts: Vec<(f32, f32)> = points
                    .split(' ')
                    .filter_map(|p| {
                        let mut it = p.split(',');
                        match (it.next(), it.next()) {
                            (Some(x), Some(y)) => x.parse().ok().zip(y.parse().ok()),
                            _ => None,
                        }
                    })
                    .collect();
                if pts.len() >= 2 {
                    svg.push_str(&format!(
                        "<path d=\"M{} {} L{} L{} {} Z\" fill=\"{}\"/>",
                        pts[0].0,
                        height,
                        points,
                        pts[pts.len() - 1].0,
                        height,
                        fill_color
                    ));
                }
            }
        }
        SparklineVariant::Bar => {
            let range = DataRange::from_data(&data.data);
            let point_count = data.data.len();
            if point_count == 0 {
                return svg;
            }
            let padding_y = 2.0;
            let chart_top = padding_y;
            let chart_bottom = height - padding_y;
            let chart_height = chart_bottom - chart_top;
            let gap = data.size.bar_gap();
            let total_gap = gap * (point_count.saturating_sub(1)) as f32;
            let bar_width = ((width - total_gap) / point_count as f32).max(1.0);
            for (i, &value) in data.data.iter().enumerate() {
                let x = bar_width * i as f32 + gap * i as f32;
                let height_ratio = range.normalize(value);
                let bar_height = chart_height * height_ratio;
                let y = chart_bottom - bar_height;
                let bar_color =
                    if data.show_min_max && (i == range.min_index || i == range.max_index) {
                        min_max_color.clone()
                    } else {
                        line_color.clone()
                    };
                svg.push_str(&format!(
                    "<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" rx=\"{}\" fill=\"{}\"/>",
                    x,
                    y,
                    bar_width,
                    bar_height,
                    bar_width * 0.5,
                    bar_color
                ));
            }
        }
    }

    // 高亮最小/最大值端点(折线与面积图共用)。
    if data.show_min_max
        && matches!(
            data.variant,
            SparklineVariant::Line | SparklineVariant::Area
        )
    {
        if let Some(points) = sparkline_points(bounds, data) {
            let range = DataRange::from_data(&data.data);
            let radius = data.size.point_radius() / px(1.0);
            for &index in &[range.min_index, range.max_index] {
                if let Some(pt) = points.split(' ').nth(index) {
                    let mut it = pt.split(',');
                    if let (Some(x), Some(y)) = (it.next(), it.next()) {
                        svg.push_str(&format!(
                            "<circle cx=\"{}\" cy=\"{}\" r=\"{}\" fill=\"{}\"/>",
                            x, y, radius, min_max_color
                        ));
                    }
                }
            }
        }
    }

    svg.push_str("</svg>");
    svg
}

/// 计算折线/面积图的数据点坐标字符串(本地坐标),点数不足 2 时返回 `None`。
#[cfg(feature = "dom-backend")]
fn sparkline_points(bounds: Bounds<Pixels>, data: &SparklinePaintData) -> Option<String> {
    let range = DataRange::from_data(&data.data);
    let point_count = data.data.len();
    if point_count < 2 {
        return None;
    }

    let width = bounds.size.width / px(1.0);
    let height = bounds.size.height / px(1.0);
    let padding = data.size.point_radius() / px(1.0);
    let chart_left = padding;
    let chart_right = width - padding;
    let chart_top = padding;
    let chart_bottom = height - padding;
    let chart_width = chart_right - chart_left;
    let chart_height = chart_bottom - chart_top;
    if chart_width <= 0.0 || chart_height <= 0.0 {
        return None;
    }

    let mut points = String::new();
    for (i, &value) in data.data.iter().enumerate() {
        let x_ratio = i as f32 / (point_count - 1) as f32;
        let y_ratio = range.normalize(value);
        let x = chart_left + chart_width * x_ratio;
        let y = chart_bottom - chart_height * y_ratio;
        points.push_str(&format!("{:.2},{:.2} ", x, y));
    }
    Some(points.trim().to_string())
}

/// 绘制折线走势图。
fn paint_line_sparkline(bounds: Bounds<Pixels>, data: &SparklinePaintData, window: &mut Window) {
    let range = DataRange::from_data(&data.data);
    let point_count = data.data.len();

    if point_count < 2 {
        return;
    }

    let padding = data.size.point_radius();
    let chart_left = bounds.left() + padding;
    let chart_right = bounds.right() - padding;
    let chart_top = bounds.top() + padding;
    let chart_bottom = bounds.bottom() - padding;
    let chart_width = chart_right - chart_left;
    let chart_height = chart_bottom - chart_top;

    if chart_width <= px(0.0) || chart_height <= px(0.0) {
        return;
    }

    let screen_points: Vec<Point<Pixels>> = data
        .data
        .iter()
        .enumerate()
        .map(|(i, &value)| {
            let x_ratio = i as f32 / (point_count - 1) as f32;
            let y_ratio = range.normalize(value);
            let screen_x = chart_left + chart_width * x_ratio;
            let screen_y = chart_bottom - chart_height * y_ratio;
            point(screen_x, screen_y)
        })
        .collect();

    let mut builder = PathBuilder::stroke(data.size.line_width());
    builder.move_to(screen_points[0]);
    for pt in screen_points.iter().skip(1) {
        builder.line_to(*pt);
    }
    if let Ok(path) = builder.build() {
        window.paint_path(path, data.line_color);
    }

    if data.show_min_max {
        let point_radius = data.size.point_radius();
        let min_pt = screen_points[range.min_index];
        let max_pt = screen_points[range.max_index];

        window.paint_quad(fill(
            Bounds::centered_at(min_pt, size(point_radius * 2.0, point_radius * 2.0)),
            data.min_max_color,
        ));
        window.paint_quad(fill(
            Bounds::centered_at(max_pt, size(point_radius * 2.0, point_radius * 2.0)),
            data.min_max_color,
        ));
    }
}

/// 绘制面积走势图。
fn paint_area_sparkline(bounds: Bounds<Pixels>, data: &SparklinePaintData, window: &mut Window) {
    let range = DataRange::from_data(&data.data);
    let point_count = data.data.len();

    if point_count < 2 {
        return;
    }

    let padding = data.size.point_radius();
    let chart_left = bounds.left() + padding;
    let chart_right = bounds.right() - padding;
    let chart_top = bounds.top() + padding;
    let chart_bottom = bounds.bottom() - padding;
    let chart_width = chart_right - chart_left;
    let chart_height = chart_bottom - chart_top;

    if chart_width <= px(0.0) || chart_height <= px(0.0) {
        return;
    }

    let screen_points: Vec<Point<Pixels>> = data
        .data
        .iter()
        .enumerate()
        .map(|(i, &value)| {
            let x_ratio = i as f32 / (point_count - 1) as f32;
            let y_ratio = range.normalize(value);
            let screen_x = chart_left + chart_width * x_ratio;
            let screen_y = chart_bottom - chart_height * y_ratio;
            point(screen_x, screen_y)
        })
        .collect();

    let mut fill_builder = PathBuilder::fill();
    fill_builder.move_to(point(screen_points[0].x, chart_bottom));
    fill_builder.line_to(screen_points[0]);
    for pt in screen_points.iter().skip(1) {
        fill_builder.line_to(*pt);
    }
    fill_builder.line_to(point(screen_points.last().unwrap().x, chart_bottom));
    fill_builder.close();

    if let Ok(path) = fill_builder.build() {
        window.paint_path(path, data.fill_color);
    }

    let mut line_builder = PathBuilder::stroke(data.size.line_width());
    line_builder.move_to(screen_points[0]);
    for pt in screen_points.iter().skip(1) {
        line_builder.line_to(*pt);
    }
    if let Ok(path) = line_builder.build() {
        window.paint_path(path, data.line_color);
    }

    if data.show_min_max {
        let point_radius = data.size.point_radius();
        let min_pt = screen_points[range.min_index];
        let max_pt = screen_points[range.max_index];

        window.paint_quad(fill(
            Bounds::centered_at(min_pt, size(point_radius * 2.0, point_radius * 2.0)),
            data.min_max_color,
        ));
        window.paint_quad(fill(
            Bounds::centered_at(max_pt, size(point_radius * 2.0, point_radius * 2.0)),
            data.min_max_color,
        ));
    }
}

/// 绘制柱状走势图。
fn paint_bar_sparkline(bounds: Bounds<Pixels>, data: &SparklinePaintData, window: &mut Window) {
    let range = DataRange::from_data(&data.data);
    let point_count = data.data.len();

    if point_count == 0 {
        return;
    }

    let padding_y = px(2.0);
    let chart_left = bounds.left();
    let chart_right = bounds.right();
    let chart_top = bounds.top() + padding_y;
    let chart_bottom = bounds.bottom() - padding_y;
    let chart_width = chart_right - chart_left;
    let chart_height = chart_bottom - chart_top;

    if chart_width <= px(0.0) || chart_height <= px(0.0) {
        return;
    }

    let gap = data.size.bar_gap();
    let total_gap = gap * (point_count.saturating_sub(1)) as f32;
    let bar_width_f32 = ((chart_width - px(total_gap)) / point_count as f32).max(px(1.0));
    let bar_width = bar_width_f32;

    for (i, &value) in data.data.iter().enumerate() {
        let x = chart_left + bar_width * i as f32 + px(gap * i as f32);
        let height_ratio = range.normalize(value);
        let bar_height = chart_height * height_ratio;
        let y = chart_bottom - bar_height;

        let bar_color = if data.show_min_max && (i == range.min_index || i == range.max_index) {
            data.min_max_color
        } else {
            data.line_color
        };

        window.paint_quad(fill(
            Bounds::new(point(x, y), size(bar_width, bar_height)),
            bar_color,
        ));
    }
}