gpui-global by longbridge/gpui-component
npx skills add https://github.com/longbridge/gpui-component --skill gpui-globalGPUI 中的全局状态提供应用程序范围内共享的数据,可从任何上下文访问。
关键特性 : Global - 在类型上实现此特性以使其全局可访问
use gpui::Global;
#[derive(Clone)]
struct AppSettings {
theme: Theme,
language: String,
}
impl Global for AppSettings {}
fn main() {
let app = Application::new();
app.run(|cx: &mut App| {
// 设置全局状态
cx.set_global(AppSettings {
theme: Theme::Dark,
language: "en".to_string(),
});
// 访问全局状态(只读)
let settings = cx.global::<AppSettings>();
println!("Theme: {:?}", settings.theme);
});
}
impl MyComponent {
fn change_theme(&mut self, new_theme: Theme, cx: &mut Context<Self>) {
cx.update_global::<AppSettings, _>(|settings, cx| {
settings.theme = new_theme;
// 全局状态更新不会自动触发通知
// 手动通知关心的组件
});
cx.notify(); // 重新渲染此组件
}
}
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
#[derive(Clone)]
struct AppConfig {
api_endpoint: String,
max_retries: u32,
timeout: Duration,
}
impl Global for AppConfig {}
// 在启动时设置一次
cx.set_global(AppConfig {
api_endpoint: "https://api.example.com".to_string(),
max_retries: 3,
timeout: Duration::from_secs(30),
});
// 在任何地方访问
let config = cx.global::<AppConfig>();
#[derive(Clone)]
struct FeatureFlags {
enable_beta_features: bool,
enable_analytics: bool,
}
impl Global for FeatureFlags {}
impl MyComponent {
fn render_beta_feature(&self, cx: &App) -> Option<impl IntoElement> {
let flags = cx.global::<FeatureFlags>();
if flags.enable_beta_features {
Some(div().child("Beta feature"))
} else {
None
}
}
}
#[derive(Clone)]
struct ServiceRegistry {
http_client: Arc<HttpClient>,
logger: Arc<Logger>,
}
impl Global for ServiceRegistry {}
impl MyComponent {
fn fetch_data(&mut self, cx: &mut Context<Self>) {
let registry = cx.global::<ServiceRegistry>();
let client = registry.http_client.clone();
cx.spawn(async move |cx| {
let data = client.get("api/data").await?;
// 处理数据...
Ok::<_, anyhow::Error>(())
}).detach();
}
}
#[derive(Clone)]
struct GlobalState {
database: Arc<Database>, // 克隆成本低
cache: Arc<RwLock<Cache>>,
}
impl Global for GlobalState {}
全局状态默认是只读的。需要时使用内部可变性:
#[derive(Clone)]
struct Counter {
count: Arc<AtomicUsize>,
}
impl Global for Counter {}
impl Counter {
fn increment(&self) {
self.count.fetch_add(1, Ordering::SeqCst);
}
fn get(&self) -> usize {
self.count.load(Ordering::SeqCst)
}
}
// ❌ 不好:全局状态过多
cx.set_global(UserState { ... });
cx.set_global(CartState { ... });
cx.set_global(CheckoutState { ... });
// ✅ 好:对组件状态使用实体
let user_entity = cx.new(|_| UserState { ... });
对以下情况使用全局状态:
对以下情况使用实体:
每周安装次数
136
代码仓库
GitHub 星标数
10.7K
首次出现
2026 年 1 月 21 日
安全审计
安装于
opencode124
codex119
gemini-cli118
github-copilot113
cursor107
amp102
Global state in GPUI provides app-wide shared data accessible from any context.
Key Trait : Global - Implement on types to make them globally accessible
use gpui::Global;
#[derive(Clone)]
struct AppSettings {
theme: Theme,
language: String,
}
impl Global for AppSettings {}
fn main() {
let app = Application::new();
app.run(|cx: &mut App| {
// Set global
cx.set_global(AppSettings {
theme: Theme::Dark,
language: "en".to_string(),
});
// Access global (read-only)
let settings = cx.global::<AppSettings>();
println!("Theme: {:?}", settings.theme);
});
}
impl MyComponent {
fn change_theme(&mut self, new_theme: Theme, cx: &mut Context<Self>) {
cx.update_global::<AppSettings, _>(|settings, cx| {
settings.theme = new_theme;
// Global updates don't trigger automatic notifications
// Manually notify components that care
});
cx.notify(); // Re-render this component
}
}
#[derive(Clone)]
struct AppConfig {
api_endpoint: String,
max_retries: u32,
timeout: Duration,
}
impl Global for AppConfig {}
// Set once at startup
cx.set_global(AppConfig {
api_endpoint: "https://api.example.com".to_string(),
max_retries: 3,
timeout: Duration::from_secs(30),
});
// Access anywhere
let config = cx.global::<AppConfig>();
#[derive(Clone)]
struct FeatureFlags {
enable_beta_features: bool,
enable_analytics: bool,
}
impl Global for FeatureFlags {}
impl MyComponent {
fn render_beta_feature(&self, cx: &App) -> Option<impl IntoElement> {
let flags = cx.global::<FeatureFlags>();
if flags.enable_beta_features {
Some(div().child("Beta feature"))
} else {
None
}
}
}
#[derive(Clone)]
struct ServiceRegistry {
http_client: Arc<HttpClient>,
logger: Arc<Logger>,
}
impl Global for ServiceRegistry {}
impl MyComponent {
fn fetch_data(&mut self, cx: &mut Context<Self>) {
let registry = cx.global::<ServiceRegistry>();
let client = registry.http_client.clone();
cx.spawn(async move |cx| {
let data = client.get("api/data").await?;
// Process data...
Ok::<_, anyhow::Error>(())
}).detach();
}
}
#[derive(Clone)]
struct GlobalState {
database: Arc<Database>, // Cheap to clone
cache: Arc<RwLock<Cache>>,
}
impl Global for GlobalState {}
Globals are read-only by default. Use interior mutability when needed:
#[derive(Clone)]
struct Counter {
count: Arc<AtomicUsize>,
}
impl Global for Counter {}
impl Counter {
fn increment(&self) {
self.count.fetch_add(1, Ordering::SeqCst);
}
fn get(&self) -> usize {
self.count.load(Ordering::SeqCst)
}
}
// ❌ Bad: Too many globals
cx.set_global(UserState { ... });
cx.set_global(CartState { ... });
cx.set_global(CheckoutState { ... });
// ✅ Good: Use entities for component state
let user_entity = cx.new(|_| UserState { ... });
Use Globals for:
Use Entities for:
Weekly Installs
136
Repository
GitHub Stars
10.7K
First Seen
Jan 21, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
opencode124
codex119
gemini-cli118
github-copilot113
cursor107
amp102
Rust性能优化指南:m10-performance技能详解,包含算法、数据结构与内存优化策略
715 周安装
Google Ads 账户深度分析与健康度审计工具 - 74项检查,自动生成优化报告
208 周安装
阿里云CDN OpenAPI自动化操作指南 - 域名管理、缓存刷新、HTTPS证书配置
129 周安装
SpriteKit 常见问题诊断指南:物理接触、帧率优化与内存泄漏排查
134 周安装
iOS游戏开发终极指南:SpriteKit、SceneKit、RealityKit架构、性能优化与故障排除
139 周安装
JSON数据处理教程:Python与JavaScript解析、验证与进阶操作指南
133 周安装
Hookify 规则编写指南:创建自定义代码监控与安全提示规则
142 周安装