Checkbox
指示器可独立设置样式的受控三态复选框。
和所有 GPUI Base 原语一样,Checkbox 只提供行为和语义结构,不规定产品视觉语言。请使用 GPUI 样式并组合导出的部件,使其符合你的设计系统。
示例
原生示例和页面上方的 WASM 预览共用同一份实现:
bash
cargo run -p gpui-base --example components -- checkbox导入
rust
use gpui_base::{Checkbox, CheckboxIndicator};结构与 API
示例组合上述公开类型。GPUI 的标准样式和事件 trait 负责表现,Base 类型负责交互结构。权威实现位于 components/checkbox.rs,原生与浏览器预览编译的是同一文件。
状态与事件
父级持有选中、未选中或不确定状态,并在激活时更新。
受控状态应保存在父渲染类型或 GPUI entity 中;在回调中更新并调用 cx.notify(),不要在每次渲染时重建持久 entity。
完整 Rust 示例
rust
use super::*;
use gpui::{Image, ImageFormat, img};
use std::sync::Arc;
const CHECK_SVG: &[u8] = br#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="none"><path d="m3.25 8.25 3 3 6.5-7" stroke="white" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg>"#;
impl BaseShowcase {
pub(in super::super) fn checkbox(&self, cx: &mut Context<Self>) -> impl IntoElement {
let checked = self.checkbox_checked;
let entity = cx.entity().downgrade();
Checkbox::new("example-checkbox")
.checked(checked)
.flex()
.items_center()
.gap_2()
.on_change(move |state, _, _, cx| {
_ = entity.update(cx, |this, cx| {
this.checkbox_checked = state == CheckboxState::Checked;
cx.notify();
});
})
.child(
CheckboxIndicator::new()
.checked(checked)
.flex()
.items_center()
.justify_center()
.size_4()
.border_1()
.border_color(super::example_rgb(0x171717))
.when(checked, |this| {
this.bg(super::example_rgb(0x171717)).child(
img(Arc::new(Image::from_bytes(
ImageFormat::Svg,
CHECK_SVG.to_vec(),
)))
.size(px(12.)),
)
}),
)
.child(div().text_xs().child("Enable product updates"))
}
}可访问性
暴露复选框角色、当前状态、标签和禁用状态。
注意事项
在支持的位置使用稳定元素 ID,并在消费端设计系统中验证焦点、悬停、按下、选中、禁用、减少动态效果和高对比度状态。