tokio-rs / topcoat

本文为原文前 6,000 字符的节选翻译,完整内容请查看原文。

The full full-stack framework for Rust Topcoat is a modular, batteries-included Rust framework for building full-stack apps. It prioritizes simplicity and productivity. See Learn Topcoat to get started, or the Roadmap for what’s coming next. Early-stage and experimental. Expect breaking changes.

Topcoat 是一个用于构建全栈应用的模块化、功能完备的 Rust 框架。它优先考虑简洁性和生产力。请参阅“学习 Topcoat”以开始使用,或查看“路线图”了解后续计划。该项目处于早期实验阶段,请预料到会有破坏性变更。

use topcoat::{ Result, context::Cx, router::{module_router, page}, view::{View, component, view}, }; #[tokio::main] async fn main() { topcoat::start(module_router!().build()).await.unwrap(); } #[page] async fn home(cx: &Cx) -> Result { Ok(view! { hello(name: “World”) }) } #[component] async fn hello(cx: &Cx, name: &str) -> Result { Ok(view! {

“Hello, ” (name) ”!”

}) }

use topcoat::{ Result, context::Cx, router::{module_router, page}, view::{View, component, view}, }; #[tokio::main] async fn main() { topcoat::start(module_router!().build()).await.unwrap(); } #[page] async fn home(cx: &Cx) -> Result<impl View> { Ok(view! { <!DOCTYPE html> <html> <body> hello(name: "World") </body> </html> }) } #[component] async fn hello(cx: &Cx, name: &str) -> Result<impl View> { Ok(view! { <h1>"Hello, " (name) "!"</h1> }) }

What makes Topcoat different Client reactivity without the boilerplate Topcoat renders all markup on the server: components can be async and query the database directly, eliminating all the traditional boilerplate needed for a separate API layer. Interactivity does not have to cost a round-trip, though. A $(…) expression is ordinary type-checked Rust that Topcoat evaluates on the server for the initial render and also translates to JavaScript, so it re-runs instantly in the browser. No wasm bundle, no client build step:

Topcoat 的独特之处在于无需样板代码的客户端响应式。Topcoat 在服务器上渲染所有标记:组件可以是异步的,并能直接查询数据库,从而消除了为单独 API 层所需的传统样板代码。不过,交互性并不一定需要往返服务器。$(…) 表达式是普通的类型检查 Rust 代码,Topcoat 会在服务器上对其进行初始渲染评估,并将其转换为 JavaScript,因此它可以在浏览器中即时重新运行。无需 WASM 包,也无需客户端构建步骤:

#[component] async fn faq(cx: &Cx) -> Result { let open = signal(cx, || false); Ok(view! { // Runs entirely in the browser; no server round-trip. <button @click=$(|_e| open.set(!open.get()))>“What is Topcoat?”

“A full-stack Rust framework.”

}) }

#[component] async fn faq(cx: &Cx) -> Result<impl View> { let open = signal(cx, || false); Ok(view! { // 完全在浏览器中运行;无需服务器往返。 <button @click=$(|_e| open.set(!open.get()))>"What is Topcoat?"</button> <p :hidden=$(!open.get())>"A full-stack Rust framework."</p> }) }

When an update does need the server, like fresh search results, mark the component as a #[shard]. Topcoat re-renders it on the server whenever one of its $(…) arguments changes and swaps the new HTML in place:

当更新确实需要服务器(例如获取最新的搜索结果)时,将组件标记为 #[shard]。每当其 $(…) 参数发生变化时,Topcoat 都会在服务器上重新渲染该组件,并将新的 HTML 替换到原位:

#[component] async fn search(cx: &Cx) -> Result { let query = signal(cx, String::new); Ok(view! { <input @input=$(|e: Event| query.set(e.target.value))> // Updates as the user types. search_results(query: $(query.get())) }) } #[shard] async fn search_results(cx: &Cx, query: String) -> Result { Ok(view! {

    // Your own server-side code, like a database query: for product in search_products(cx, &query).await? {
  • (product.name)
  • }
}) }

#[component] async fn search(cx: &Cx) -> Result<impl View> { let query = signal(cx, String::new); Ok(view! { <input @input=$(|e: Event| query.set(e.target.value))> // 随用户输入更新。 search_results(query: $(query.get())) }) } #[shard] async fn search_results(cx: &Cx, query: String) -> Result<impl View> { Ok(view! { <ul> // 您自己的服务器端代码,例如数据库查询: for product in search_products(cx, &query).await? { <li>(product.name)</li> } </ul> }) }

Powerful, unsurprising HTML templates The view! macro stays true to HTML and Rust. Use familiar Rust control flow as part of your templates:

强大且符合直觉的 HTML 模板。view! 宏忠实于 HTML 和 Rust。在模板中使用熟悉的 Rust 控制流:

view! {

}

view! { <nav> for item in nav_items { <a href=(item.url) if item.url == current_path { aria-current="page" class="active" } > (item.label) </a> } </nav> }

Use the topcoat fmt CLI command to automatically format view! snippets (and other macros) across your codebase.

使用 topcoat fmt 命令行工具自动格式化代码库中的 view! 片段(以及其他宏)。

Module-based routing Topcoat can optionally infer your route tree from your app’s module structure (without a build step):

基于模块的路由。Topcoat 可以选择性地从应用的模块结构中推断路由树(无需构建步骤):

src/ |— app.rs -> / (and the root layout) -- app/ |-- about.rs -> /about |-- _marketing.rs (layout, no URL segment) |-- _marketing/ | — pricing.rs -> /pricing |— posts.rs -> /posts |— posts/ | -- id.rs -> /posts/{post_id} — api/ `— health.rs -> GET /api/health

src/
|-- app.rs -> / (以及根 <html> 布局)
`-- app/
    |-- about.rs -> /about
    |-- _marketing.rs (布局,无 URL 片段)
    |-- _marketing/
    |   `-- pricing.rs -> /pricing
    |-- posts.rs -> /posts
    |-- posts/
    |   `-- id.rs -> /posts/{post_id}
    `-- api/
        `-- health.rs -> GET /api/health

