MCPInstall

gpui-patterns

Common GPUI patterns including component composition, state management strategies, event handling, and action dispatching. Use when user needs guidance on GPUI patterns, component design, or state management approaches.

Installs
48
Last 24h
—
Trending rank
—
Security
Not audited

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/geoffjay/claude-plugins --skill gpui-patterns
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads gpui-patterns automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

SKILL.md

The instructions your agent reads when the skill is triggered.

GPUI Patterns

Metadata

This skill provides comprehensive guidance on common GPUI patterns and best practices for building maintainable, performant applications.

Instructions

Component Composition Patterns

Basic Component Structure

use gpui::*;

// View component with state
struct MyView {
    state: Model<MyState>,
    _subscription: Subscription,
}

impl MyView {
    fn new(state: Model<MyState>, cx: &mut ViewContext<Self>) -> Self {
        let _subscription = cx.observe(&state, |_, _, cx| cx.notify());
        Self { state, _subscription }
    }
}

impl Render for MyView {
    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
        let state = self.state.read(cx);

        div()
            .flex()
            .flex_col()
            .child(format!("Value: {}", state.value))
    }
}

Container/Presenter Pattern

Container (manages state and logic):

struct Container {
    model: Model<AppState>,
    _subscription: Subscription,
}

impl Container {
    fn new(model: Model<AppState>, cx: &mut ViewContext<Self>) -> Self {
        let _subscription = cx.observe(&model, |_, _, cx| cx.notify());
        Self { model, _subscription }
    }
}

impl Render for Container {
    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
        let state = self.model.read(cx);

        // Pass data to presenter
        Presenter::new(state.data.clone())
    }
}

Presenter (pure rendering):

struct Presenter {
    data: String,
}

impl Presenter {
    fn new(data: String) -> Self {
        Self { data }
    }
}

impl Render for Presenter {
    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
        div().child(self.data.as_str())
    }
}

Compound Components

// Parent component with shared context
pub struct Tabs {
    items: Vec<TabItem>,
    active_index: usize,
}

pub struct TabItem {
    label: String,
    content: Box<dyn Fn() -> AnyElement>,
}

impl Tabs {
    pub fn new() -> Self {
        Self {
            items: Vec::new(),
            active_index: 0,
        }
    }

    pub fn add_tab(
        mut self,
        label: impl Into<String>,
        content: impl Fn() -> AnyElement + 'static,
    ) -> Self {
        self.items.push(TabItem {
            label: label.into(),
            content: Box::new(content),
        });
        self
    }

    fn set_active(&mut self, index: usize, cx: &mut ViewContext<Self>) {
        self.active_index = index;
        cx.notify();
    }
}

impl Render for Tabs {
    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
        div()
            .flex()
            .flex_col()
            .child(
                // Tab headers
                div()
                    .flex()
                    .children(
                        self.items.iter().enumerate().map(|(i, item)| {
                            tab_header(&item.label, i == self.active_index, || {
                                self.set_active(i, cx)
                            })
                        })
                    )
            )
            .child(
                // Active tab content
                (self.items[self.active_index].content)()
            )
    }
}

State Management Strategies

Model-View Pattern

// Model: Application state
#[derive(Clone)]
struct AppState {
    count: usize,
    items: Vec<String>,
}

// View: Observes and renders state
struct AppView {
    state: Model<AppState>,
    _subscription: Subscription,
}

impl AppView {
    fn new(state: Model<AppState>, cx: &mut ViewContext<Self>) -> Self {
        let _subscription = cx.observe(&state, |_, _, cx| cx.notify());
        Self { state, _subscription }
    }

    fn increment(&mut self, cx: &mut ViewContext<Self>) {
        self.state.update(cx, |state, cx| {
            state.count += 1;
            cx.notify();
        });
    }
}

Context-Based State

// Global state via context
#[derive(Clone)]
struct GlobalSettings {
    theme: Theme,
    language: String,
}

impl Global for GlobalSettings {}

// Initialize in app
fn init_app(cx: &mut AppContext) {
    cx.set_global(GlobalSettings {
        theme: Theme::Light,
        language: "en".to_string(),
    });
}

// Access in components
impl Render for MyView {
    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
        let settings = cx.global::<GlobalSettings>();

        div()
            .child(format!("Language: {}", settings.language))
    }
}

Subscription Patterns

Basic Subscription:

struct Observer {
    model: Model<Data>,
    _subscription: Subscription,
}

impl Observer {
    fn new(model: Model<Data>, cx: &mut ViewContext<Self>) -> Self {
        let _subscription = cx.observe(&model, |_, _, cx| {
            cx.notify();  // Rerender on change
        });

        Self { model, _subscription }
    }
}

Selective Updates:

impl Observer {
    fn new(model: Model<Data>, cx: &mut ViewContext<Self>) -> Self {
        let _subscription = cx.observe(&model, |this, model, cx| {
            let data = model.read(cx);

            // Only rerender if specific field changed
            if data.important_field != this.cached_field {
                this.cached_field = data.important_field.clone();
                cx.notify();
            }
        });

        Self {
            model,
            cached_field: String::new(),
            _subscription,
        }
    }
}

