gpui-entities
БесплатноБез исполняемых скриптовНе проверенEntity and context patterns for state management in GPUI. Use when managing component state, implementing entity lifecycle, handling subscriptions, or…
Об этом скилле
GPUI Entities
This skill provides comprehensive patterns for working with entities and contexts in GPUI applications.
Overview
Entities are GPUI's core state management primitive:
- Type-safe handles to state with automatic lifecycle management
- Read/write access with borrow checking at runtime
- Weak references to avoid memory leaks
- Subscriptions for observing state changes
Creating Entities
In Window Context
use gpui::*;
struct MyView {
count: usize,
}
fn main() {
let app = Application::new();
app.run(move |cx| {
cx.spawn(async move |cx| {
cx.open_window(WindowOptions::default(), |window, cx| {
// Create entity with cx.new()
cx.new(|_cx| MyView { count: 0 })
})?;
Ok::<_, anyhow::Error>(())
}).detach();
});
}
In Entity Context
struct ParentView {
child: Entity<ChildView>,
}
impl ParentView {
fn new(cx: &mut Context<Self>) -> Self {
let child = cx.new(|_cx| ChildView::new());
Self { child }
}
}
Reading Entities
Direct Read
fn display_count(entity: &Entity<MyView>, cx: &App) {
let view = entity.read(cx);
println!("Count: {}", view.count);
}
Read with Closure
fn get_count(entity: &Entity<MyView>, cx: &App) -> usize {
entity.read_with(cx, |view, _cx| view.count)
}
Important: The closure return value is returned directly from .read_with().
Updating Entities
Basic Update
fn increment(entity: &Entity<MyView>, cx: &mut App) {
entity.update(cx, |view, cx| {
view.count += 1;
cx.notify(); // Trigger re-render
});
}
Update with Window
Use .update_in() when you need window access:
fn increment_and_dispatch(
entity: &Entity<MyView>,
cx: &mut AsyncWindowContext,
) -> anyhow::Result<()> {
entity.update_in(cx, |view, window, cx| {
view.count += 1;
window.dispatch_action(CountChanged.boxed_clone(), cx);
cx.notify();
})
}
Return Values
// update returns the closure's return value
let new_count = entity.update(cx, |view, cx| {
view.count += 1;
cx.notify();
view.count // Return new count
});
println!("New count: {}", new_count);
WeakEntity
Use WeakEntity<T> to avoid memory leaks when entities reference each other.
Creating Weak References
struct Parent {
child: Entity<Child>,
}
struct Child {
parent: WeakEntity<Parent>, // Weak to avoid cycle
}
impl Parent {
fn new(cx: &mut Context<Self>) -> Self {
let parent_weak = cx.entity().downgrade();
let child = cx.new(|_cx| Child {
parent: parent_weak,
});
Self { child }
}
}
Using Weak References
impl Child {
fn notify_parent(&self, cx: &mut Context<Self>) {
if let Some(parent) = self.parent.upgrade() {
parent.update(cx, |parent, cx| {
parent.handle_child_event(cx);
});
}
}
}
Async Context with WeakEntity
When using async contexts, methods return anyhow::Result:
fn do_async_work(&self, cx: &mut Context<Self>) {
cx.spawn(async move |this, cx| {
// this: WeakEntity<Self>
// Async work
tokio::time::sleep(Duration::from_secs(1)).await;
// Update returns Result in async context
this.update(&mut *cx, |view, cx| {
view.count += 1;
cx.notify();
})?;
Ok(())
}).detach();
}
Entity Lifecycle
Entity ID
let id = entity.entity_id();
// id: EntityId - unique identifier that persists
Checking Entity Validity
// Strong entity is always valid
let entity: Entity<MyView> = cx.new(|_| MyView { count: 0 });
// entity is guaranteed to be valid
// Weak entity might be invalid
let weak: WeakEntity<MyView> = entity.downgrade();
if let Some(entity) = weak.upgrade() {
// Entity still exists
entity.update(cx, |view, cx| {
// ...
});
} else {
// Entity was dropped
println!("Entity no longer exists");
}
Subscriptions
Subscribe to entity events to observe state changes.
Defining Events
use gpui::*;
#[derive(Clone, Debug)]
enum MyEvent {
CountChanged { new_value: usize },
Reset,
}
// Declare that this entity can emit MyEvent
impl EventEmitter<MyEvent> for MyView {}
Emitting Events
impl MyView {
fn increment(&mut self, cx: &mut Context<Self>) {
self.count += 1;
cx.emit(MyEvent::CountChanged { new_value: self.count });
cx.notify();
}
fn reset(&mut self, cx: &mut Context<Self>) {
self.count = 0;
cx.emit(MyEvent::Reset);
cx.notify();
}
}
Subscribing to Events
struct ParentView {
child: Entity<Ch
Установить gpui-entities в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл gpui-entities?
Entity and context patterns for state management in GPUI. Use when managing component state, implementing entity lifecycle, handling subscriptions, or avoiding common entity access pitfalls.
Как установить скилл gpui-entities?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл gpui-entities запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic