gpui
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseGPUI Best Practices
GPUI 最佳实践
Comprehensive guide for building desktop applications with GPUI, the UI framework powering Zed editor. Contains 40+ rules across 8 categories, prioritized by impact.
这是一份使用GPUI构建桌面应用的综合指南,GPUI是为Zed编辑器提供支持的UI框架。指南包含8个分类下的40+条规则,按影响优先级排序。
When to Apply
适用场景
Reference these guidelines when:
- Writing new GPUI views or components
- Implementing state management with Entity
- Handling events and keyboard shortcuts
- Working with async tasks and background work
- Building forms, lists, or dialogs
- Styling components with Tailwind-like API
- Testing GPUI applications
在以下场景中可参考本指南:
- 编写新的GPUI视图或组件
- 使用Entity实现状态管理
- 处理事件和键盘快捷键
- 处理异步任务和后台工作
- 构建表单、列表或对话框
- 使用类Tailwind API为组件设置样式
- 测试GPUI应用
Rule Categories by Priority
按优先级划分的规则分类
| Priority | Category | Impact | Prefix |
|---|---|---|---|
| 1 | Core Concepts | CRITICAL | |
| 2 | Rendering | CRITICAL | |
| 3 | State Management | HIGH | |
| 4 | Event Handling | HIGH | |
| 5 | Async & Concurrency | MEDIUM-HIGH | |
| 6 | Styling | MEDIUM | |
| 7 | Components | MEDIUM | |
| 8 | Anti-patterns | CRITICAL | |
| 优先级 | 分类 | 影响程度 | 前缀 |
|---|---|---|---|
| 1 | 核心概念 | 关键 | |
| 2 | 渲染 | 关键 | |
| 3 | 状态管理 | 高 | |
| 4 | 事件处理 | 高 | |
| 5 | 异步与并发 | 中高 | |
| 6 | 样式设计 | 中 | |
| 7 | 组件 | 中 | |
| 8 | 反模式 | 关键 | |
Quick Reference
快速参考
1. Core Concepts (CRITICAL)
1. 核心概念(关键)
- - Understand GPUI's single ownership model
core-ownership-model - - Use read/update/observe/subscribe correctly
core-entity-operations - - Use WeakEntity to break circular references
core-weak-entity - - Know when to use App, Context<T>, AsyncApp
core-context-types
- - 理解GPUI的单一所有权模型
core-ownership-model - - 正确使用read/update/observe/subscribe方法
core-entity-operations - - 使用WeakEntity打破循环引用
core-weak-entity - - 了解何时使用App、Context<T>、AsyncApp
core-context-types
2. Rendering (CRITICAL)
2. 渲染(关键)
- - Choose Render for stateful, RenderOnce for components
render-render-vs-renderonce - - Build element trees with div() and method chaining
render-element-composition - - Use .when() and .when_some() for conditional styling
render-conditional - - Use SharedString to avoid string copying
render-shared-string - - Design components with builder pattern
render-builder-pattern
- - 为有状态组件选择Render,为无状态组件选择RenderOnce
render-render-vs-renderonce - - 使用div()和方法链构建元素树
render-element-composition - - 使用.when()和.when_some()实现条件样式
render-conditional - - 使用SharedString避免字符串复制
render-shared-string - - 采用构建者模式设计组件
render-builder-pattern
3. State Management (HIGH)
3. 状态管理(高)
- - Always call cx.notify() after state changes
state-notify - - Use cx.observe() to react to Entity changes
state-observe - - Use cx.subscribe() for typed events
state-subscribe - - Use Global trait for app-wide state
state-global - - Use window.use_keyed_state() for persistent state
state-keyed-state
- - 状态变更后务必调用cx.notify()
state-notify - - 使用cx.observe()响应Entity变更
state-observe - - 使用cx.subscribe()处理类型化事件
state-subscribe - - 为全局应用状态使用Global trait
state-global - - 使用window.use_keyed_state()实现持久化状态
state-keyed-state
4. Event Handling (HIGH)
4. 事件处理(高)
- - Define and register actions for keyboard shortcuts
event-actions - - Use cx.listener() for view-bound event handlers
event-listener - - Manage focus with FocusHandle and key_context
event-focus - - Understand event bubbling and stop_propagation
event-propagation
- - 定义并注册键盘快捷键对应的动作
event-actions - - 使用cx.listener()实现视图绑定的事件处理器
event-listener - - 使用FocusHandle和key_context管理焦点
event-focus - - 理解事件冒泡与stop_propagation的使用
event-propagation
5. Async & Concurrency (MEDIUM-HIGH)
5. 异步与并发(中高)
- - Store or detach tasks to prevent cancellation
async-task-lifecycle - - Implement debounce with timer + task replacement
async-debounce - - Use background_spawn for CPU-intensive work
async-background-spawn - - Use WeakEntity for safe cross-await access
async-weak-entity - - Use .log_err() and .detach_and_log_err()
async-error-handling
- - 存储或分离Task以避免被取消
async-task-lifecycle - - 结合定时器与任务替换实现防抖
async-debounce - - 使用background_spawn处理CPU密集型工作
async-background-spawn - - 使用WeakEntity实现跨await的安全访问
async-weak-entity - - 使用.log_err()和.detach_and_log_err()处理错误
async-error-handling
6. Styling (MEDIUM)
6. 样式设计(中)
- - Use h_flex() and v_flex() for layouts
style-flexbox - - Always use cx.theme() for colors
style-theme-colors - - Use DynamicSpacing for responsive spacing
style-spacing - - Use elevation system for layered surfaces
style-elevation
- - 使用h_flex()和v_flex()实现布局
style-flexbox - - 始终使用cx.theme()获取颜色
style-theme-colors - - 使用DynamicSpacing实现响应式间距
style-spacing - - 使用层级系统实现分层界面
style-elevation
7. Components (MEDIUM)
7. 组件(中)
- - Prefer RenderOnce with #[derive(IntoElement)]
comp-stateless - - Implement Disableable, Selectable, Sizable traits
comp-traits - - Add focus ring for accessibility
comp-focus-ring - - Use WindowExt for dialog management
comp-dialog - - Use variant enums for component styles
comp-variant
- - 优先使用带有#[derive(IntoElement)]的RenderOnce
comp-stateless - - 实现Disableable、Selectable、Sizable trait
comp-traits - - 添加焦点环以提升可访问性
comp-focus-ring - - 使用WindowExt管理对话框
comp-dialog - - 使用变体枚举实现组件样式
comp-variant
8. Anti-patterns (CRITICAL)
8. 反模式(关键)
- - Never silently discard errors with let _ =
anti-silent-error - - Never drop Task without storing or detaching
anti-drop-task - - Always detach or store subscriptions
anti-drop-subscription - - Avoid Entity cycles, use WeakEntity
anti-circular-reference - - Never forget cx.notify() after state changes
anti-missing-notify - - Avoid unwrap(), use ? or explicit handling
anti-unwrap
- - 绝不要用let _ = 静默丢弃错误
anti-silent-error - - 绝不要在未存储或分离的情况下丢弃Task
anti-drop-task - - 务必分离或存储订阅
anti-drop-subscription - - 避免Entity循环引用,使用WeakEntity替代
anti-circular-reference - - 状态变更后绝不要忘记调用cx.notify()
anti-missing-notify - - 避免使用unwrap(),改用?或显式处理
anti-unwrap
Architecture Overview
架构概述
┌─────────────────────────────────────────────────────────┐
│ Application (App) │
│ (Single owner of all Entities) │
└─────────────────────────────────────────────────────────┘
│
┌───────────────────┼───────────────────┐
│ │ │
┌───────────┐ ┌───────────┐ ┌──────────┐
│ Entity<A> │ │ Entity<B> │ │ Global<C>│
└───────────┘ └───────────┘ └──────────┘
│ │ │
│ read/update │ read/update │ via App
│ via Context<A> │ via Context<B> │
│
┌─────────────────────────────────────────────────┐
│ UI Rendering (Render trait) │
│ Each frame: fn render(&mut self, ...) │
│ Returns: impl IntoElement (Element tree) │
└─────────────────────────────────────────────────┘
│
├─ observe() → changes trigger render
├─ subscribe() → events trigger reactions
├─ notify() → signal changes
└─ emit() → send typed events┌─────────────────────────────────────────────────────────┐
│ Application (App) │
│ (Single owner of all Entities) │
└─────────────────────────────────────────────────────────┘
│
┌───────────────────┼───────────────────┐
│ │ │
┌───────────┐ ┌───────────┐ ┌──────────┐
│ Entity<A> │ │ Entity<B> │ │ Global<C>│
└───────────┘ └───────────┘ └──────────┘
│ │ │
│ read/update │ read/update │ via App
│ via Context<A> │ via Context<B> │
│
┌─────────────────────────────────────────────────┐
│ UI Rendering (Render trait) │
│ Each frame: fn render(&mut self, ...) │
│ Returns: impl IntoElement (Element tree) │
└─────────────────────────────────────────────────┘
│
├─ observe() → changes trigger render
├─ subscribe() → events trigger reactions
├─ notify() → signal changes
└─ emit() → send typed eventsHow to Use
使用方法
Read individual rule files for detailed explanations and code examples:
rules/core-ownership-model.md
rules/render-render-vs-renderonce.md
rules/anti-silent-error.mdEach rule file contains:
- Brief explanation of why it matters
- Incorrect code example with explanation
- Correct code example with explanation
- Additional context and references
阅读单个规则文件以获取详细说明和代码示例:
rules/core-ownership-model.md
rules/render-render-vs-renderonce.md
rules/anti-silent-error.md每个规则文件包含:
- 规则重要性的简要说明
- 错误代码示例及解释
- 正确代码示例及解释
- 额外背景信息与参考资料