Topcoat UI 组件安装与主题定制实战指南:用 `topcoat ui` 构建可改写的 Rust 组件库

原创2026-11-11 20:12:081,924 阅读
文章标签:后端Web框架前端

Topcoat UI 组件安装与主题定制实战指南:用 topcoat ui 构建可改写的 Rust 组件库

Topcoat UI 是 Topcoat 框架内置的组件方案,它的核心思路不是“引入一个黑盒依赖”,而是把组件源码直接复制进你的项目,让你像维护自己的代码一样修改它。本文以官方 docs/ui.md 为主线,完整覆盖从 topcoat ui init、Tailwind 接入、topcoat ui add、组件使用约定,到主题定制、更新与移除、自定义 registry 的全流程,并结合 crates/topcoat-ui 与 crates/topcoat-cli/src/ui 的源码解释每条命令背后的行为边界。读完后,你可以独立完成一个带主题、可定制、可升级的 Topcoat UI 组件层。

设计模型:源码即组件

Topcoat UI 提供的不是运行时组件库,而是一套“可复制的源码 + 一份主题样式表”:

  • 组件源码使用 #<a href="https://link.gitcode.com/i/b135cc28be3f508c2e9443307c5d6154" target="_blank">component]、view! 与 Tailwind 类,安装后就是你自己 crate 里的普通模块(见 [crates/topcoat-ui/registry/src/components/button.rs)。
  • 颜色、边框、阴影等共享样式来自主题样式表 styles.css,由 topcoat ui init 从 registry 中安装(见 crates/topcoat-ui/registry/themes/neutral.css)。
  • 安装状态记录在 components.toml,用于判断组件是否已安装、是否需要更新。

这套模型带来两个直接后果:第一,组件的行为可以按项目需要任意修改;第二,升级是“重新复制源码”而不是“升级依赖版本”,因此你需要理解覆盖语义(后文“更新组件”一节)。

环境准备

先完成两件前置工作:安装 topcoat CLI,并接入 Tailwind 集成,然后启用 ui feature。官方示例同时启用 Fontsource,用于加载主题声明的字体:

[dependencies]
topcoat = { version = "0.12.0", features = ["font-fontsource", "tailwind", "ui"] }

[build-dependencies]
topcoat = { version = "0.12.0", default-features = false, features = ["tailwind"] }

