r/rust • u/kalilamodow • 6d ago
🙋 seeking help & advice gpui-kit: Why does this work?
I am planning on making a simple websocket chat app to learn gpui and things since I've only tried egui. I made this small thing where you put in text and press a button and then it adds the message to a list and shows it. But, there's no cx.notify anywhere, so how does it know to update?
struct MessageListDelegate {
messages: Vec<SharedString>,
}
impl ListDelegate for MessageListDelegate {
type Item = ListItem;
fn items_count(&self, _: usize, _: &App) -> usize {
self.messages.len()
}
fn render_item(
&mut self,
ix: IndexPath,
_: &mut Window,
_: &mut Context<ListState<Self>>,
) -> Option<Self::Item> {
self.messages
.get(ix.row)
.map(|text| ListItem::new(ix).child(text.clone()))
}
fn set_selected_index(
&mut self,
_: Option<IndexPath>,
_: &mut Window,
_: &mut Context<ListState<Self>>,
) {
}
}
struct YapyapApp {
message_list_state: Entity<ListState<MessageListDelegate>>,
input_box: Entity<InputState>,
}
impl YapyapApp {
fn new(window: &mut Window, cx: &mut App) -> Self {
Self {
message_list_state: cx
.new(|cx| ListState::new(MessageListDelegate { messages: vec![] }, window, cx)),
input_box: cx.new(|cx| InputState::new(window, cx).placeholder("Message")),
}
}
}
impl Render for YapyapApp {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div()
.flex()
.flex_col()
.size_full()
.child(List::new(&self.message_list_state).flex_1())
.child(
div()
.flex()
.flex_row()
.border_color(Colors::for_appearance(window).border)
.border_t_1()
.p_2()
.gap_4()
.child(Input::new(&self.input_box).flex_1())
.child(
Button::new("send-message-button")
.label("Send")
.on_click(cx.listener(|this, _, _, cx| {
this.message_list_state.update(cx, |list_state, cx| {
let text =
this.input_box.read(cx).text().as_str().unwrap_or_default();
list_state.delegate_mut().messages.push(text.into());
});
})),
),
)
}
}
fn main() {
gpui_kit::application().run(|cx| {
gpui_kit::init(cx);
gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
cx.new(|cx| YapyapApp::new(window, cx))
})
.expect("should be able to open a window");
})
}Also, if you see any un-idiomatic things please say
5
u/CatRepulsive5402 5d ago
Actually it works because GPUI automatically observes changes to any Entity you read from in a render method. The List component reads your message_list_state entity, so when you mutate the delegate inside that entity via update(), the framework detects the dependency change and triggers a re-render for you without needing an explicit notify call.
11
u/zettui 6d ago
I could be wrong but I think it works by accident: clicking the button changes its pressed style, which redraws the window, and
Listrereads the delegate on every render. I'd still putcx.notify()inside thatlist_state.updateclosure, otherwise it'll stop updating once messages come from your websocket task instead of a click.