Premade components you can edit Topcoat UI is a component library based on Tailwind inspired by shadcn/ui. Components are copied into your project via the topcoat ui CLI command, meaning you can freely change their design and functionality to fit your use case:

可编辑的预制组件。Topcoat UI 是一个基于 Tailwind 的组件库,灵感来自 shadcn/ui。组件通过 topcoat ui 命令行工具复制到您的项目中,这意味着您可以自由更改其设计和功能以适应您的用例:

#[component] async fn delete_card(cx: &Cx) -> Result { Ok(view! { card( card_header( card_title(“Delete workspace”) card_description( “This permanently removes the workspace and all of its data.” ) ) card_footer( attrs: attributes! { class=“justify-end” }, button(variant: ButtonVariant::Ghost, “Cancel”) button(variant: ButtonVariant::Destructive, “Delete workspace”) ) ) }) }

#[component] async fn delete_card(cx: &Cx) -> Result<impl View> { Ok(view! { card( card_header( card_title("Delete workspace") card_description( "这将永久删除工作区及其所有数据。" ) ) card_footer( attrs: attributes! { class="justify-end" }, button(variant: ButtonVariant::Ghost, "Cancel") button(variant: ButtonVariant::Destructive, "Delete workspace") ) ) }) }

Asset bundling The bundler scans your compiled binary for asset! calls, copies (or even downloads) every file into a local asset directory, and allows Topcoat to serve them efficiently with aggressive browser caching.

资源打包。打包器会扫描您编译后的二进制文件中的 asset! 调用,将每个文件复制(甚至下载)到本地资源目录,并允许 Topcoat 通过激进的浏览器缓存高效地提供这些资源。

const FERRIS: Asset = asset!(”./ferris.png”); view! { }

const FERRIS: Asset = asset!("./ferris.png"); view! { <img src=(FERRIS)> }

Topcoat also ships with utilities for web fonts and icons, as well as easy integrations for Fontsource (Google Fonts) and Iconify.

Topcoat 还附带了用于 Web 字体和图标的实用工具,以及对 Fontsource(Google Fonts)和 Iconify 的简便集成。

Built-in Tailwind support Enable the tailwind feature to integrate Tailwind into your project:

内置 Tailwind 支持。启用 tailwind 特性以将 Tailwind 集成到您的项目中:

view! { }

view! { <link rel="stylesheet" href=(topcoat::tailwind::stylesheet!())> }

Learn Topcoat Start here Getting started: create an app with topcoat new and run the dev server. Manual setup: add dependencies and wire up a minimal app yourself. Source code formatting: topcoat fmt for macro bodies. Rendering view! mixes HTML, Rust expressions, control flow, and component calls. #[component] makes async functions callable from markup with named arguments and child content. attributes! collects attributes to pass through components and spread onto elements. class! joins base, optional, and conditional CSS classes. suspense shows a fallback while content loads. error_boundary shows one if rendering fails. live! and emit! replace part of a page as async work produces new HTML. Routing Router: pages, layouts, and API routes; manual and auto-discovered. Module-based routing: derive the route table from your module tree. Linking to handlers: use href! for navigation links, form actions, and redirects. Working with requests Context (Cx): read request data and values stored by type. Add shared values with the router builder’s .with, or use cx.with to add a value for part of a request. Memoization: #[memoize] for per-request caching and fan-out dedup. Cookies: read and write the request cookie jar, with signed, encrypted, and prefixed cookies. Sessions: bring-your-own-storage session authentication: login/logout lifecycle, sliding expiration, and token rotation. Asset system Assets: declare assets in Rust, serve them with content-hashed URLs. Fonts: bundle and serve web fonts. Icons: download Iconify icon sets or declare your own. Client reactivity The runtime: signals, $(…) expressions, @ event handlers, and : bind attributes. Expressions: the dual R

学习 Topcoat。从这里开始:入门:使用 topcoat new 创建应用并运行开发服务器。手动设置:添加依赖项并自行配置最小化应用。源代码格式化:使用 topcoat fmt 格式化宏主体。渲染:view! 混合了 HTML、Rust 表达式、控制流和组件调用。#[component] 使异步函数可以通过标记调用,并支持命名参数和子内容。attributes! 收集要传递给组件并展开到元素上的属性。class! 连接基础、可选和条件 CSS 类。suspense 在内容加载时显示回退内容。error_boundary 在渲染失败时显示错误边界。live! 和 emit! 在异步工作产生新 HTML 时替换页面的一部分。路由:路由器:页面、布局和 API 路由;支持手动和自动发现。基于模块的路由:从模块树派生路由表。链接到处理程序:使用 href! 进行导航链接、表单操作和重定向。处理请求:上下文 (Cx):读取请求数据和按类型存储的值。使用路由器构建器的 .with 添加共享值,或使用 cx.with 为部分请求添加值。记忆化:#[memoize] 用于单次请求缓存和扇出去重。Cookie:读写请求 Cookie 罐,支持签名、加密和带前缀的 Cookie。会话:自带存储的会话身份验证:登录/注销生命周期、滑动过期和令牌轮换。资源系统:资源:在 Rust 中声明资源,并使用内容哈希 URL 提供服务。字体:打包并提供 Web 字体。图标:下载 Iconify 图标集或声明您自己的图标。客户端响应式:运行时:信号、$(…) 表达式、@ 事件处理程序和 : 绑定属性。表达式:双重 R