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
//! 单选框组件,支持互斥选择的圆形选择控件。

use std::sync::Arc;

use crate::elements::checkbox::checkbox_check_icon;
use crate::prelude::FluentBuilder as _;
use crate::{
    ActiveTheme, AnyElement, App, Axis, ComponentText, Disableable, ElementId, ElementSize,
    FocusableExt as _, InteractiveElement, IntoElement, ParentElement, RenderOnce, Selectable,
    SharedString, Sizable, StatefulInteractiveElement, StyleRefinement, Styled, StyledExt as _,
    Window, div, h_flex, px, relative, rems, v_flex,
};

/// 单选按钮(Radio)元素。
///
/// 不包含 RadioGroup 实现,可自行管理分组。
#[derive(IntoElement)]
pub struct Radio {
    /// 基础 Div 元素
    base: crate::Div,
    /// 样式精炼
    style: StyleRefinement,
    /// 元素 ID
    id: ElementId,
    /// 标签文本
    label: Option<ComponentText>,
    /// 子元素
    children: Vec<AnyElement>,
    /// 是否选中
    checked: bool,
    /// 是否禁用
    disabled: bool,
    /// 是否为 Tab 停靠点
    tab_stop: bool,
    /// Tab 索引
    tab_index: isize,
    /// 尺寸
    size: ElementSize,
    /// 值变更回调(参数为变更后的选中状态,按值传递)
    on_change: Option<Arc<dyn Fn(bool, &mut Window, &mut App) + Send + Sync + 'static>>,
    /// 提示文本(当前简化存储,暂不渲染)
    tooltip: Option<SharedString>,
}

impl Radio {
    /// 创建带有指定 id 的新 Radio 元素。
    pub fn new(id: impl Into<ElementId>) -> Self {
        Self {
            id: id.into(),
            base: div(),
            style: StyleRefinement::default(),
            label: None,
            children: Vec::new(),
            checked: false,
            disabled: false,
            tab_index: 0,
            tab_stop: true,
            size: ElementSize::default(),
            on_change: None,
            tooltip: None,
        }
    }

    /// 设置 Radio 的提示文本。
    pub fn tooltip(mut self, tooltip: impl Into<SharedString>) -> Self {
        self.tooltip = Some(tooltip.into());
        self
    }

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

    /// 设置 Radio 的选中状态,默认为 `false`。
    pub fn checked(mut self, checked: bool) -> Self {
        self.checked = checked;
        self
    }

    /// 设置 Radio 的禁用状态,默认为 `false`。
    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    /// 设置 Radio 的 Tab 索引,默认为 `0`。
    pub fn tab_index(mut self, tab_index: isize) -> Self {
        self.tab_index = tab_index;
        self
    }

    /// 设置 Radio 是否为 Tab 停靠点,默认为 `true`。
    pub fn tab_stop(mut self, tab_stop: bool) -> Self {
        self.tab_stop = tab_stop;
        self
    }

    /// 添加 Radio 的值变更回调。
    ///
    /// `bool` 参数表示点击后的**新选中状态**(按值传递)。
    pub fn on_change(
        mut self,
        handler: impl Fn(bool, &mut Window, &mut App) + Send + Sync + 'static,
    ) -> Self {
        self.on_change = Some(Arc::new(handler));
        self
    }

    fn handle_change(
        on_change: &Option<Arc<dyn Fn(bool, &mut Window, &mut App) + Send + Sync + 'static>>,
        checked: bool,
        window: &mut Window,
        cx: &mut App,
    ) {
        let new_checked = !checked;
        if let Some(f) = on_change {
            (f)(new_checked, window, cx);
        }
    }
}

impl Sizable for Radio {
    fn with_size(mut self, size: impl Into<ElementSize>) -> Self {
        self.size = size.into();
        self
    }
}

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

impl InteractiveElement for Radio {
    fn interactivity(&mut self) -> &mut crate::Interactivity {
        self.base.interactivity()
    }
}

impl StatefulInteractiveElement for Radio {}

impl ParentElement for Radio {
    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
        self.children.extend(elements);
    }
}

impl Disableable for Radio {
    fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }
}