Multiple Subscriptions:

struct MultiObserver {
    model_a: Model<DataA>,
    model_b: Model<DataB>,
    _subscriptions: Vec<Subscription>,
}

impl MultiObserver {
    fn new(
        model_a: Model<DataA>,
        model_b: Model<DataB>,
        cx: &mut ViewContext<Self>,
    ) -> Self {
        let mut subscriptions = Vec::new();

        subscriptions.push(cx.observe(&model_a, |_, _, cx| cx.notify()));
        subscriptions.push(cx.observe(&model_b, |_, _, cx| cx.notify()));

        Self {
            model_a,
            model_b,
            _subscriptions: subscriptions,
        }
    }
}

Event Handling Patterns

Click Events

div()
    .on_click(cx.listener(|this, event: &ClickEvent, cx| {
        // Handle click
        this.handle_click(cx);
    }))
    .child("Click me")

Keyboard Events

div()
    .on_key_down(cx.listener(|this, event: &KeyDownEvent, cx| {
        match event.key.as_str() {
            "Enter" => this.submit(cx),
            "Escape" => this.cancel(cx),
            _ => {}
        }
    }))

Event Propagation

// Stop propagation
div()
    .on_click(|event, cx| {
        event.stop_propagation();
        // Handle click
    })

// Prevent default
div()
    .on_key_down(|event, cx| {
        if event.key == "Tab" {
            event.prevent_default();
            // Custom tab handling
        }
    })

Mouse Events

div()
    .on_mouse_down(cx.listener(|this, event, cx| {
        this.mouse_down_position = Some(event.position);
    }))
    .on_mouse_move(cx.listener(|this, event, cx| {
        if let Some(start) = this.mouse_down_position {
            let delta = event.position - start;
            this.handle_drag(delta, cx);
        }
    }))
    .on_mouse_up(cx.listener(|this, event, cx| {
        this.mouse_down_position = None;
    }))

Action System

Define Actions

use gpui::*;

actions!(app, [
    Increment,
    Decrement,
    Reset,
    SetValue
]);

// Action with data
#[derive(Clone, PartialEq)]
pub struct SetValue {
    pub value: i32,
}

impl_actions!(app, [SetValue]);

Register Action Handlers

impl Counter {
    fn register_actions(&mut self, cx: &mut ViewContext<Self>) {
        cx.on_action(cx.listener(|this, _: &Increment, cx| {
            this.model.update(cx, |state, cx| {
                state.count += 1;
                cx.notify();
            });
        }));

        cx.on_action(cx.listener(|this, _: &Decrement, cx| {
            this.model.update(cx, |state, cx| {
                state.count = state.count.saturating_sub(1);
                cx.notify();
            });
        }));

        cx.on_action(cx.listener(|this, action: &SetValue, cx| {
            this.model.update(cx, |state, cx| {
                state.count = action.value;
                cx.notify();
            });
        }));
    }
}

Dispatch Actions

// From within component
fn handle_button_click(&mut self, cx: &mut ViewContext<Self>) {
    cx.dispatch_action(Increment);
}

// With data
fn set_specific_value(&mut self, value: i32, cx: &mut ViewContext<Self>) {
    cx.dispatch_action(SetValue { value });
}

// Global action dispatch
cx.dispatch_action_on_window(Reset, window_id);

Keybindings

// Register global keybindings
fn register_keybindings(cx: &mut AppContext) {
    cx.bind_keys([
        KeyBinding::new("cmd-+", Increment, None),
        KeyBinding::new("cmd--", Decrement, None),
        KeyBinding::new("cmd-0", Reset, None),
    ]);
}

Element Composition

Builder Pattern

fn card(title: &str, content: impl IntoElement) -> impl IntoElement {
    div()
        .flex()
        .flex_col()
        .bg(white())
        .border_1()
        .rounded_lg()
        .shadow_sm()
        .p_6()
        .child(
            div()
                .text_lg()
                .font_semibold()
                .mb_4()
                .child(title)
        )
        .child(content)
}

Conditional Rendering

div()
    .when(condition, |this| {
        this.bg(blue_500())
    })
    .when_some(optional_value, |this, value| {
        this.child(format!("Value: {}", value))
    })
    .map(|this| {
        if complex_condition {
            this.border_1()
        } else {
            this.border_2()
        }
    })

Dynamic Children

div()
    .children(
        items.iter().map(|item| {
            div().child(item.name.as_str())
        })
    )

View Lifecycle

Initialization

impl MyView {
    fn new(cx: &mut ViewContext<Self>) -> Self {
        // Initialize state
        let model = cx.new_model(|_| MyState::default());

        // Set up subscriptions
        let subscription = cx.observe(&model, |_, _, cx| cx.notify());

        // Spawn async tasks
        cx.spawn(|this, mut cx| async move {
            // Async initialization
        }).detach();

        Self {
            model,
            _subscription: subscription,
        }
    }
}

