主题与设计令牌
在 crate 的 Cargo.toml 同级目录放置 rsx.toml,即可统一管理全项目的设计令牌与宏默认选项。静态 class 字面量会在编译期解析令牌并直接展开为原生 GPUI builder 调用,没有任何运行时查表开销。
1. 定义设计令牌
Section titled “1. 定义设计令牌”从一份精简的令牌配置开始:
[colors]brand = "#2563eb"
[radius]card = "12px"
[spacing]gutter = "18px"
[text-size]body = "14px"
[line-height]body = "20px"
[opacity]muted = "60%"在静态 class 中直接使用这些语义名称:
rsx! { <div class="flex flex-col gap-gutter p-gutter rounded-card"> <h1 class="text-brand font-bold">{"项目概览"}</h1> <p class="text-size-body leading-body opacity-muted"> {"跨视图共享统一的视觉词表。"} </p> </div>}令牌到 GPUI 方法的映射
Section titled “令牌到 GPUI 方法的映射”rsx.toml 分组 |
示例工具类 | 展开后的 GPUI 方法 |
|---|---|---|
colors |
bg-brand、text-brand、border-brand |
.bg()、.text_color()、.border_color() |
radius |
rounded-card |
.rounded() |
spacing |
p-gutter、gap-gutter |
.p()、.gap() 及各方向变体 |
text-size |
text-size-body |
.text_size() |
line-height |
leading-body |
.line_height() |
opacity |
opacity-muted |
.opacity() |
shadow |
shadow-card |
.shadow() |
校验规则: 长度值必须带显式单位(如
"12px");透明度支持带引号的小数("0.6")或百分比("60%")。重复键、非法值或冲突的text-size-*会在校验阶段直接报错。
2. 跟随应用主题(gpui-component 预设)
Section titled “2. 跟随应用主题(gpui-component 预设)”启用内置的 gpui-component 预设后,可直接获得 bg-background、text-foreground、bg-primary 等语义类:
[options]preset = "gpui-component"# context = "cx" # 默认值;若渲染上下文变量名不同可在此修改在宏展开处导入 ActiveTheme 并确保 cx 在作用域内:
use gpui::component::ActiveTheme as _;use gpui::prelude::*;use gpui::*;use gpui_rsx::rsx;
// 在 Render::render 中(包含 cx: &mut Context<Self>):rsx! { <div class="bg-background text-foreground p-[24px]"> {"自动响应当前激活的应用主题。"} </div>}预设会生成类似 cx.theme().colors.background 的表达式。若在 [colors] 中定义了同名令牌,自定义值会覆盖预设项;十六进制字面量始终表示固定颜色。组件接入方式请参阅 gpui-component 集成。
3. Rust 表达式令牌与阴影
Section titled “3. Rust 表达式令牌与阴影”任意令牌都可以通过 { expr = "..." } 在渲染时求值一段 Rust 表达式:
[colors]surface = { expr = "cx.theme().colors.background" }
[shadow]card = { expr = "vec![BoxShadow::new(px(0.0), px(1.0), hsla(0.0, 0.0, 0.0, 0.2))]" }使用时直接写 class="bg-surface shadow-card"。表达式中引用的所有标识符(如 BoxShadow、px、hsla、cx)必须在宏展开作用域内可见。
4. 检查与诊断配置
Section titled “4. 检查与诊断配置”安装 cargo-rsx 后,可在终端快速校验并追踪任意令牌的展开结果:
cargo rsx theme check --manifest-path demo/Cargo.tomlcargo rsx theme list --manifest-path demo/Cargo.tomlcargo rsx theme explain hover:opacity-muted --manifest-path demo/Cargo.toml三条命令均支持 --json 输出(校验失败退出码为 1,用法错误为 2)。编辑器 LSP 复用同一套配置解析器。
5. Crate 级 [options] 配置
Section titled “5. Crate 级 [options] 配置”除 preset 外,rsx.toml 还支持集中配置三项 crate 级宏选项:
[options]preset = "gpui-component"spacing-scale = "tailwind" # 开启 4px 间距刻度(gap-4 -> 16px)dynamic-runtime = "rsx_runtime" # 在多处动态 class 间共享运行时匹配器gpui-path = "::engine" # 可选:覆盖默认的 ::gpui 路径