关于 feature 的语义,可以从 crates/topcoat/Cargo.toml 确认:ui = <a href="https://link.gitcode.com/i/6a89da50ffb522d12be482e2b1a69c71" target="_blank">"dep:topcoat-ui-registry"],即该 feature 只负责把内置 registry crate 纳入依赖图。CLI 在解析内置 registry 时依赖这一点——如果 topcoat-ui-registry 不在依赖图中,命令会报错提示启用 ui feature(见 [crates/topcoat-ui/src/manage/workspace.rs)。

仓库中的 examples/ui/Cargo.toml 是可直接参考的完整配置,它还额外启用了 icon-iconify,用于图标组件。

初始化包

在包目录下执行:

topcoat ui init

该命令会创建 components.toml 用于跟踪已安装组件,并把主题写入 styles.css。这两个文件都应纳入版本控制。必须在使用其他 UI 子命令前先执行 init——add、list、remove 都会从 components.toml 读取安装状态,缺失时会提示 run \topcoat ui init` first`(见 crates/topcoat-ui/src/manage/state.rs)。

参数与选择规则

场景 用法 源码行为
多个主题可选 topcoat ui init --theme neutral 未指定且主题多于一个时会交互式选择;只有一个主题时直接安装,不弹出选择器
自定义组件目录 topcoat ui init --components-dir src/ui 目录会写入 components.toml 的 components_dir,默认 src/components
工作区中选择成员 topcoat ui init --package my-app 通过 cargo metadata 解析包根目录,等价于 cargo -p 的定位方式

主题选择逻辑位于 crates/topcoat-ui/src/manage/init.rs:显式 --theme 会先校验名称,未知主题会列出可用主题;未指定且仅有一个主题时直接使用;否则调用选择回调。非交互环境下(例如 CI)无法提示,命令会要求你显式传 --theme(见 crates/topcoat-cli/src/ui/init.rs)。

初始化做了什么

init 采用“先规划、后落盘”的顺序,仓库源码对此有明确注释:先解析 registry、读取主题 CSS、决定目标路径,全部成功后才写文件,因此 registry 不可达或主题名错误不会留下半初始化的包(见 crates/topcoat-ui/src/manage/init.rs)。目标文件固定为包根目录的 styles.css(crates/topcoat-ui/src/registry.rs)。

已初始化的包不能再次 init:components.toml 存在时会直接报错。这一约束保证了安装状态不会被覆盖,也意味着后续自定义 styles.css 是安全的——UI 命令不会重写它。

初始化后的 components.toml 结构如下(取自 examples/ui/components.toml):

# Topcoat UI install state. Managed by `topcoat ui`.
version = 1
components_dir = "src/components"

[theme]
name = "neutral"
registry = "topcoat"
hash = "sha256:5e370e648fef95d78c8b048d99be7f7d79fd82132f8c9cc1ce854d3b73024137"
file = "styles.css"

[registries.topcoat.components.button]
hash = "sha256:53bddb06a7db178a09d1e9395c1edb5e055b5f50107e8d4708ca029ecc1593af"
file = "src/components/button.rs"

三个字段值得注意:version 是安装状态格式版本,高于当前支持版本会被拒绝;theme 记录主题来源与哈希;registries.<name>.components.<component> 记录每个组件的源码哈希与落地路径。哈希算法是 SHA-256,并以 sha256: 前缀呈现(见 crates/topcoat-ui/src/registry.rs)。

把主题接入 Tailwind

init 完成后,styles.css 就是你的 Tailwind 输入文件。它已经包含 Tailwind 导入、主题 token,以及让 Tailwind 扫描 Rust 源码的指令。在 build.rs 中指定它:

fn main() {
    topcoat::tailwind::BuildConfig::new()
        .input("styles.css")
        .render()
        .unwrap();
}

CLI 在初始化结束时会主动打印这条提示,因为“主题装好了但没接进 Tailwind”时页面不会有任何样式(见 crates/topcoat-cli/src/ui/init.rs)。

解剖 styles.css

理解生成文件的内容,才能判断哪些地方可以改、哪些地方不要动。关键片段如下(完整文件见 crates/topcoat-ui/registry/themes/neutral.css):

@import "tailwindcss";

/* 扫描项目的 Rust 源码,提取其中使用的 Tailwind 类 */
@source "./src/**/*.rs";

/* 暗色模式通过祖先元素上的 `dark` 类开启 */
@custom-variant dark (&:is(.dark *));

@theme inline {
  --font-sans: "Geist", sans-serif;
  --color-background: var(--background);
  --color-primary: var(--primary);
  --shadow-xs: var(--shadow-xs);
  --shadow-sm: var(--shadow-sm);
  /* ...其余 token 映射 */
}

@theme inline 的作用是把 :root / .dark 上的普通 CSS 变量映射为 Tailwind 工具类(bg-background、text-primary、border-border 等)。正是这层间接映射,使得切换 .dark 时所有颜色自动跟随。@source 指向 ./src/**/*.rs,前提是 styles.css 位于 crate 根目录——文件注释也说明了这一点。

如果你把组件装到了自定义目录,Tailwind 仍会扫描 ./src,因此只要目录在 src 下即可正常生成类;若放在 src 之外,就需要相应调整 @source。

加载样式表与字体

在根布局中加载生成的样式表。如果主题声明了 Web 字体,也要一并加载。以 Fontsource 集成加载 Geist 为例(对应 docs/font.md):

use topcoat::{
    Result,
    context::Cx,
    font::fontsource::fontsource_font,
    router::{Slot, layout},
    tailwind,
    view::{View, view},
};

#[layout]
async fn layout(cx: &Cx, slot: Slot<'_>) -> Result<impl View> {
    Ok(view! {
        <!DOCTYPE html>
        <html>
            <head>
                topcoat::font::link(font: fontsource_font!(GEIST))
                <link rel="stylesheet" href=(tailwind::stylesheet!())>
            </head>
            <body>
                (slot)
            </body>
        </html>
    })
}

tailwind::stylesheet!() 展开为一个资产引用,指向构建脚本生成的样式表(见 crates/topcoat-tailwind/src/stylesheet.rs)。样式表加载后,主题会把基础样式应用到 <body>:bg-background、font-sans、text-foreground(见主题文件末尾的 @layer base)。这也解释了为什么主题的 --font-sans 需要 Geist 实际可用——字体缺失时回退到 sans-serif。

添加组件

按名称添加组件:

topcoat ui add button

命令会把源码复制到组件目录、写入模块声明,并在 components.toml 中记录安装。它还会自动安装被请求组件依赖的其他组件。

模块声明的落点规则:写在 src/components.rs;若该文件已存在同级目录内的 src/components/mod.rs,则写入 mod.rs。两种风格同时存在时,命令会在写文件前报错,要求你先删掉一个(见 crates/topcoat-ui/src/manage/module.rs)。声明格式固定为 pub mod <name>;,重复声明会被识别并跳过。

批量安装与跳过语义

要安装 registry 提供的全部组件,传 --all:

topcoat ui add --all

已安装的组件会被跳过并逐条报告(形如 - skipped button (src/components/button.rs): already installed)。加 --overwrite 可连已存在文件一起替换。

这里有一个容易忽略但很重要的差异,源码中由 Origin 区分(见 crates/topcoat-ui/src/manage/add.rs):

  • 显式点名的组件,如果目标文件已存在且没有 --overwrite,直接报错:already exists; pass --overwrite to replace it;
  • --all 扫描到的组件,已存在时跳过而不报错;
  • 作为依赖被拉入的组件,即使存在也不会被覆盖,也不会出现在输出中。

这意味着“我想更新某个组件但不想动其他组件”时,应使用带 --overwrite 的显式名称,而不是 --all --overwrite。

依赖如何展开

依赖关系来自 registry 清单中的 dependencies 字段。内置 registry 的实际依赖举例如下(见 crates/topcoat-ui/registry/registry.toml):

组件 依赖
sidebar button、input、separator、sheet、skeleton
sheet、alert_dialog dialog
dropdown_menu、hover_card、popover、tooltip floating
field label
pagination button

因此 topcoat ui add sidebar 会连带安装 7 个组件(含传递依赖 sheet → dialog)。安装器使用队列做广度遍历,并用 (registry, component) 去重,保证菱形依赖不会重复安装。

文件冲突与交互确认

所有 registry 共享同一个组件目录,且一个文件只能属于一个组件。如果目标路径已被另一个 registry 的组件占用,命令会询问是否替换,并在确认后删除旧文件、移除其模块声明(见 crates/topcoat-ui/src/manage/add.rs)。同名但落地路径不同的组件不会被视为冲突。

在非交互环境(无 TTY)中,任何需要确认的提问都会转为错误,并提示改用 --registry 显式指定;--registry 是规避交互的推荐方式(见 crates/topcoat-cli/src/ui/add.rs)。

使用组件

安装后的组件就是你 crate 里的普通模块,直接导入即可。官方给出的登录表单示例展示了典型组合方式:

mod components;

use components::button::button;
use components::card::{
    card, card_content, card_description, card_footer, card_header, card_title,
};
use components::field::{field, field_description, field_group, field_label};
use components::input::input;
use topcoat::{
    Result,
    context::Cx,
    view::{View, attributes, component, element_id, view},
};

#[component]
async fn sign_in(cx: &Cx) -> Result<impl View> {
    Ok(view! {
        // Elements that refer to each other share these IDs.
        let form = element_id(cx);
        let email = element_id(cx);
        let email_description = element_id(cx);

        card(
            card_header(
                card_title("Sign in")
                card_description("Use your work email to continue.")
            )
            card_content(
                <form id=(&form) method="post" action="/login">
                    field_group(
                        field(
                            field_label(attrs: attributes! { for=(&email) }, "Email")
                            input(
                                attrs: attributes! {
                                    id=(&email)
                                    name="email"
                                    type="email"
                                    placeholder="you@example.com"
                                    aria-describedby=(&email_description)
                                }
                            )
                            field_description(
                                attrs: attributes! { id=(&email_description) },
                                "Use the email address associated with your account."
                            )
                        )
                    )
                </form>
            )
            card_footer(
                button(
                    attrs: attributes! { class="w-full" type="submit" form=(&form) },
                    "Sign in"
                )
            )
        )
    })
}

element_id(cx) 用于生成同一渲染中互相引用的 ID,避免手写字符串导致的重复或错配。示例把 label 的 for、input 的 id、以及 aria-describedby 指向同一组 ID,这正是无障碍表单的基础要求。

四条共享约定

变体与尺寸使用枚举 prop。 例如 variant: ButtonVariant::Destructive 表示破坏性操作。源码中 ButtonVariant 有 Primary、Secondary、Outline、Ghost、Destructive 五个取值,ButtonSize 有 Sm、Md、Lg、Icon,且都通过 #<a href="https://link.gitcode.com/i/1625e9cdb2764cbc4ab53126a09e1108" target="_blank">derive(Default)] 给出了默认值(Primary 与 Md),因此不传也能编译(见 [crates/topcoat-ui/registry/src/components/button.rs)。

额外属性放进 attrs。 用 attributes! 构造。每个组件都会在自己的文档注释中说明这些属性最终落在哪个元素上——button 落在 <button>,card 落在包裹的 <div>,input 落在 <input>。类名会被追加到组件既有类名之后,但不会解决 Tailwind 工具类冲突。要可靠覆盖默认样式,应使用更具体的选择器,或直接改组件源码。

具体实现方式可以在源码中确认:各组件先用 attrs.remove("class") 取出调用方传入的 class,再用 class!(BASE, ..., attrs.remove("class")) 拼接,剩余属性整体展开到目标元素上:

// button 的核心渲染
<button
    class=(class!(
        BASE,
        variant.classes(),
        size.classes(),
        attrs.remove("class"),
    ))
    (attrs)
>
    (child)
</button>

内容通过 children 传入。 子内容可以是文本、HTML 和其他组件。源码中的参数类型是 Child<'_>,因此可以自由嵌套。

通过 class helper 复用样式。 例如 button_variants 可以让链接获得按钮外观:

view! {
    <a href="/login" class=(button_variants(ButtonVariant::Outline, ButtonSize::Md))>
        "Sign in"
    </a>
}

button_variants 与 button 共享同一份 BASE 常量,因此两者的尺寸、焦点环、禁用态完全一致。

表单字段的额外约定

field 家族比表面看到的更细致,源码里有几条值得掌握的行为(见 crates/topcoat-ui/registry/src/components/field.rs):

  • FieldOrientation 支持 Vertical(默认)、Horizontal、Responsive;Responsive 依赖 field_group 提供的 @container/field-group 容器查询,在容器足够宽时才切换为横向布局。
  • field 渲染为 role="group" 的容器,并带有 data-slot="field",因此组件内部用 group-data-[invalid=true]/field 之类的选择器联动样式。
  • 当控件带有 aria-invalid="true",或其祖先 field 带有 data-invalid="true" 时,field_label 会自动变为破坏性颜色。校验逻辑与错误信息是否渲染由调用方负责。
  • field_error 渲染 role="alert",只在真有错误时渲染,并通过 aria-describedby 与控件关联。
  • field_legend 配合 field_set(<fieldset>)使用,field_separator 提供带可选文本的分隔线。

组件源码本身就是最准确的 API 文档,建议安装后直接阅读对应 .rs 文件;examples/ui 提供了可运行的完整展示。

主题定制

主题用 styles.css 中的 CSS 变量定义共享样式,组件只通过 bg-primary、text-muted-foreground 这类类名读取变量,从不直接写死颜色。这意味着改一处变量即可全局生效。

可调 token 一览

内置 neutral 主题声明的变量及含义(整理自主题文件头部注释):

变量 作用
--background / --foreground 页面背景 / 其上的文字与图标
--card / --card-foreground 卡片与面板背景 / 其上的文字
--popover / --popover-foreground 浮层(菜单、气泡)背景 / 其上的文字
--muted-foreground 次要文字:说明、占位符
--primary / --primary-foreground 强调色(主操作、选中、高亮)/ 主色填充上的文字
--destructive / --destructive-foreground 破坏性操作与错误态 / 其上的文字
--border 细边框与分隔线
--ring 焦点环
--sidebar 系列(7 个) 侧边栏独立的背景、前景、主色、悬停/选中、边框、焦点环
--shadow-xs / --shadow-sm 抬升控件与抬升表面(卡片、菜单)的阴影

这些值可以独立调整。例如只改 --card 而不动 --background,就能让卡片与页面形成层次;--card-foreground 会随之决定卡片内文字颜色。

暗色模式

在 <html> 上添加 dark 类可为整页启用暗色,或添加到任意祖先元素上为子树启用。暗色变量定义在同一文件的 .dark 选择器中,修改即可换色。

之所以能用类切换,是因为主题文件声明了 @custom-variant dark (&:is(.dark *)),把 Tailwind 的 dark: 变体绑定到“存在 .dark 祖先”这一条件上,而不是依赖 prefers-color-scheme。

阴影默认关闭

主题默认不带阴影。要启用,把 :root 与 .dark 中的 --shadow-xs、--shadow-sm 替换为旁边注释里的值即可,例如亮色下:

--shadow-xs: 0 1px 2px oklch(0.24 0.02 260 / 12%);
--shadow-sm:
  0 1px 2px oklch(0.24 0.02 260 / 10%),
  0 2px 8px -2px oklch(0.24 0.02 260 / 9%);

默认值写成 0 0 #0000 而不是 none,原因也在文件注释里:Tailwind 会把阴影与焦点环合并到同一个 box-shadow,使用 none 会连带破坏焦点环。

UI 命令在初始化后不会改写 styles.css,因此可以放心在文件中追加自定义 token、覆盖 @layer base,或补充自己的工具类。

更新组件

topcoat ui list 会在组件的 registry 源码发生变化时报告更新。判断依据是比较 registry 当前的哈希与 components.toml 中保存的哈希;你对本地副本的修改不参与这个比较。也就是说,“更新可用”只表示上游变了,不表示你改过。

查看清单:

topcoat ui list

列表会显示可用组件及其安装状态。用 --installed 只看已安装的组件。CLI 输出使用了四种标记(见 crates/topcoat-cli/src/ui/list.rs):

标记 状态 含义
无标记 Available registry 提供但未安装(--installed 时隐藏)
✓ UpToDate 已安装,且哈希与 registry 一致
↑ Update 已安装,但 registry 提供更新的源码
? Orphaned 安装状态中有记录,但 registry 已不再提供该组件,或 registry 无法加载

要拉取新源码,重新执行带 --overwrite 的 add:

topcoat ui add button --overwrite

这会用 registry 源码替换你的文件。务必先提交或备份本地改动,替换后查看 diff,再把需要保留的修改重新应用。

要一次性刷新全部组件,运行 topcoat ui add --all --overwrite。它同时会安装你尚未拥有的组件——这也是它与逐个更新最实质的区别。

移除组件

按名称移除:

topcoat ui remove button

该命令会删除组件文件、移除其模块声明,并从 components.toml 中删除记录。它不会删除当初作为依赖被一起安装的组件。原因在源码中很直接:remove 只处理你显式列出的目标,不做反向依赖分析(见 crates/topcoat-ui/src/manage/remove.rs)。

两个实现细节对排错有用:一是所有目标会先全部解析完毕,再开始删除文件,因此拼错名字或跨 registry 歧义不会造成“删了一半”;二是某个 registry 的最后一个组件被移除后,其 [registries.<name>] 段落会被整个清除,避免留下空表。若同一组件名存在于多个 registry,需要 --registry 指定来源,否则会报歧义错误。

自定义 registry

自定义 registry 是一个提供组件源码与 registry.toml 清单的 Cargo crate。在 crate 的 metadata 中指向清单所在目录:

# Cargo.toml of the registry crate
[package.metadata.topcoat-ui]
registry = "registry"
# registry/registry.toml
version = 1

[themes.acme]
source = "themes/acme.css"

[components.button]
source = "src/components/button.rs"

[components.data_table]
source = "src/components/data_table.rs"
# Installed alongside data_table. An entry names a component in the same
# registry, or one in another registry by that registry's crate name.
dependencies = ["button", { registry = "other-registry-crate", name = "spinner" }]

清单结构对应 crates/topcoat-ui/src/registry.rs 中的反序列化类型:version 为格式版本,themes 与 components 是名称到条目的映射,条目至少包含 source,组件条目还可包含 dependencies。依赖有两种写法:字符串表示同 registry 内的组件名,内联表表示另一个 registry 中的组件(按 crate 名引用)。

组件版本由源码内容计算得出。要分发更新,只需发布一个源码已变更的 registry crate 新版本。

消费 registry

在 Cargo.toml 中把 registry crate 声明为直接依赖,它的组件就会出现在 topcoat ui list 中,并可通过 --registry 添加:

topcoat ui add data_table --registry my-registry-crate

这条约束在源码中是强制的:非内置 registry 必须出现在工作区成员的直接依赖列表中,否则报错 must be a direct dependency in Cargo.toml(见 crates/topcoat-ui/src/manage/workspace.rs)。内置 registry 是例外,允许作为传递依赖。

不带 --registry 时,命令优先使用内置 topcoat registry;如果组件只存在于其他 registry,会请求确认。所有 registry 共用同一个安装目录;如果某个组件会替换来自其他 registry 的文件,命令会在替换前询问。内置 registry 通过 Topcoat 的 ui feature 提供,无需单独依赖。

一个实用的 registry 侧参考是 crates/topcoat-ui/registry/Cargo.toml:它用 registry = "." 把清单放在 crate 根目录,并可选启用 embedded feature 把清单与源码编译进二进制(对应 Registry::embedded)。仓库里还有一个测试,会比较“磁盘上的 registry”与“内嵌的 registry”是否逐字节一致(见 crates/topcoat-ui/src/registry.rs),这是维护自定义 registry 时值得借鉴的一致性保障。

内置组件清单

neutral 主题之外,内置 registry 目前提供 34 个组件(以 crates/topcoat-ui/registry/registry.toml 为准):

accordion、alert、alert_dialog、avatar、badge、breadcrumb、button、card、checkbox、dialog、dropdown_menu、field、floating、hover_card、input、kbd、label、navigation_menu、pagination、popover、progress、radio_group、select、separator、sheet、sidebar、skeleton、spinner、switch、table、tabs、textarea、toggle、tooltip。

其中 floating 与 label 更像共享基元:前者提供浮层的对齐与方位枚举(FloatingAlign、FloatingSide),后者是 field_label 的底层实现。它们通常不由你直接调用,而是被 popover、tooltip、dropdown_menu、hover_card、field 引入。

常见问题排查

报错“the package is already initialized”。 components.toml 已存在,说明这是重复执行 init。若要重建,需要先自行处理该文件;正常升级场景不需要重新 init。

报错“the built-in registry crate ... is not in the dependency graph”。 忘记启用 ui feature,或使用了 default-features = false 而未显式列出 ui。

报错“components module declared at both ...”。 同时存在 src/components.rs 与 src/components/mod.rs,需删除一个以确定模块风格;命令在写文件前就会失败,不会产生半成品。

组件安装了但没有样式。 检查 build.rs 是否把 styles.css 设为 Tailwind 的 input,以及布局中是否引用了 tailwind::stylesheet!()。init 输出中的两条 ! 提示正对应这两步。

本地改过的组件被覆盖了。 add --overwrite 是无条件替换。应先用 topcoat ui list 确认状态,提交改动后再覆盖,最后按 diff 回填。

自定义目录下的组件类名没生成。 主题的 @source 固定扫描 ./src/**/*.rs。若把组件装到 src 之外,需要同步调整 styles.css 中的扫描路径与 components_dir 保持一致。

延伸阅读

登录后查看全文
topcoat