Update Notifications

impl MyView {
    fn update_state(&mut self, new_data: Data, cx: &mut ViewContext<Self>) {
        self.model.update(cx, |state, cx| {
            state.data = new_data;
            cx.notify();  // Trigger rerender
        });
    }
}

Cleanup

impl Drop for MyView {
    fn drop(&mut self) {
        // Manual cleanup if needed
        // Subscriptions are automatically dropped
    }
}

Reactive Patterns

Derived State

impl Render for MyView {
    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
        let state = self.model.read(cx);

        // Compute derived values
        let total = state.items.iter().map(|i| i.value).sum::<i32>();
        let average = total / state.items.len() as i32;

        div()
            .child(format!("Total: {}", total))
            .child(format!("Average: {}", average))
    }
}

Async Updates

impl MyView {
    fn load_data(&mut self, cx: &mut ViewContext<Self>) {
        let model = self.model.clone();

        cx.spawn(|_, mut cx| async move {
            let data = fetch_data().await?;

            cx.update_model(&model, |state, cx| {
                state.data = data;
                cx.notify();
            })?;

            Ok::<_, anyhow::Error>(())
        }).detach();
    }
}

Resources

Official Documentation

Common Patterns Reference

  • Model-View: State management pattern
  • Container-Presenter: Separation of concerns
  • Compound Components: Related components working together
  • Action System: Command pattern for user interactions
  • Subscriptions: Observer pattern for reactive updates

Best Practices

  • Store subscriptions to prevent cleanup
  • Use cx.notify() sparingly
  • Prefer composition over inheritance
  • Keep render methods pure
  • Handle errors gracefully
  • Document component APIs
  • Test component behavior

FAQ

What does the gpui-patterns skill do?

Common GPUI patterns including component composition, state management strategies, event handling, and action dispatching. Use when user needs guidance on GPUI patterns, component design, or state management approaches.

How do I install gpui-patterns?

Run npx skills add https://github.com/geoffjay/claude-plugins --skill gpui-patterns in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/gpui-patterns/ (personal) or .claude/skills/gpui-patterns/ (project).

Which AI agents can use gpui-patterns?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is gpui-patterns safe to install?

No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.

Who maintains gpui-patterns?

It is published by geoffjay in geoffjay/claude-plugins. It has 48 recorded installs.

More from geoffjay/claude-plugins

View all →

documentation-update

geoffjay/claude-plugins

Regenerates documentation files (agents.md, agent-skills.md, plugins.md, usage.md) from marketplace data using Jinja templates. Use when plugins are added, updated, or removed to keep documentation in sync.

Docs & Writing1.8K installs

git-troubleshooting

geoffjay/claude-plugins

Open the skill to read its SKILL.md instructions.

git-advanced

geoffjay/claude-plugins

Advanced git operations including complex rebase strategies, interactive staging, commit surgery, and history manipulation. Use when user needs to perform complex git operations like rewriting history or advanced merging.

tokio-patterns

geoffjay/claude-plugins

Open the skill to read its SKILL.md instructions.

117 installs

tokio-concurrency

geoffjay/claude-plugins

Advanced concurrency patterns for Tokio including fan-out/fan-in, pipeline processing, rate limiting, and coordinated shutdown. Use when building high-concurrency async systems.

71 installs

git-repository

geoffjay/claude-plugins

Open the skill to read its SKILL.md instructions.

Popular frontend & design skills

View category →

setup-matt-pocock-skills

mattpocock/skills

Configure this repo for the engineering skills: set up its issue tracker, triage label vocabulary, and domain doc layout. Run once before first use of the other engineering skills.

Frontend & Design1.1M installs

frontend-design

anthropics/skills

Guidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults.

OfficialFrontend & Design1M installs

hyperframes-animation

heygen-com/hyperframes

All animation knowledge for HyperFrames — atomic motion rules, multi-phase scene blueprints, scene transitions, broader motion-design techniques, AND the seven runtime adapters (GSAP default, plus Lottie, Three.js, Anime.js, CSS keyframes, Web Animations API, TypeGPU). Use for any motion or animation task: pick 2-4 rules and compose, or load a blueprint, or look up runtime-specific API (e.g. GSAP eases / Lottie player / Three.js mixer). Also covers auditing an existing composition's choreography (animation map) and 24 named text-animation effects. HyperFrames-native: single paused timeline, seek-safe, deterministic.

prototype

mattpocock/skills

Build a throwaway prototype to answer a design question. Use when the user wants to sanity-check whether a state model or logic feels right, or explore what a UI should look like.

Frontend & Design999.2K installs

hyperframes-core

heygen-com/hyperframes

The HyperFrames composition contract — build one renderable project. Use for composition structure, the data- timing attributes, class="clip", tracks, sub-compositions, variables, framework-owned media playback, deterministic-render rules, and validation. Read before writing composition HTML.

Frontend & Design930.5K installs

vercel-react-best-practices

vercel-labs/agent-skills

React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React/Next.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.

OfficialFrontend & Design843.1K installs