impl Selectable for Radio {
    fn selected(self, selected: bool) -> Self {
        self.checked(selected)
    }

    fn is_selected(&self) -> bool {
        self.checked
    }
}

impl From<&'static str> for Radio {
    fn from(label: &'static str) -> Self {
        Self::new(label).label(label)
    }
}

impl From<SharedString> for Radio {
    fn from(label: SharedString) -> Self {
        Self::new(label.clone()).label(label)
    }
}

impl From<String> for Radio {
    fn from(label: String) -> Self {
        Self::new(SharedString::from(label.clone())).label(SharedString::from(label))
    }
}

impl RenderOnce for Radio {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let checked = self.checked;
        let focus_handle = window
            .use_keyed_state(self.id.clone(), cx, |_, cx| cx.focus_handle())
            .read(cx)
            .clone();
        let is_focused = focus_handle.is_focused(window);
        let disabled = self.disabled;

        let (border_color, bg) = if checked {
            (cx.theme().primary, cx.theme().primary)
        } else {
            (cx.theme().input, cx.theme().input.opacity(0.5))
        };
        let (border_color, bg) = if disabled {
            (border_color.opacity(0.5), bg.opacity(0.5))
        } else {
            (border_color, bg)
        };

        // 包裹一个 flex 以修复 Radio 的 inline 显示
        div().child(
            self.base
                .id(self.id.clone())
                .when(!self.disabled, |this| {
                    this.track_focus(
                        &focus_handle
                            .tab_stop(self.tab_stop)
                            .tab_index(self.tab_index),
                    )
                })
                .h_flex()
                .gap_x_2()
                .text_color(cx.theme().foreground)
                .items_start()
                .line_height(relative(1.))
                .rounded(cx.theme().radius * 0.5)
                .focus_ring(is_focused, px(2.), window, cx)
                .map(|this| match self.size {
                    ElementSize::XSmall => this.text_xs(),
                    ElementSize::Small => this.text_sm(),
                    ElementSize::Medium => this.text_base(),
                    ElementSize::Large => this.text_lg(),
                    _ => this,
                })
                .refine_style(&self.style)
                .child(
                    div()
                        .relative()
                        .map(|this| match self.size {
                            ElementSize::XSmall => this.size_3(),
                            ElementSize::Small => this.size_3p5(),
                            ElementSize::Medium => this.size_4(),
                            ElementSize::Large => this.size(rems(1.125)),
                            _ => this.size_4(),
                        })
                        .flex_shrink_0()
                        .rounded_full()
                        .border_1()
                        .border_color(border_color)
                        .when(cx.theme().shadow && !disabled, |this| this.shadow_xs())
                        .map(|this| match self.checked {
                            false => this.bg(cx.theme().input_background()),
                            true if disabled => this.bg(bg),
                            true => this.bg(cx.theme().tokens.primary),
                        })
                        .child(checkbox_check_icon(
                            self.id, self.size, checked, disabled, window, cx,
                        )),
                )
                .when(!self.children.is_empty() || self.label.is_some(), |this| {
                    this.child(
                        v_flex()
                            .w_full()
                            .line_height(relative(1.2))
                            .gap_1()
                            .when_some(self.label, |this, label| {
                                this.child(
                                    div()
                                        .size_full()
                                        .line_height(relative(1.))
                                        .when(self.disabled, |this| {
                                            this.text_color(cx.theme().muted_foreground)
                                        })
                                        .child(label),
                                )
                            })
                            .children(self.children),
                    )
                })
                .on_mouse_down(crate::MouseButton::Left, |_, window, _| {
                    // 避免在鼠标按下时获得焦点
                    window.prevent_default();
                })
                .when(!self.disabled, |this| {
                    this.on_click({
                        let on_change = self.on_change.clone();
                        move |_, window, cx| {
                            window.prevent_default();
                            Self::handle_change(&on_change, checked, window, cx);
                        }
                    })
                }),
        )
    }
}

