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
//! 环形图组件(基于饼图扇区模型)。

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

/// 默认系列配色。
const CHART_COLORS: [u32; 8] = [
    0x3b82f6, 0x22c55e, 0xf59e0b, 0xef4444, 0x8b5cf6, 0x06b6d4, 0xf97316, 0xec4899,
];

/// 获取默认系列颜色。
fn default_color(index: usize) -> Hsla {
    rgb(CHART_COLORS[index % CHART_COLORS.len()]).into()
}

/// 环形图尺寸。
#[derive(Copy, Clone, Default, PartialEq, Eq)]
pub enum DonutChartSize {
    /// 小尺寸。
    Sm,
    /// 中等尺寸。
    #[default]
    Md,
    /// 大尺寸。
    Lg,
    /// 自定义尺寸。
    Custom(u32),
}

impl DonutChartSize {
    /// 转换为像素。
    fn to_pixels(self) -> Pixels {
        match self {
            DonutChartSize::Sm => px(120.0),
            DonutChartSize::Md => px(200.0),
            DonutChartSize::Lg => px(280.0),
            DonutChartSize::Custom(size) => px(size as f32),
        }
    }
}

/// 环形图组件。
#[derive(IntoElement)]
pub struct DonutChart {
    segments: Vec<PieChartSegment>,
    inner_radius: f32,
    center_label: Option<SharedString>,
    center_value: Option<SharedString>,
    size: DonutChartSize,
    show_legend: bool,
    show_percentages: bool,
    style: StyleRefinement,
}

impl DonutChart {
    /// 创建环形图。
    pub fn new() -> Self {
        Self {
            segments: Vec::new(),
            inner_radius: 0.6,
            center_label: None,
            center_value: None,
            size: DonutChartSize::default(),
            show_legend: false,
            show_percentages: false,
            style: StyleRefinement::default(),
        }
    }

    /// 设置扇区。
    pub fn segments(mut self, segments: Vec<PieChartSegment>) -> Self {
        self.segments = segments;
        self
    }

    /// 添加扇区。
    pub fn segment(mut self, segment: PieChartSegment) -> Self {
        self.segments.push(segment);
        self
    }

    /// 设置内半径比例。
    pub fn inner_radius(mut self, ratio: f32) -> Self {
        self.inner_radius = ratio.clamp(0.0, 0.9);
        self
    }

    /// 设置中心标签。
    pub fn center_label(mut self, label: impl Into<SharedString>) -> Self {
        self.center_label = Some(label.into());
        self
    }

    /// 设置中心数值。
    pub fn center_value(mut self, value: impl Into<SharedString>) -> Self {
        self.center_value = Some(value.into());
        self
    }

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

    /// 设置像素尺寸。
    pub fn size_px(mut self, size_val: u32) -> Self {
        self.size = DonutChartSize::Custom(size_val);
        self
    }

    /// 设置是否显示图例。
    pub fn show_legend(mut self, show: bool) -> Self {
        self.show_legend = show;
        self
    }

    /// 设置是否在图例中显示百分比。
    pub fn show_percentages(mut self, show: bool) -> Self {
        self.show_percentages = show;
        self
    }
}

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

/// 根据角度获取扇区颜色。
fn get_color_at_angle(angle: f32, segment_data: &[(f32, f32, Hsla)]) -> Hsla {
    let normalized = if angle < -std::f32::consts::FRAC_PI_2 {
        angle + std::f32::consts::TAU
    } else {
        angle
    };

    for &(start, sweep, color) in segment_data {
        if normalized >= start && normalized < start + sweep {
            return color;
        }
    }

    segment_data
        .last()
        .map(|&(_, _, c)| c)
        .unwrap_or(hsla(0.0, 0.0, 0.5, 1.0))
}

impl RenderOnce for DonutChart {
    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
        let theme = cx.theme();
        let user_style = self.style;
        let chart_size = self.size.to_pixels();
        let show_legend = self.show_legend;
        let show_percentages = self.show_percentages;

        let total: f64 = self.segments.iter().map(|s| s.value).sum();

        let chart = if total == 0.0 || self.segments.is_empty() {
            render_empty(chart_size, theme)
        } else {
            render_donut(
                chart_size,
                &self.segments,
                total,
                self.inner_radius,
                self.center_label.clone(),
                self.center_value.clone(),
                theme,
            )
        };

        let legend = if show_legend {
            Some(render_legend(
                &self.segments,
                total,
                show_percentages,
                theme,
            ))
        } else {
            None
        };

        div()
            .flex()
            .gap(px(24.0))
            .items_center()
            .child(chart)
            .when_some(legend, |this, l| this.child(l))
            .map(|this| {
                let mut d = this;
                d.style().refine(&user_style);
                d
            })
    }
}

/// 渲染空数据占位。
fn render_empty(chart_size: Pixels, theme: &Theme) -> Div {
    div()
        .size(chart_size)
        .rounded(px(9999.0))
        .bg(theme.tokens.muted)
        .flex()
        .items_center()
        .justify_center()
        .child(
            div()
                .text_sm()
                .text_color(theme.tokens.muted_foreground)
                .child("No data"),
        )
}

