WIP(app-iced): M75 组件基座 checkpoint —— 组件骨架/按钮五式/分隔线/gallery harness

已落地:
- components/{mod,interaction,layout,divider,gate}.rs + buttons/{mod,geometry,assemble,tests}.rs
- gallery/{mod,buttons,probe,scan}.rs + 四个家族桩(selection/inputs/feedback/navigation)
- cli.rs: --screen=shell|gallery + capture_flavor(截图默认 Light,删掉等系统主题的闸门)
- app.rs: gallery 路由 + DemoMessage 接线(400 行)

待办(下一个 commit):编译/测试全绿、浅深矩阵出图、1:1 并排与数值表。
This commit is contained in:
AskaEth committed 2026-11-02 04:50:44 +08:00
1 parent 22ddc74784
commit 4774e7b788
23 files changed
+3136 -133

No files matched your search

@@ -0,0 +1,191 @@
//! 装配与样式:五式共用的一条产线(尺寸 / 内边距 / 图标盒 / 状态层 / 描边)。
//!
//! 单独成文件的原因:`mod.rs` 已经是「对外契约 + 变体角色表」,把绘制细节放一起会顶到 400 行红线;
//! 而且这条产线是**唯一**会把「令牌 → 像素」翻一次的地方,独立出来才好审。
use iced::widget::text::LineHeight;
use iced::widget::{button, text, Row};
use iced::{Alignment, Background, Border, Element, Length, Pixels, Shadow};
use unlucky_design::color::Role;
use unlucky_design::elevation::Elevation;
use unlucky_design::shape::ShapeScale;
use unlucky_design::typography::TypeRole;
use crate::icons;
use crate::theme::{Ui, STROKE_PX};
use super::super::interaction::{self, Interaction};
use super::super::layout;
use super::{Geometry, Variant};
/// 一个按钮样式要的全部输入(避免 `style_closure` 长出七个位置参数)。
#[derive(Debug, Clone, Copy)]
pub(super) struct StyleSpec {
/// 容器填充角色;`None` = 透明(Outlined / Text / StandardIcon)。
pub fill: Option<Role>,
/// 内容(文字 + 图标)角色。
pub content: Role,
/// 描边角色;`None` = 无描边。
pub border: Option<Role>,
/// 圆角档位(来自组件表,五式统一 `Full`)。
pub shape: ShapeScale,
/// 圆角折算用的边长(药丸 = 可见高)。
pub radius_side: f32,
/// 强制态(gallery 取证);`Enabled` 时跟随运行期的 `button::Status`。
pub forced: Interaction,
}
/// 五式共用的装配:**只画一处**,五个变体函数都走这里。
pub(super) fn assemble<'a, M: Clone + 'a>(
ui: &'a Ui,
variant: Variant,
spec: super::Button<'a, M>,
) -> Element<'a, M> {
let geometry = Geometry::of(ui, variant, spec.leading.is_some());
let (fill, content, border) = variant.roles();
// 按钮家族没有浮层级高程:L1(Elevated)只用容器色调差表达(rubric §7 不画阴影)
debug_assert!(
!matches!(
variant.elevation(),
Elevation::Level3 | Elevation::Level4 | Elevation::Level5
),
"按钮家族不许有浮层高程"
);
let content_color = ui.color(content);
let label = text(spec.label)
.size(ui.style(TypeRole::LabelLarge).size_px)
.line_height(LineHeight::Absolute(Pixels(
ui.style(TypeRole::LabelLarge).line_height_px,
)))
.font(ui.font_of(ui.emphasized(TypeRole::LabelLarge)))
.color(content_color);
let mut row = Row::new().align_y(Alignment::Center);
if let Some(kind) = spec.leading {
// Q9:图标一律经固定尺寸容器(按钮图标 16、IconButton 24 都不例外)
row = row.push(layout::fixed(
geometry.icon,
geometry.icon,
icons::view::<M>(kind, content_color),
));
}
row = row.push(label);
if let Some(kind) = spec.trailing {
row = row.push(layout::fixed(
geometry.icon,
geometry.icon,
icons::view::<M>(kind, content_color),
));
}
let row = row.spacing(geometry.gap);
// **垂直居中必须在内容侧做**:iced 的 `button::layout` 把内容放在 padding-box 的左上角
// (`layout::padded` 只 `move_to(padding.top)`,不做居中),所以内容自己撑满高度再居中。
// 少了这一层,40 高的按钮里文字会贴上沿 10px(实测首版就是这样)。
let content_box = iced::widget::container(row)
.height(Length::Fill)
.align_y(iced::Alignment::Center);
let forced = spec.state.unwrap_or(if spec.on_press.is_none() {
Interaction::Disabled
} else {
Interaction::Enabled
});
let style = style_closure(
ui,
StyleSpec {
fill,
content,
border,
shape: variant.shape(),
radius_side: geometry.height,
forced,
},
);
let element = button(content_box)
.height(Length::Fixed(geometry.height))
.padding(geometry.padding)
.style(style);
match spec.on_press {
Some(message) => element.on_press(message).into(),
None => element.into(),
}
}
/// 生成 `button::style` 闭包:状态层 / 禁用 / 描边全在这里落地。
pub(super) fn style_closure(
ui: &Ui,
spec: StyleSpec,
) -> impl Fn(&iced::Theme, button::Status) -> button::Style + '_ {
move |_theme: &iced::Theme, status| {
// 强制态优先(gallery 状态矩阵),否则把 iced 的四态翻成 M3 五态
let state = match spec.forced {
Interaction::Enabled => Interaction::from_status(status),
forced => forced,
};
let (background, text_color) = if state.is_disabled() {
let (container, content) = interaction::disabled_colors(ui, Role::Surface);
// 透明容器在禁用态依然透明(官方只改内容透明度)
(spec.fill.map(|_| container), content)
} else {
// 有填充:状态层叠在**容器角色**上;透明容器:叠在表面色上(否则 hover 看不见)
let background = match spec.fill {
Some(role) => match state.layer() {
Some(_) => interaction::overlay_color(ui, state, spec.content, role)
.or(Some(ui.color(role))),
None => Some(ui.color(role)),
},
None => transparent_state_color(ui, state, spec.content),
};
(background, ui.color(spec.content))
};
let border_color = if state.is_disabled() {
interaction::disabled_colors(ui, Role::Surface).0
} else {
spec.border
.map_or_else(|| ui.color(Role::OutlineVariant), |role| ui.color(role))
};
button::Style {
background: background.map(Background::Color),
text_color,
border: Border {
color: if spec.border.is_some() {
border_color
} else {
iced::Color::TRANSPARENT
},
width: if spec.border.is_some() {
STROKE_PX
} else {
0.0
},
radius: ui.radius(spec.shape, spec.radius_side),
},
// rubric §7:L0/L1 不用阴影(Elevated 的 L1 由容器色调差表达)
shadow: Shadow::default(),
snap: true,
}
}
}
/// 透明容器的状态层:`Outlined` / `Text` / `StandardIcon` 没有填充,可见反馈只能来自
/// 叠在**内容角色**上的状态层——把它们当作「叠在表面色上」求值,得到不透明实色。
///
/// 之所以单独一个函数:这是 M3 里唯一「容器不存在但状态层存在」的情形,
/// 三个变体共用一条口径,免得各自发挥。
pub(super) fn transparent_state_color(
ui: &Ui,
state: Interaction,
content: Role,
) -> Option<iced::Color> {
interaction::overlay_color(ui, state, content, Role::Surface)
}
@@ -0,0 +1,93 @@
//! 按钮家族的**内部几何**:一个数值都不写,全部由 `unlucky_design` 的令牌推导。
//!
//! | 量 | 令牌 | 值(DESKTOP / 100% DPI) |
//! |---|---|---|
//! | 可见高 | `LayoutMetrics::control_height` | 40 `[源]` 12b 1.1 |
//! | 圆角 | `ShapeScale::Full.radius_px(高)` | 20 `[源]` 12b 1.2 |
//! | 左右内边距(无图标) | `Space::X6` | 24 / 24 `[源]` 12b 1.3 |
//! | 左内边距(带前置图标) | `Space::X4` | 16 `[源]` 12b 1.4 |
//! | 图标边长 | `IconSize::Button` | 16(**官方 18 → G14 偏离**) |
//! | 图标↔文字 | `Space::X2` | 8 `[源]` 12b 1.6 |
//! | 描边 | `unlucky_design::stroke::HAIRLINE`(`crate::theme::STROKE_PX` 同一真源) | 1 `[源]` rubric G7 |
//! | IconButton 边长 | `LayoutMetrics::control_height` | 40 `[源]` 12b 2.1 |
//! | IconButton 图标 / 边距 | `IconSize::Toolbar` / `Space::X2` | 24 / 8 `[源]` 12b 2.2 |
//!
//! **没有落点的两个参考值**(登记在报告里,不在此处写数):
//!
//! - 12b 1.7 最小宽 **58** → `G15`:iced 的 `Length` 没有 min-width 语义;按「24 + 24 内边距 +
//! LabelLarge 二字」自然宽度 ≈ 76,实际不触发,故本 mission 不施加该约束;
//! - 12b 1.6 图标 **18** → `G14`:令牌层 `IconSize::Button` 是 16、没有 18 档,
//! 组件层又不许写字面量 → 先用 16 并登记 2px 偏离。
//!
//! 这两条是**能力缺口不是审美选择**,登记后由令牌层(`crates/design`)补档位。
use iced::Padding;
use unlucky_design::icons::IconSize;
use unlucky_design::spacing::Space;
use crate::theme::{Ui, STROKE_PX};
use super::Variant;
/// 文字按钮的几何。
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Geometry {
/// 可见高(药丸圆角按它折算)。
pub height: f32,
/// 内边距(上下 0;左右按有无前置图标取 16 或 24)。
pub padding: Padding,
/// 图标盒边长。
pub icon: f32,
/// 图标 ↔ 文字间距。
pub gap: f32,
/// 描边宽度;`0` = 该式无描边。
pub stroke: f32,
}
impl Geometry {
/// 按变体 + 有没有前置图标求值(带图标时左内边距收到 16,右仍 24)。
pub fn of(ui: &Ui, variant: Variant, leading_icon: bool) -> Self {
let (_, _, border) = variant.roles();
let start = if leading_icon {
ui.space(Space::X4)
} else {
ui.space(Space::X6)
};
Self {
height: ui.metrics().control_height,
padding: Padding {
top: 0.0,
right: ui.space(Space::X6),
bottom: 0.0,
left: start,
},
icon: IconSize::Button.px(),
gap: ui.space(Space::X2),
stroke: if border.is_some() { STROKE_PX } else { 0.0 },
}
}
}
/// IconButton 的几何(正方形,图标 24、边距 8)。
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct IconGeometry {
/// 容器边长(40,命中区 48 由父级留白补足)。
pub side: f32,
/// 图标盒边长(24)——**必须**经 `layout::centered_fixed` 锁住,否则 Q9 会把字形撑满。
pub icon: f32,
/// 图标到容器边的默认边距(8;narrow 4 / wide 14 属变体参数,本 mission 不用)。
pub padding: f32,
}
impl IconGeometry {
/// 从令牌求值。
pub fn of(ui: &Ui) -> Self {
Self {
side: ui.metrics().control_height,
icon: IconSize::Toolbar.px(),
padding: ui.space(Space::X2),
}
}
}
@@ -0,0 +1,321 @@
//! 按钮家族(`research/12b` §1 五式 + §2 IconButton)。
//!
//! ## 参考值(全部 `[源]` = A1,`material3-android:1.4.0` 的 `*Tokens.kt` / `Button.kt`)
//!
//! | # | 检查项 | 参考值 | 本模块落点 |
//! |---|---|---|---|
//! | 1.1 | 容器可见高 | **40** | `LM.control_height`([`Geometry::height`]) |
//! | 1.2 | 圆角 | **full = 高/2 = 20** | `ShapeScale::Full` + `Ui::radius` |
//! | 1.3 | 水平内边距(无图标) | **24 / 24** | `Space::X6` |
//! | 1.4 | 水平内边距(带前置图标) | **16(左)/ 24(右)** | `Space::X4` / `Space::X6` |
//! | 1.5 | 字级 | **LabelLarge 14/20 w500** | `TypeRole::LabelLarge` 强调档 |
//! | 1.6 | 图标 18 + 图标↔文字 8 | 图标见 **G14 偏离**(令牌只有 16);间距 `Space::X2` | [`Geometry`] |
//! | 1.7 | 最小宽 58 | **G15**:iced 的 `Length` 无 min-width,不施加(实测见报告) | — |
//! | 1.8 | 状态层 + 禁用 | hover 8 / focus 10 / pressed 10;容器 12% & 内容 38% | [`super::interaction`] |
//! | 1.9 | 五式色彩角色 | Filled `Primary`/`OnPrimary`;Tonal `SecondaryContainer`/`OnSecondaryContainer`;Elevated `SurfaceContainerLow`/`Primary`;Outlined 透明 + 1dp `OutlineVariant` + `OnSurfaceVariant`;Text 透明 + `OnSurfaceVariant` | [`Variant::roles`] |
//! | 2.1 | IconButton 容器 | **40×40**、圆角 full | [`IconGeometry`] |
//! | 2.2 | IconButton 图标 / 边距 | 图标 **24**、边距 **8** | [`IconGeometry`] |
//! | 2.4 | Standard 各态**图标色不变** | 只有状态层变化 | [`Variant::roles`] 与态无关 |
//! | 2.7 | IconButton 禁用 | 内容 `OnSurface`@38% | [`super::interaction::disabled_colors`] |
//! | 2.8 | 命中区 | 容器 40 + 四周各 4 = **48** | `LM.touch_target`(按钮自身不撑高) |
//!
//! ## 与契约 §2 的签名差异(**已登记,请 tower 确认**)
//!
//! 契约 §2 的示例签名是 `filled(ui, label, on_press)`——三个参数装不下
//! 「五式 × 五态 × 前后双图标 × 禁用」。所以本模块的落地是**契约的加法版**:
//! 泛型纪律一字不改(`M: Clone`,不碰 `app::Message`),但把前两个参数收进 [`Button`]:
//!
//! ```text
//! 契约示例: filled(ui, "保存", Message::Save)
//! 本模块: filled(ui, Button::new("保存").press(Message::Save))
//! ```
//!
//! 差别只是「label + 消息」两件事从位置参数变成构造器参数,语义一一对应;
//! 要图标/禁用/焦点取证时再加链式调用(`.leading(..)` / `Button::disabled(..)` / `.state(..)`),
//! 不需要第二个签名。**这是本周唯一一处偏离契约示例的地方**,报告「决策」一节有登记。
//!
//! ## 为什么不用 iced 内置的 `theme::Button` 样式
//!
//! iced 的内置按钮样式只有 `primary/success/danger/text` 几档,且**不带 M3 的状态层 α**
//! (读的是 `Palette` 现成色)。D30 要求 hover 8% / pressed 10% 可判定,所以样式自绘;
//! 但**只画颜色与描边**——尺寸仍由 `button` 的 width/height/padding 决定,不手搓几何。
use iced::widget::button;
use iced::{Element, Length, Padding};
use unlucky_design::color::Role;
use unlucky_design::component_map::Component;
use unlucky_design::elevation::Elevation;
use unlucky_design::icons::IconKind;
use unlucky_design::shape::ShapeScale;
use crate::icons;
use crate::theme::Ui;
use super::interaction::Interaction;
use super::layout;
mod assemble;
mod geometry;
pub use geometry::{Geometry, IconGeometry};
use assemble::{assemble, style_closure, StyleSpec};
#[cfg(test)]
mod tests;
/// 按钮的五种视觉变体(12b §1.9 的色彩角色,一名一式)。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Variant {
/// 实心强调色:**每屏最多一个**(rubric K2)。
Filled,
/// 次强调(tonal):`SecondaryContainer`。
Tonal,
/// 带高程:`SurfaceContainerLow` + `Primary` 文本(L1 用色调差,不画阴影)。
Elevated,
/// 描边:透明容器 + 1dp `OutlineVariant`。
Outlined,
/// 纯文本:最低权重。
Text,
}
impl Variant {
/// 五式全序(gallery 的矩阵按这个次序出图)。
pub const ALL: [Variant; 5] = [
Variant::Filled,
Variant::Tonal,
Variant::Elevated,
Variant::Outlined,
Variant::Text,
];
/// 稳定名字(图例 / 文件名 / 失败信息用)。
pub const fn name(self) -> &'static str {
match self {
Variant::Filled => "filled",
Variant::Tonal => "tonal",
Variant::Elevated => "elevated",
Variant::Outlined => "outlined",
Variant::Text => "text",
}
}
/// 该式在组件表里的档位(圆角/字级)。`Component` 没有 `Outlined/Elevated` 变体,
/// 借用 `PrimaryButton`:三者判据值相同(`Full` 圆角 + `LabelLarge` + L0)。
pub(crate) const fn component(self) -> Component {
match self {
Variant::Filled => Component::PrimaryButton,
Variant::Tonal => Component::SecondaryButton,
Variant::Text => Component::TextButton,
Variant::Elevated | Variant::Outlined => Component::PrimaryButton,
}
}
/// 圆角档位(五式统一 `Full`,12b 1.2)。
pub(crate) fn shape(self) -> ShapeScale {
self.component().spec().shape
}
/// 高程:只有 Elevated 是 L1(`ElevatedButtonTokens.ContainerElevation`),其余 L0。
///
/// **不画阴影**:rubric §7「L0/L1 不应有可见阴影(用 tone 差)」,所以 L1 只体现为
/// `SurfaceContainerLow` 容器色,`button::Style.shadow` 永远 default。
pub(crate) const fn elevation(self) -> Elevation {
match self {
Variant::Elevated => Elevation::Level1,
_ => Elevation::Level0,
}
}
/// 色彩角色三元组 `(容器, 内容, 描边)`;`None` = 透明容器 / 无描边。
pub(crate) const fn roles(self) -> (Option<Role>, Role, Option<Role>) {
match self {
Variant::Filled => (Some(Role::Primary), Role::OnPrimary, None),
Variant::Tonal => (
Some(Role::SecondaryContainer),
Role::OnSecondaryContainer,
None,
),
Variant::Elevated => (Some(Role::SurfaceContainerLow), Role::Primary, None),
Variant::Outlined => (None, Role::OnSurfaceVariant, Some(Role::OutlineVariant)),
Variant::Text => (None, Role::OnSurfaceVariant, None),
}
}
}
/// IconButton 的三种容器变体(12b §2.5)。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum IconVariant {
/// 标准:容器透明、图标 `OnSurfaceVariant`(各态图标色不变,12b 2.4)。
Standard,
/// 实心:`Primary` + `OnPrimary`。
Filled,
/// Tonal:`SecondaryContainer` + `OnSecondaryContainer`。
Tonal,
}
impl IconVariant {
/// 三式全序(gallery 顺序)。
pub const ALL: [IconVariant; 3] = [
IconVariant::Standard,
IconVariant::Filled,
IconVariant::Tonal,
];
/// 稳定名字。
pub const fn name(self) -> &'static str {
match self {
IconVariant::Standard => "standard",
IconVariant::Filled => "filled",
IconVariant::Tonal => "tonal",
}
}
/// 色彩角色三元组(同 [`Variant::roles`] 的口径)。
pub(crate) const fn roles(self) -> (Option<Role>, Role, Option<Role>) {
match self {
IconVariant::Standard => (None, Role::OnSurfaceVariant, None),
IconVariant::Filled => (Some(Role::Primary), Role::OnPrimary, None),
IconVariant::Tonal => (
Some(Role::SecondaryContainer),
Role::OnSecondaryContainer,
None,
),
}
}
}
/// 一个按钮的装配描述(五式共用;**不持有任何状态所有权**)。
///
/// `on_press: Option<M>` 就是 M3 的 enabled/disabled 开关——`None` = 禁用,
/// 与 `button::on_press_maybe` 的语义天然对齐(省掉一个 `disabled: bool` 字段,
/// 也就不会出现「有消息但画成禁用」这种自相矛盾的状态)。
#[derive(Debug, Clone)]
pub struct Button<'a, M> {
label: &'a str,
on_press: Option<M>,
leading: Option<IconKind>,
trailing: Option<IconKind>,
state: Option<Interaction>,
}
impl<'a, M> Button<'a, M> {
/// 一个可点的按钮。
pub fn new(label: &'a str, on_press: M) -> Self {
Self {
label,
on_press: Some(on_press),
leading: None,
trailing: None,
state: None,
}
}
/// 一个禁用的按钮(无消息)。禁用不是「另一种颜色」,见 `interaction::disabled_colors`。
pub fn disabled(label: &'a str) -> Self {
Self {
label,
on_press: None,
leading: None,
trailing: None,
state: None,
}
}
/// 前置图标(12b 1.4:带图标时左内边距收到 16)。
pub fn leading(mut self, kind: IconKind) -> Self {
self.leading = Some(kind);
self
}
/// 后置图标(右内边距保持 24)。
pub fn trailing(mut self, kind: IconKind) -> Self {
self.trailing = Some(kind);
self
}
/// 强制视觉态(`--screen=gallery` 的状态矩阵取证用;运行期不要调)。
pub fn state(mut self, state: Interaction) -> Self {
self.state = Some(state);
self
}
}
/// Filled 按钮(实心 `Primary`)。
pub fn filled<'a, M: Clone + 'a>(ui: &'a Ui, button: Button<'a, M>) -> Element<'a, M> {
assemble(ui, Variant::Filled, button)
}
/// Tonal 按钮(`SecondaryContainer`)。
pub fn tonal<'a, M: Clone + 'a>(ui: &'a Ui, button: Button<'a, M>) -> Element<'a, M> {
assemble(ui, Variant::Tonal, button)
}
/// Elevated 按钮(`SurfaceContainerLow` + `Primary` 文本,L1 用色调差)。
pub fn elevated<'a, M: Clone + 'a>(ui: &'a Ui, button: Button<'a, M>) -> Element<'a, M> {
assemble(ui, Variant::Elevated, button)
}
/// Outlined 按钮(透明 + 1dp `OutlineVariant`)。
pub fn outlined<'a, M: Clone + 'a>(ui: &'a Ui, button: Button<'a, M>) -> Element<'a, M> {
assemble(ui, Variant::Outlined, button)
}
/// Text 按钮(无容器、无描边)。
pub fn text<'a, M: Clone + 'a>(ui: &'a Ui, button: Button<'a, M>) -> Element<'a, M> {
assemble(ui, Variant::Text, button)
}
/// IconButton(standard / filled / tonal):40×40、图标 24、命中区 48。
///
/// `on_press: Option<M>`(`None` = 禁用)与 `state` 分开给:前者是语义,后者是取证开关。
pub fn icon<'a, M: Clone + 'a>(
ui: &'a Ui,
variant: IconVariant,
kind: IconKind,
on_press: Option<M>,
state: Option<Interaction>,
) -> Element<'a, M> {
let geometry = IconGeometry::of(ui);
let (fill, content, border) = variant.roles();
let forced = state.unwrap_or(if on_press.is_some() {
Interaction::Enabled
} else {
Interaction::Disabled
});
// Q9:图标**必须在固定尺寸的中层容器里**,否则 Button 的 Fill 约束会让 usvg 按 Contain
// 撑满内容区(M68:24 的字形渲染成 46px、线宽 1.5 → 2.9)。
// 这里把盒子做成整个 40×40(而不是 24×24):`button::layout` 把内容放左上角、不居中,
// 所以「居中」这件事必须由容器自己写死,别指望 button。
let icon_box = layout::centered_fixed(
geometry.side,
geometry.side,
icons::view::<M>(kind, ui.color(content)),
);
let style = style_closure(
ui,
StyleSpec {
fill,
content,
border,
// 方形图标按钮同样是 full 圆角(40 → 20),档位取自组件表
shape: Component::IconButton.spec().shape,
radius_side: geometry.side,
forced,
},
);
let element = button(icon_box)
.width(Length::Fixed(geometry.side))
.height(Length::Fixed(geometry.side))
.padding(Padding::default())
.style(style);
match on_press {
Some(message) => element.on_press(message).into(),
None => element.into(),
}
}
@@ -0,0 +1,317 @@
//! 按钮家族的单测(几何值 / 色彩角色 / 样式闭包)。
//!
//! 这里测的是「函数与样式结构」;**像素级**的几何(40 高、20 圆角、24 图标盒)
//! 由 `gallery/probe.rs` 对着真截图量——M68 的教训是「函数对、图错」,两者缺一不可。
use iced::widget::button;
use iced::{Background, Shadow};
use unlucky_design::color::SchemeFlavor;
use unlucky_design::elevation::Elevation;
use unlucky_design::icons::IconKind;
use unlucky_design::spacing::Space;
use super::super::interaction::{self, Interaction};
use super::assemble::StyleSpec;
use super::{style_closure, Geometry, IconGeometry, IconVariant, Variant};
use crate::theme::{Families, Ui, STROKE_PX};
const FAMILIES: Families = Families {
text: "Segoe UI",
display: "Segoe UI",
mono: "Consolas",
};
fn ui(flavor: SchemeFlavor) -> Ui {
Ui::with_platform(
flavor,
unlucky_design::typography::Platform::Windows,
FAMILIES,
)
}
fn light() -> Ui {
ui(SchemeFlavor::Light)
}
#[derive(Debug, Clone, PartialEq)]
enum Msg {
Pressed(&'static str),
}
#[test]
fn every_variant_builds_and_disabled_has_no_message() {
let ui = light();
let _ = super::filled(&ui, super::Button::new("Filled", Msg::Pressed("f")));
let _ = super::tonal(&ui, super::Button::new("Tonal", Msg::Pressed("t")));
let _ = super::elevated(&ui, super::Button::new("Elevated", Msg::Pressed("e")));
let _ = super::outlined(&ui, super::Button::new("Outlined", Msg::Pressed("o")));
let _ = super::text(&ui, super::Button::new("Text", Msg::Pressed("x")));
let _ = super::filled::<Msg>(&ui, super::Button::disabled("Disabled"));
let _ = super::filled(
&ui,
super::Button::new("Icons", Msg::Pressed("i"))
.leading(IconKind::Plus)
.trailing(IconKind::ChevronRight),
);
}
/// 12b 1.1~1.6 + 2.1~2.2:几何逐值钉住(每个值都要能指回令牌)。
#[test]
fn geometry_matches_the_reference_values() {
let ui = light();
let geometry = Geometry::of(&ui, Variant::Filled, false);
assert_eq!(geometry.height, 40.0, "12b 1.1 可见高 40");
assert_eq!(geometry.height, ui.metrics().control_height);
assert_eq!(
ui.radius(unlucky_design::shape::ShapeScale::Full, geometry.height)
.top_left,
20.0,
"12b 1.2 full 圆角 = 高/2"
);
assert_eq!(geometry.padding.left, 24.0, "12b 1.3 左 24");
assert_eq!(geometry.padding.right, 24.0, "12b 1.3 右 24");
assert_eq!(geometry.padding.top, 0.0);
assert_eq!(geometry.gap, 8.0, "12b 1.6 图标↔文字 8");
assert_eq!(geometry.gap, ui.space(Space::X2));
assert_eq!(geometry.stroke, 0.0, "实心按钮无描边");
let with_icon = Geometry::of(&ui, Variant::Filled, true);
assert_eq!(with_icon.padding.left, 16.0, "12b 1.4 带图标左内边距 16");
assert_eq!(with_icon.padding.right, 24.0, "带图标右内边距不动");
let outlined = Geometry::of(&ui, Variant::Outlined, false);
assert_eq!(outlined.stroke, STROKE_PX, "rubric G7 全站 1px");
assert_eq!(outlined.stroke, 1.0);
// 图标 16 是**令牌值**;官方 18 是 G14 登记的偏离(不在这里假装相等)
assert_eq!(geometry.icon, 16.0, "IconSize::Button");
assert_eq!(geometry.height % 4.0, 0.0, "可见高必须在 4px 栅格上(D1)");
}
#[test]
fn icon_button_geometry_matches_the_reference() {
let ui = light();
let geometry = IconGeometry::of(&ui);
assert_eq!((geometry.side, geometry.icon), (40.0, 24.0), "12b 2.1/2.2");
assert_eq!(
ui.radius(unlucky_design::shape::ShapeScale::Full, geometry.side)
.top_left,
20.0,
"40×40 的 full 圆角 = 20"
);
assert_eq!(geometry.padding, 8.0, "12b 2.2 默认边距 8");
// 命中区 = 容器 40 + 四周各 4(12b 2.8);按钮自身不撑高
assert_eq!(
geometry.side + 2.0 * ui.space(Space::X1),
ui.metrics().touch_target,
"40 + 8 = 48 命中下限"
);
}
#[test]
fn five_variants_have_distinct_colour_roles() {
let mut seen = Vec::new();
for variant in Variant::ALL {
let roles = variant.roles();
assert!(
!seen.contains(&roles),
"{variant:?} 与别的变体色彩角色重复了"
);
seen.push(roles);
}
// 12b 1.9 逐条角色名核对
assert_eq!(
Variant::Filled.roles(),
(
Some(unlucky_design::color::Role::Primary),
unlucky_design::color::Role::OnPrimary,
None
)
);
assert_eq!(
Variant::Tonal.roles(),
(
Some(unlucky_design::color::Role::SecondaryContainer),
unlucky_design::color::Role::OnSecondaryContainer,
None
)
);
assert_eq!(
Variant::Elevated.roles(),
(
Some(unlucky_design::color::Role::SurfaceContainerLow),
unlucky_design::color::Role::Primary,
None
)
);
assert_eq!(
Variant::Outlined.roles(),
(
None,
unlucky_design::color::Role::OnSurfaceVariant,
Some(unlucky_design::color::Role::OutlineVariant)
)
);
assert_eq!(
Variant::Text.roles(),
(None, unlucky_design::color::Role::OnSurfaceVariant, None)
);
for variant in Variant::ALL {
let expected = if variant == Variant::Elevated {
Elevation::Level1
} else {
Elevation::Level0
};
assert_eq!(variant.elevation(), expected, "{variant:?} 高程");
}
}
#[test]
fn icon_button_variants_match_the_reference_roles() {
use unlucky_design::color::Role;
assert_eq!(
IconVariant::Standard.roles(),
(None, Role::OnSurfaceVariant, None)
);
assert_eq!(
IconVariant::Filled.roles(),
(Some(Role::Primary), Role::OnPrimary, None)
);
assert_eq!(
IconVariant::Tonal.roles(),
(
Some(Role::SecondaryContainer),
Role::OnSecondaryContainer,
None
)
);
let ui = light();
for variant in IconVariant::ALL {
let _ = super::icon::<Msg>(&ui, variant, IconKind::Settings, None, None);
let _ = super::icon(
&ui,
variant,
IconKind::Settings,
Some(Msg::Pressed("i")),
None,
);
// 五态取证开关都能出元素(gallery 矩阵依赖它)
for state in Interaction::ALL {
let _ = super::icon(
&ui,
variant,
IconKind::Settings,
Some(Msg::Pressed("i")),
Some(state),
);
}
}
}
fn spec_of(variant: Variant, forced: Interaction) -> StyleSpec {
let (fill, content, border) = variant.roles();
StyleSpec {
fill,
content,
border,
shape: variant.shape(),
radius_side: Geometry::of(&light(), variant, false).height,
forced,
}
}
/// **渲染层**:样式闭包吐给 iced 的圆角/描边/阴影必须是令牌推导值。
#[test]
fn outlined_style_draws_hairline_border_and_full_radius() {
let ui = light();
let style = style_closure(&ui, spec_of(Variant::Outlined, Interaction::Enabled));
let idle = style(&ui.theme(), button::Status::Active);
assert_eq!(idle.background, None, "Outlined 静息容器必须透明");
assert_eq!(idle.border.width, STROKE_PX, "1dp 描边");
assert_eq!(idle.border.radius.top_left, 20.0, "full 圆角");
assert_eq!(
idle.border.color,
ui.color(unlucky_design::color::Role::OutlineVariant)
);
assert_eq!(idle.shadow, Shadow::default(), "L0 不许有阴影");
// 透明容器也要看得见 hover:状态层叠到表面色上
let hovered = style(&ui.theme(), button::Status::Hovered);
assert_ne!(hovered.background, None, "透明容器的 hover 必须有可见变化");
assert_ne!(hovered.background, idle.background);
let disabled = style(&ui.theme(), button::Status::Disabled);
let (container, content) =
interaction::disabled_colors(&ui, unlucky_design::color::Role::Surface);
assert_eq!(disabled.text_color, content, "禁用内容 = 令牌 38%");
assert_eq!(disabled.border.color, container, "禁用描边 = 令牌 12%");
}
#[test]
fn filled_button_state_layers_are_visible_and_ordered() {
let ui = light();
let style = style_closure(&ui, spec_of(Variant::Filled, Interaction::Enabled));
let idle = style(&ui.theme(), button::Status::Active);
let hovered = style(&ui.theme(), button::Status::Hovered);
let pressed = style(&ui.theme(), button::Status::Pressed);
assert_eq!(
idle.background,
Some(Background::Color(
ui.color(unlucky_design::color::Role::Primary)
))
);
assert_ne!(hovered.background, idle.background, "hover 8%");
assert_ne!(
pressed.background, hovered.background,
"pressed 10% ≠ hover 8%"
);
assert_eq!(
hovered.text_color,
ui.color(unlucky_design::color::Role::OnPrimary),
"12b 2.4/4.7:状态层不换内容色"
);
assert_eq!(idle.border.width, 0.0, "实心按钮无描边");
}
#[test]
fn forced_state_overrides_the_runtime_status() {
let ui = light();
let style = style_closure(&ui, spec_of(Variant::Tonal, Interaction::Hovered));
// 运行期说 Active,但取证要 hover → 必须画 hover
assert_eq!(
style(&ui.theme(), button::Status::Active).background,
style(&ui.theme(), button::Status::Hovered).background
);
assert_ne!(
style(&ui.theme(), button::Status::Active).background,
Some(Background::Color(
ui.color(unlucky_design::color::Role::SecondaryContainer)
))
);
}
#[test]
fn elevated_uses_a_tone_not_a_shadow() {
let ui = light();
let style = style_closure(&ui, spec_of(Variant::Elevated, Interaction::Enabled));
let idle = style(&ui.theme(), button::Status::Active);
assert_eq!(idle.shadow, Shadow::default(), "rubric §7:L1 不画阴影");
assert_eq!(
idle.background,
Some(Background::Color(
ui.color(unlucky_design::color::Role::SurfaceContainerLow)
)),
"L1 由 SurfaceContainerLow 的色调差表达"
);
assert_eq!(
idle.text_color,
ui.color(unlucky_design::color::Role::Primary)
);
}