/// 单选按钮组(RadioGroup)元素。
#[derive(IntoElement)]
pub struct RadioGroup {
    /// 元素 ID
    id: ElementId,
    /// 样式精炼
    style: StyleRefinement,
    /// 子 Radio 列表
    radios: Vec<Radio>,
    /// 布局方向
    layout: Axis,
    /// 选中的索引
    selected_index: Option<usize>,
    /// 是否禁用
    disabled: bool,
    /// 选中索引变化回调(参数为选中的索引,按值传递)
    on_change: Option<Arc<dyn Fn(usize, &mut Window, &mut App) + Send + Sync + 'static>>,
}

impl RadioGroup {
    /// 创建新的 RadioGroup,默认垂直布局。
    fn new(id: impl Into<ElementId>) -> Self {
        Self {
            id: id.into(),
            style: StyleRefinement::default().flex_1(),
            on_change: None,
            layout: Axis::Vertical,
            selected_index: None,
            disabled: false,
            radios: vec![],
        }
    }

    /// 创建默认垂直布局的 RadioGroup。
    pub fn vertical(id: impl Into<ElementId>) -> Self {
        Self::new(id)
    }

    /// 创建水平布局的 RadioGroup。
    pub fn horizontal(id: impl Into<ElementId>) -> Self {
        Self::new(id).layout(Axis::Horizontal)
    }

    /// 设置 RadioGroup 的布局方向。默认为 `Axis::Vertical`。
    pub fn layout(mut self, layout: Axis) -> Self {
        self.layout = layout;
        self
    }

    /// 添加选中索引变化回调。
    ///
    /// `usize` 参数表示选中的索引(按值传递)。
    pub fn on_change(
        mut self,
        handler: impl Fn(usize, &mut Window, &mut App) + Send + Sync + 'static,
    ) -> Self {
        self.on_change = Some(Arc::new(handler));
        self
    }

    /// 设置选中的索引。
    pub fn selected_index(mut self, index: Option<usize>) -> Self {
        self.selected_index = index;
        self
    }

    /// 设置禁用状态。
    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    /// 添加一个子 Radio 元素。
    pub fn child(mut self, child: impl Into<Radio>) -> Self {
        self.radios.push(child.into());
        self
    }

    /// 添加多个子 Radio 元素。
    pub fn children(mut self, children: impl IntoIterator<Item = impl Into<Radio>>) -> Self {
        self.radios.extend(children.into_iter().map(Into::into));
        self
    }
}

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

impl RenderOnce for RadioGroup {
    fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
        let on_change = self.on_change;
        let disabled = self.disabled;
        let selected_ix = self.selected_index;

        let base = if self.layout == Axis::Vertical {
            v_flex()
        } else {
            h_flex().w_full().flex_wrap()
        };

        let mut container = div().id(self.id);
        *container.style() = self.style;

        container.child(
            base.gap_3()
                .children(self.radios.into_iter().enumerate().map(|(ix, mut radio)| {
                    let checked = selected_ix == Some(ix);

                    radio.id = ix.into();
                    radio.disabled(disabled).checked(checked).when_some(
                        on_change.clone(),
                        |this, on_change| {
                            this.on_change(move |_, window, cx| {
                                on_change(ix, window, cx);
                            })
                        },
                    )
                })),
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// 测试 Radio 基本构造
    #[test]
    fn test_radio_build() {
        let r = Radio::new("test-radio")
            .label("选项 A")
            .checked(true)
            .with_size(ElementSize::Small);
        assert!(r.checked);
        assert!(r.label.is_some());
    }

    /// 测试从字符串构造 Radio
    #[test]
    fn test_radio_from_str() {
        let r: Radio = "选项 B".into();
        assert_eq!(r.id, ElementId::from("选项 B"));
        assert!(r.label.is_some());
    }

    /// 测试 RadioGroup 构造与布局
    #[test]
    fn test_radio_group_build() {
        let group = RadioGroup::horizontal("test-group")
            .selected_index(Some(1))
            .child(Radio::new("r1").label("A"))
            .child(Radio::new("r2").label("B"));
        assert_eq!(group.radios.len(), 2);
        assert_eq!(group.selected_index, Some(1));
        assert_eq!(group.layout, Axis::Horizontal);
    }
}