/// 渲染环形图主体(用点阵近似扇区环)。
fn render_donut(
    chart_size: Pixels,
    segments: &[PieChartSegment],
    total: f64,
    inner_ratio: f32,
    center_label: Option<SharedString>,
    center_value: Option<SharedString>,
    theme: &Theme,
) -> Div {
    let size_f32 = chart_size / px(1.0);
    let center = size_f32 * 0.5;
    let outer_radius = size_f32 * 0.5;
    let inner_radius = outer_radius * inner_ratio;

    let mut segment_data: Vec<(f32, f32, Hsla)> = Vec::new();
    let mut current_angle: f32 = -std::f32::consts::FRAC_PI_2;

    for (idx, segment) in segments.iter().enumerate() {
        if segment.value <= 0.0 {
            continue;
        }
        let fraction = (segment.value / total) as f32;
        let sweep = fraction * std::f32::consts::TAU;
        let color = segment.color.unwrap_or_else(|| default_color(idx));
        segment_data.push((current_angle, sweep, color));
        current_angle += sweep;
    }

    if segment_data.len() == 1 {
        return render_single_segment(
            chart_size,
            segment_data[0].2,
            inner_radius,
            center_label,
            center_value,
            theme,
        );
    }

    let ring_width = outer_radius - inner_radius;
    let ring_count = ((ring_width / 3.0).max(1.0) as usize).min(20);

    let mut container = div()
        .size(chart_size)
        .rounded(px(9999.0))
        .relative()
        .overflow_hidden();

    for ring_idx in 0..ring_count {
        let ring_radius = inner_radius + (ring_idx as f32 + 0.5) * (ring_width / ring_count as f32);
        let circumference = std::f32::consts::TAU * ring_radius;
        let dots_in_ring = (circumference / 4.0).max(16.0) as usize;

        for i in 0..dots_in_ring {
            let angle = -std::f32::consts::FRAC_PI_2
                + (i as f32 / dots_in_ring as f32) * std::f32::consts::TAU;
            let color = get_color_at_angle(angle, &segment_data);
            let x = center + ring_radius * angle.cos() - 2.0;
            let y = center + ring_radius * angle.sin() - 2.0;

            container = container.child(
                div()
                    .absolute()
                    .size(px(5.0))
                    .rounded(px(9999.0))
                    .bg(color)
                    .left(px(x))
                    .top(px(y)),
            );
        }
    }

    let inner_size = inner_radius * 2.0 - 4.0;
    let inner_offset = center - inner_radius + 2.0;

    container = container.child(
        div()
            .absolute()
            .size(px(inner_size))
            .rounded(px(9999.0))
            .bg(theme.tokens.background)
            .left(px(inner_offset))
            .top(px(inner_offset))
            .flex()
            .flex_col()
            .items_center()
            .justify_center()
            .gap(px(2.0))
            .when_some(center_value, |this, val| {
                this.child(
                    div()
                        .text_lg()
                        .font_weight(FontWeight::BOLD)
                        .text_color(theme.tokens.foreground)
                        .child(val),
                )
            })
            .when_some(center_label, |this, lbl| {
                this.child(
                    div()
                        .text_xs()
                        .text_color(theme.tokens.muted_foreground)
                        .child(lbl),
                )
            }),
    );

    container
}

/// 渲染单扇区(整环)。
fn render_single_segment(
    chart_size: Pixels,
    color: Hsla,
    inner_radius: f32,
    center_label: Option<SharedString>,
    center_value: Option<SharedString>,
    theme: &Theme,
) -> Div {
    let size_f32 = chart_size / px(1.0);
    let center = size_f32 * 0.5;
    let inner_size = inner_radius * 2.0;
    let inner_offset = center - inner_radius;

    div()
        .size(chart_size)
        .rounded(px(9999.0))
        .relative()
        .bg(color)
        .child(
            div()
                .absolute()
                .size(px(inner_size))
                .rounded(px(9999.0))
                .bg(theme.tokens.background)
                .left(px(inner_offset))
                .top(px(inner_offset))
                .flex()
                .flex_col()
                .items_center()
                .justify_center()
                .gap(px(2.0))
                .when_some(center_value, |this, val| {
                    this.child(
                        div()
                            .text_lg()
                            .font_weight(FontWeight::BOLD)
                            .text_color(theme.tokens.foreground)
                            .child(val),
                    )
                })
                .when_some(center_label, |this, lbl| {
                    this.child(
                        div()
                            .text_xs()
                            .text_color(theme.tokens.muted_foreground)
                            .child(lbl),
                    )
                }),
        )
}

/// 渲染图例。
fn render_legend(
    segments: &[PieChartSegment],
    total: f64,
    show_percentages: bool,
    theme: &Theme,
) -> Div {
    div()
        .flex()
        .flex_col()
        .gap(px(8.0))
        .children(segments.iter().enumerate().filter_map(|(idx, segment)| {
            if segment.value <= 0.0 {
                return None;
            }

            let color = segment.color.unwrap_or_else(|| default_color(idx));
            let percentage = if total > 0.0 {
                (segment.value / total * 100.0) as u32
            } else {
                0
            };

            Some(
                div()
                    .flex()
                    .items_center()
                    .gap(px(8.0))
                    .child(div().size(px(12.0)).rounded(px(2.0)).bg(color))
                    .child(
                        div()
                            .flex()
                            .flex_1()
                            .items_center()
                            .justify_between()
                            .gap(px(12.0))
                            .child(
                                div()
                                    .text_sm()
                                    .text_color(theme.tokens.foreground)
                                    .child(segment.label.clone()),
                            )
                            .when(show_percentages, |this| {
                                this.child(
                                    div()
                                        .text_sm()
                                        .text_color(theme.tokens.muted_foreground)
                                        .child(format!("{}%", percentage)),
                                )
                            }),
                    ),
            )
        }))
}