Agent SkillsfeigeCode/navop › gpui-global

gpui-global

GitHub

管理GPUI应用全局状态,支持通过实现Global trait定义、设置和访问应用级共享数据。涵盖配置、功能开关及共享服务场景,强调使用Arc优化资源克隆与手动通知机制。

.codex/skills/gpui-global/SKILL.md feigeCode/navop

Trigger Scenarios

需要跨组件共享应用配置 实现全局功能标志位控制 注册和管理全局共享服务

Install

npx skills add feigeCode/navop --skill gpui-global -g -y
More Options

Non-standard path

npx skills add https://github.com/feigeCode/navop/tree/dev/.codex/skills/gpui-global -g -y

Use without installing

npx skills use feigeCode/navop@gpui-global

指定 Agent (Claude Code)

npx skills add feigeCode/navop --skill gpui-global -a claude-code -g -y

安装 repo 全部 skill

npx skills add feigeCode/navop --all -g -y

预览 repo 内 skill

npx skills add feigeCode/navop --list

SKILL.md

Frontmatter
{
    "name": "gpui-global",
    "description": "Global state management in GPUI. Use when implementing global state, app-wide configuration, or shared resources."
}

Overview

Global state in GPUI provides app-wide shared data accessible from any context.

Key Trait: Global - Implement on types to make them globally accessible

Quick Start

Define Global State

use gpui::Global;

#[derive(Clone)]
struct AppSettings {
    theme: Theme,
    language: String,
}

impl Global for AppSettings {}

Set and Access Globals

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);
    });
}

Update Globals

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
    }
}

Common Use Cases

1. App Configuration

#[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>();

2. Feature Flags

#[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
        }
    }
}

3. Shared Services

#[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();
    }
}

Best Practices

✅ Use Arc for Shared Resources

#[derive(Clone)]
struct GlobalState {
    database: Arc<Database>,  // Cheap to clone
    cache: Arc<RwLock<Cache>>,
}

impl Global for GlobalState {}

✅ Immutable by Default

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)
    }
}

❌ Don't: Overuse Globals

// ❌ 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 { ... });

When to Use

Use Globals for:

  • App-wide configuration
  • Feature flags
  • Shared services (HTTP client, logger)
  • Read-only reference data

Use Entities for:

  • Component-specific state
  • State that changes frequently
  • State that needs notifications

Reference Documentation

  • API Reference: See api-reference.md
    • Global trait, set_global, update_global
    • Interior mutability patterns
    • Best practices and anti-patterns

Version History

  • e768f09 Current 2026-07-19 08:48

Same Skill Collection

.codex/skills/gpui-action/SKILL.md
.codex/skills/gpui-async/SKILL.md
.codex/skills/gpui-context/SKILL.md
.codex/skills/gpui-element/SKILL.md
.codex/skills/gpui-entity/SKILL.md
.codex/skills/gpui-event/SKILL.md
.codex/skills/gpui-focus-handle/SKILL.md
.codex/skills/gpui-layout-and-style/SKILL.md
.codex/skills/gpui-style-guide/SKILL.md
.codex/skills/gpui-test/SKILL.md
.codex/skills/navop-release-notes/SKILL.md
.codex/skills/new-component/SKILL.md

Metadata

Files
0
Version
ba0720c
Hash
f92e37b6
Indexed
2026-07-19 08:48

Accueil - Wiki
Copyright © 2011-2026 iteam. Current version is 2.155.2. UTC+08:00, 2026-07-20 15:27
浙ICP备14020137号-1 $Carte des visiteurs$