常用界面写法
覆盖状态绑定与阈值变色、弹性伸缩布局、弹簧跟随框、自定义矢量控件、曲线排字与滚动视口。
状态绑定与阈值换色
声明一个可观察字段,让数字读数、百分比条宽度与满载告警色在同一帧联动,无需手写同步回调。
//~focus-start:reactive
#[model]
pub struct Gauge {
#[observe]
pub level: i32,
}
impl Default for Gauge {
fn default() -> Self {
Self { level: 42 }
}
}
#[model]
impl Gauge {
pub fn step(&mut self, delta: i32) {
self.level = (self.level + delta).clamp(0, 100);
}
}
#[compose]
fn reactive_scene(gauge: model!(Gauge)) {
ui! {
Column (
grow: 1.0,
padding: Padding::all(20),
justify: JustifyContent::SpaceBetween,
text_color: ColorToken::OnSurface
) {
Row (height: 28, justify: JustifyContent::SpaceBetween, align: AlignItems::Center) {
Text (
"Signal binding",
grow: 1.0,
height: 20,
font_size: 14,
text_color: ColorToken::OnSurfaceVariant,
paragraph: ParagraphStyle::label().with_align(TextAlign::Start)
)
Text (
text: ${ format_args!("{} %", gauge.level()) },
capacity: 12,
grow: 1.0,
font_size: 22,
height: 28,
paragraph: ParagraphStyle::label().with_align(TextAlign::End)
)
}
View (height: 14, bg_color: ColorToken::SurfaceVariant, border_radius: 7, clip_children: true) {
View (
width: ${ Dimension::percent(gauge.level()) },
height: Dimension::percent(100),
bg_color: ${ if gauge.level() >= 80 { ColorToken::Primary } else { ColorToken::Secondary } },
border_radius: 7
)
}
Row (height: 40, column_gap: 8) {
Button (
"- 10",
grow: 1.0,
height: 40,
border_radius: 9,
normal_color: ColorToken::SurfaceVariant,
pressed_color: ColorToken::Outline,
text_color: ColorToken::OnSurface
) on Tap { gauge.step(-10); }
Button (
"42",
width: 64,
height: 40,
border_radius: 9,
normal_color: ColorToken::SurfaceVariant,
pressed_color: ColorToken::Outline,
text_color: ColorToken::OnSurfaceVariant
) on Tap { gauge.step(42 - gauge.level()); }
Button (
"+ 10",
grow: 1.0,
height: 40,
border_radius: 9,
normal_color: ColorToken::Primary,
pressed_color: ColorToken::Secondary,
text_color: ColorToken::OnPrimary
) on Tap { gauge.step(10); }
}
}
};
}
//~focus-end:reactive#[observe] 为 level 生成 gauge.level() 读取器。${ Dimension::percent(gauge.level()) } 与 ${ if gauge.level() >= 80 ... } 各自订阅同一个字段;调用 gauge.step(10) 时,只有受影响的宽度与背景色重新计算。
弹性宽度与剩余空间分配
左侧主卡片在紧凑与展开宽度之间切换,右侧容器用 grow: 1.0 自动填满剩余行宽。
//~focus-start:layout
#[model]
#[derive(Default)]
pub struct FlexDeck {
#[observe]
pub compact: bool,
}
#[model]
impl FlexDeck {
pub fn toggle(&mut self) {
self.compact = !self.compact;
}
}
#[compose]
fn layout_scene(deck: model!(FlexDeck)) {
ui! {
Column (
grow: 1.0,
padding: Padding::all(18),
row_gap: 12,
text_color: ColorToken::OnSurface
) {
Row (height: 34, column_gap: 8, align: AlignItems::Center) {
Text (
text: ${ if deck.compact() { "Compact · 96 px card" } else { "Expanded · 156 px card" } },
capacity: 28,
grow: 1.0,
min_width: 0,
height: 22,
font_size: 13,
text_color: ColorToken::OnSurfaceVariant,
paragraph: ParagraphStyle::label().with_align(TextAlign::Start)
)
Button (
"Toggle width",
width: 112,
height: 32,
font_size: 12,
border_radius: 8,
normal_color: ColorToken::Primary,
pressed_color: ColorToken::Secondary,
text_color: ColorToken::OnPrimary
) on Tap { deck.toggle(); }
}
Row (
grow: 1.0,
padding: Padding::all(14),
column_gap: 10,
align: AlignItems::Center,
justify: JustifyContent::SpaceBetween,
bg_color: ColorToken::SurfaceVariant,
border_radius: 12
) {
Column (
width: ${ Dimension::px(if deck.compact() { 96 } else { 156 }) },
height: 76,
padding: Padding::all(10),
justify: JustifyContent::SpaceBetween,
bg_color: ColorToken::Surface,
border_radius: 9
) {
View (width: 24, height: 6, bg_color: ColorToken::Primary, border_radius: 3)
Text ("Primary", font_size: 12, height: 18)
}
Column (
grow: 1.0,
height: 76,
padding: Padding::all(10),
justify: JustifyContent::SpaceBetween,
bg_color: ColorToken::Surface,
border_radius: 9
) {
View (width: 36, height: 6, bg_color: ColorToken::Secondary, border_radius: 3)
Text ("Flex grow: 1.0", font_size: 12, height: 18, text_color: ColorToken::OnSurfaceVariant)
}
}
}
};
}
//~focus-end:layout固定尺寸(Dimension::px)与弹性分配(grow: 1.0)写在同一行里。当响应式宽度改变时,布局阶段只重算这一行的几何位置。
弹簧跟随框 (FollowBounds)
选中外框独立于按钮之外;在不同宽度的标签之间快速切换时,外框会在半途继承当前速度平滑折返并自适应目标宽度。
//~focus-start:spring,mini-motion
#[model]
#[derive(Default)]
pub struct SpringTabs {
#[observe]
pub active: u8,
}
#[event]
fn pick_tab(
index: u8,
tabs: model!(SpringTabs),
target: entity!(),
followers: query!(mut FollowBounds),
) {
tabs.set_active(index);
for follower in followers {
follower.target = target;
}
}
#[model]
impl SpringTabs {
pub fn set_active(&mut self, index: u8) {
self.active = index;
}
}
#[compose]
fn spring_scene(tabs: model!(SpringTabs), reduced: bool) {
ui! {
Column (
grow: 1.0,
padding: Padding::all(20),
justify: JustifyContent::SpaceBetween,
text_color: ColorToken::OnSurface
) {
Text (
"Tap any pill — FollowBounds retargets mid-flight",
height: 22,
font_size: 13,
text_color: ColorToken::OnSurfaceVariant,
paragraph: ParagraphStyle::label().with_align(TextAlign::Start)
)
Row (
height: 52,
padding: Padding::all(5),
column_gap: 6,
align: AlignItems::Center,
bg_color: ColorToken::SurfaceVariant,
border_radius: 12
) {
Button (
"MCU",
id: "spring_first",
grow: 1.0,
height: 38,
border_radius: 8,
normal_color: ColorToken::Surface,
pressed_color: ColorToken::SurfaceVariant,
text_color: ColorToken::OnSurface
) on Tap(pick_tab::callback(0, tabs))
Button (
"Desktop",
grow: 1.4,
height: 38,
border_radius: 8,
normal_color: ColorToken::Surface,
pressed_color: ColorToken::SurfaceVariant,
text_color: ColorToken::OnSurface
) on Tap(pick_tab::callback(1, tabs))
Button (
"Web",
grow: 1.0,
height: 38,
border_radius: 8,
normal_color: ColorToken::Surface,
pressed_color: ColorToken::SurfaceVariant,
text_color: ColorToken::OnSurface
) on Tap(pick_tab::callback(2, tabs))
//~add-start:mini-motion
View (
id: "spring_ring",
border_width: 2,
border_color: ColorToken::Primary,
border_radius: 9
) [
FollowBounds::new(id("spring_first"))
.with_transition(indicator_transition(reduced)),
]
//~add-end:mini-motion
}
Text (
text: ${
match tabs.active() {
0 => "Target 01 · SPI framebuffer with dirty-rect clips",
1 => "Target 02 · Batched GPU draws with retained textures",
_ => "Target 03 · Browser canvas driven by requestAnimationFrame",
}
},
height: 20,
font_size: 12,
text_color: ColorToken::OnSurfaceVariant,
paragraph: ParagraphStyle::label().with_align(TextAlign::Start)
)
}
};
}
//~focus-end:spring,mini-motion外框本身只是一个不占 Flex 空间的 View,挂载 FollowBounds::new(id("spring_first")) 后,在 #[event] 回调里把 follower.target 指向刚被点击的 entity!(),弹簧便会自动接管位置与宽高的过渡。
自定义矢量控件 (#[view])
当内置控件不够用时,用 #[component] 与 #[view] 定义新控件标签,直接向渲染管线提交矢量路径与描边。
//~focus-start:vector
static APERTURE_BLADE: Path = path!(M 50 6 L 94 50 L 50 94 L 6 50 Z);
static INNER_RING: Path = path!(M 50 24 L 76 50 L 50 76 L 24 50 Z);
const ACCENTS: [Color; 3] = [
Color::rgb(52, 82, 255),
Color::rgb(207, 67, 43),
Color::rgb(42, 157, 143),
];
#[component]
#[derive(Clone, Copy)]
pub struct VectorGlyph {
pub accent: i32,
pub stroke: i32,
}
impl Default for VectorGlyph {
fn default() -> Self {
Self {
accent: 0,
stroke: 2,
}
}
}
impl VectorGlyph {
fn cycle(self) -> Self {
Self {
accent: (self.accent + 1) % 3,
stroke: if self.stroke >= 4 { 2 } else { self.stroke + 1 },
}
}
}
#[view(component = VectorGlyph, name = "VectorGlyph", priority = 60)]
fn paint_glyph(glyph: component!(), paint: paint!()) {
let rect = paint.rect();
let transform = paint
.transform()
.compose(&Transform::translate(rect.x, rect.y))
.compose(&Transform::scale(
rect.w / Fixed::from_int(100),
rect.h / Fixed::from_int(100),
));
let color = ACCENTS[(glyph.accent.rem_euclid(3)) as usize];
let stroke_paint = Paint::Color(color.into());
let dash: [Fixed; 0] = [];
paint.draw(&DrawCommand::StrokePath {
path: &APERTURE_BLADE,
transform,
paint: &stroke_paint,
width: Fixed::from_int(glyph.stroke),
opa: 255,
line_cap: LineCap::Round,
line_join: LineJoin::Round,
miter_limit: Fixed::from_int(4),
dash: &dash,
});
paint.draw(&DrawCommand::StrokePath {
path: &INNER_RING,
transform,
paint: &stroke_paint,
width: Fixed::from_int(1),
opa: 180,
line_cap: LineCap::Round,
line_join: LineJoin::Round,
miter_limit: Fixed::from_int(4),
dash: &dash,
});
}
#[compose]
fn vector_scene() {
ui! {
Column (
grow: 1.0,
padding: Padding::all(18),
justify: JustifyContent::SpaceBetween,
text_color: ColorToken::OnSurface
) {
Text (
"Custom #[view] — tap any tile to cycle stroke & pigment",
height: 20,
font_size: 13,
text_color: ColorToken::OnSurfaceVariant,
paragraph: ParagraphStyle::label().with_align(TextAlign::Start)
)
Row (
grow: 1.0,
justify: JustifyContent::SpaceEvenly,
align: AlignItems::Center,
column_gap: 12
) {
VectorGlyph (
accent: 0,
stroke: 2,
width: 72,
height: 72,
bg_color: ColorToken::SurfaceVariant,
border_radius: 16
) on Tap(|ev: event!(Tap), q: query!(VectorGlyph), cmd: commands!()| {
if let Some(next) = q.get(ev.target).copied().map(VectorGlyph::cycle) {
cmd.insert(ev.target, next);
}
})
VectorGlyph (
accent: 1,
stroke: 3,
width: 72,
height: 72,
bg_color: ColorToken::SurfaceVariant,
border_radius: 16
) on Tap(|ev: event!(Tap), q: query!(VectorGlyph), cmd: commands!()| {
if let Some(next) = q.get(ev.target).copied().map(VectorGlyph::cycle) {
cmd.insert(ev.target, next);
}
})
VectorGlyph (
accent: 2,
stroke: 4,
width: 72,
height: 72,
bg_color: ColorToken::SurfaceVariant,
border_radius: 16
) on Tap(|ev: event!(Tap), q: query!(VectorGlyph), cmd: commands!()| {
if let Some(next) = q.get(ev.target).copied().map(VectorGlyph::cycle) {
cmd.insert(ev.target, next);
}
})
}
}
};
}
//~focus-end:vectorpath!(...) 在编译期构造零堆分配的静态矢量路径;#[view(component = VectorGlyph)] 把组件注册成可在 ui! 中直接书写的标签,并在绘制阶段把 100 × 100 的局部坐标系缩放到控件的实际布局矩形 paint.rect()。
沿贝塞尔曲线排字 (TextPath)
把整形后的字形贴合到静态或响应式的贝塞尔曲线上,动态滑动起始偏移或切换路径。
//~focus-start:curve
static WAVE_CREST: Path = path!(M 8 64 Q 60 18 112 64 Q 164 110 216 64);
static WAVE_VALLEY: Path = path!(M 8 50 Q 60 96 112 50 Q 164 4 216 50);
#[model]
pub struct CurveRoute {
crest: PathId,
valley: PathId,
#[observe]
pub inverted: bool,
#[observe]
pub offset: i32,
}
impl CurveRoute {
pub fn new(crest: PathId, valley: PathId) -> Self {
Self {
crest,
valley,
inverted: false,
offset: 4,
}
}
}
#[model]
impl CurveRoute {
#[observe]
pub fn placement(&self) -> TextPath {
let path = if self.inverted {
self.valley
} else {
self.crest
};
TextPath::new(path).with_offset(Fixed::from_int(self.offset))
}
pub fn flip(&mut self) {
self.inverted = !self.inverted;
}
pub fn advance(&mut self) {
self.offset = (self.offset + 14) % 42;
}
}
#[compose]
fn curve_scene(route: model!(CurveRoute)) {
ui! {
Column (
grow: 1.0,
padding: Padding::all(16),
row_gap: 10,
text_color: ColorToken::OnSurface
) {
Row (height: 30, column_gap: 6, align: AlignItems::Center) {
Text (
text: ${ format_args!("+{} px", route.offset()) },
capacity: 16,
grow: 1.0,
min_width: 0,
height: 22,
font_size: 13,
text_color: ColorToken::OnSurfaceVariant,
paragraph: ParagraphStyle::label().with_align(TextAlign::Start)
)
Button (
"Slide +14",
width: 72,
height: 28,
font_size: 12,
border_radius: 7,
normal_color: ColorToken::SurfaceVariant,
pressed_color: ColorToken::Outline,
text_color: ColorToken::OnSurface
) on Tap { route.advance(); }
Button (
"Flip wave",
width: 74,
height: 28,
font_size: 12,
border_radius: 7,
normal_color: ColorToken::Primary,
pressed_color: ColorToken::Secondary,
text_color: ColorToken::OnPrimary
) on Tap { route.flip(); }
}
View (
grow: 1.0,
bg_color: ColorToken::SurfaceVariant,
border_radius: 12,
clip_children: true
) {
Text (
"mirui rides the wave",
path: ${ route.placement() },
position: Position::Absolute,
left: 6,
top: 8,
width: Dimension::percent(96),
height: Dimension::percent(88),
font_size: 14,
text_color: ColorToken::Primary
)
}
}
};
}
//~focus-end:curveapp.paths().insert_static(...) 注册编译期 Path 并返回轻量的 PathId。Text 绑定 path: ${ route.placement() } 后,每当偏移量或目标路径改变,字形就会沿着曲线切线重新排布。
滚动视口与平滑定位 (ScrollOffset)
给裁剪容器挂上滚动能力,既支持手指拖拽与滚轮,也能通过 commands.scroll_to 配合 ScrollConfig::with_transition 平滑滑向指定位置。
//~focus-start:scroll
#[compose]
fn scroll_item(title: &'static str) -> Entity {
ui! {
Row (
height: 38,
shrink: 0.0,
padding: Padding::all(10),
align: AlignItems::Center,
bg_color: ColorToken::Surface,
border_radius: 8
) {
Text (title, height: 18, font_size: 13)
}
}
}
#[compose]
fn scroll_button(label: &'static str, list: Entity, y: i32, primary: bool) -> Entity {
ui! {
Button (
label,
grow: 1.0,
height: 30,
font_size: 12,
border_radius: 7,
normal_color: if primary { ColorToken::Primary } else { ColorToken::SurfaceVariant },
pressed_color: if primary { ColorToken::Secondary } else { ColorToken::Outline },
text_color: if primary { ColorToken::OnPrimary } else { ColorToken::OnSurface }
) on Tap {
commands!().scroll_to(
list,
ScrollOffset {
x: Fixed::ZERO,
y: Fixed::from_int(y),
},
);
}
}
}
#[compose]
fn scroll_scene(reduced: bool) {
ui! {
Column (
grow: 1.0,
padding: Padding::all(16),
row_gap: 10,
text_color: ColorToken::OnSurface
) {
Row (height: 32, column_gap: 6, align: AlignItems::Center) {
scroll_button ("Top (#1)", id("scroll_list"), 0, false)
scroll_button ("Middle (#4)", id("scroll_list"), 132, false)
scroll_button ("Bottom (#7)", id("scroll_list"), 264, true)
}
Column (
id: "scroll_list",
grow: 1.0,
min_height: 0,
padding: Padding::all(8),
row_gap: 6,
bg_color: ColorToken::SurfaceVariant,
border_radius: 10,
clip_children: true
) [
ScrollOffset::default(),
ScrollConfig::default().with_transition(indicator_transition(reduced)),
] {
scroll_item ("01 · FramebufSurface (MCU SPI)")
scroll_item ("02 · SdlSurface (Desktop CPU)")
scroll_item ("03 · SdlGpuSurface (OpenGL / Metal)")
scroll_item ("04 · WgpuSurface (Vulkan / DX12)")
scroll_item ("05 · WebCanvasSurface (Browser)")
scroll_item ("06 · LinuxDrmSurface (KMS / GBM)")
scroll_item ("07 · NuttxSurface (Embedded RTOS)")
}
}
};
}
//~focus-end:scroll在 Column(clip_children: true) 上挂载 ScrollOffset::default() 与 ScrollConfig::default().with_transition(...) 即可启用滚动视口;直接赋值 scroll_offset: 属性是立即定位,而调用 commands.scroll_to(list, offset)(或 scroll_into)则会沿着 ScrollConfig 配置的过渡曲线平滑滚动。