1use std::rc::Rc;
10
11use crate::component::ComponentId;
12use crate::ui::Ui;
13
14#[derive(Clone, Debug, PartialEq)]
16pub struct Binding {
17 pub property: String,
19 pub source: Option<ComponentId>,
21 pub path: String,
24}
25
26impl Binding {
27 pub fn is_field(&self) -> bool {
29 !self.path.starts_with('=') && !self.path.contains('{')
30 }
31}
32
33pub type BindingSink = Rc<dyn Fn(&mut Ui, ComponentId)>;
35
36pub const CHANGE_EVENTS: [&str; 2] = ["on_change", "on_click"];
38
39impl Ui {
40 pub fn set_binding(&mut self, id: ComponentId, property: &str, source: Option<ComponentId>, path: &str) {
42 let Some(entry) = self.entry_mut(id) else { return };
43 entry.bindings.retain(|b| b.property != property);
44 if !path.trim().is_empty() {
45 entry.bindings.push(Binding { property: property.to_string(), source, path: path.trim().to_string() });
46 }
47 if let Some(sink) = self.binding_refresh.clone() {
48 sink(self, id);
49 }
50 self.request_repaint();
51 }
52
53 pub fn bindings(&self, id: ComponentId) -> &[Binding] {
55 self.entry(id).map_or(&[], |e| e.bindings.as_slice())
56 }
57
58 pub fn binding(&self, id: ComponentId, property: &str) -> Option<&Binding> {
60 self.bindings(id).iter().find(|b| b.property == property)
61 }
62
63 pub fn bound_to(&self, source: ComponentId) -> Vec<ComponentId> {
65 self.components().filter(|&c| self.bindings(c).iter().any(|b| b.source == Some(source))).collect()
66 }
67
68 pub fn set_binding_sink(&mut self, sink: BindingSink, refresh: BindingSink) {
72 self.binding_sink = Some(sink);
73 self.binding_refresh = Some(refresh);
74 }
75
76 pub(crate) fn binding_changed(&mut self, id: ComponentId, event: &str) {
78 if !CHANGE_EVENTS.contains(&event) || self.bindings(id).is_empty() || self.design_mode {
79 return;
80 }
81 if let Some(sink) = self.binding_sink.clone() {
82 sink(self, id);
83 }
84 }
85}