1use std::any::{Any, TypeId};
4use std::collections::HashMap;
5use std::fmt::{self, Debug};
6use std::marker::PhantomData;
7use std::panic::Location;
8use std::rc::Rc;
9
10use waft_foundation::{App, Handle, ListenableObject, Listener};
11
12use crate::framework::{
13 AnyElement, ComponentElement, ComponentElementData, CreationLocation, Element, ElementBase,
14 ElementData, ElementLifecycle, InheritedWidget, IntoWidget, KeyRef, ProxyElement, Slot, Widget,
15 WidgetKind, WidgetRef, debug_check_owner_build_target_exists, downcast_widget, short_type_name,
16};
17
18pub trait InheritedNotifier: InheritedWidget {
52 type Notifier: ListenableObject;
54
55 fn notifier(&self) -> Option<Handle<Self::Notifier>>;
69}
70
71#[macro_export]
74macro_rules! inherited_notifier_overrides {
75 () => {
76 fn update_should_notify(&self, old_widget: &Self) -> bool {
77 $crate::InheritedNotifier::notifier(old_widget)
78 != $crate::InheritedNotifier::notifier(self)
79 }
80 };
81}
82
83pub struct InheritedNotifierKind;
85
86pub struct InheritedNotifierWrapper<W: InheritedNotifier>(pub W, pub(crate) CreationLocation);
88
89impl<W: InheritedNotifier> IntoWidget<InheritedNotifierKind> for W {
90 #[cfg_attr(debug_assertions, track_caller)]
91 fn into_widget(self) -> WidgetRef {
92 if cfg!(debug_assertions) {
93 InheritedWidget::debug_check_constructor(&self);
94 }
95 Rc::new(InheritedNotifierWrapper(
96 self,
97 CreationLocation::of_caller(),
98 ))
99 }
100}
101
102impl<W: InheritedNotifier> Widget for InheritedNotifierWrapper<W> {
103 fn key(&self) -> Option<&KeyRef> {
104 self.0.key()
105 }
106
107 fn creation_location(&self) -> Option<&'static Location<'static>> {
108 self.1.location()
109 }
110
111 fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
112 InheritedNotifierElement::<W>::new(app, this).as_element()
113 }
114
115 fn as_any(&self) -> &dyn Any {
116 &self.0
117 }
118
119 fn widget_type(&self) -> TypeId {
120 TypeId::of::<W>()
121 }
122
123 fn type_name(&self) -> &'static str {
124 short_type_name::<W>()
125 }
126
127 fn kind(&self) -> WidgetKind {
128 WidgetKind::Other
129 }
130}
131
132impl<W: InheritedNotifier> Debug for InheritedNotifierWrapper<W> {
133 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
134 self.0.fmt(f)
135 }
136}
137
138pub struct InheritedNotifierElement<W: InheritedNotifier> {
144 element: ElementData,
145 component: ComponentElementData,
146 dependents: HashMap<AnyElement, Option<Rc<dyn Any>>>,
147 dirty: bool,
148 marker: PhantomData<fn() -> W>,
149}
150
151impl<W: InheritedNotifier> InheritedNotifierElement<W> {
152 pub fn new(app: &mut App, widget: WidgetRef) -> Handle<Self> {
154 debug_assert!(downcast_widget::<W>(&*widget).is_some());
155 let this = app
156 .create(InheritedNotifierElement::<W> {
157 element: ElementData::new(widget),
158 component: ComponentElementData::default(),
159 dependents: HashMap::new(),
160 dirty: false,
161 marker: PhantomData,
162 })
163 .into_tree_node(app);
164 if let Some(notifier) = this.widget(app).notifier() {
165 notifier.add_listener(app, this.update_listener());
166 }
167 this
168 }
169
170 pub fn widget(self: Handle<Self>, app: &App) -> &W {
172 downcast_widget::<W>(&**self.as_element().widget(app))
173 .expect("an InheritedNotifierElement holds its InheritedNotifier")
174 }
175
176 fn update_listener(self: Handle<Self>) -> Listener {
178 Listener::handle_method(self, InheritedNotifierElement::<W>::handle_update)
179 }
180
181 fn handle_update(self: Handle<Self>, app: &mut App) {
183 app.get_mut(self).dirty = true;
184 self.as_element().mark_needs_build(app);
185 }
186
187 pub fn get_dependencies(
189 self: Handle<Self>,
190 app: &App,
191 dependent: AnyElement,
192 ) -> Option<Rc<dyn Any>> {
193 app.get(self).dependents.get(&dependent).cloned().flatten()
194 }
195
196 pub fn set_dependencies(
198 self: Handle<Self>,
199 app: &mut App,
200 dependent: AnyElement,
201 value: Option<Rc<dyn Any>>,
202 ) {
203 app.get_mut(self).dependents.insert(dependent, value);
204 }
205
206 pub fn notify_dependent(
208 self: Handle<Self>,
209 app: &mut App,
210 old_widget: &WidgetRef,
211 dependent: AnyElement,
212 ) {
213 let _ = (self, old_widget);
214 dependent.did_change_dependencies(app);
215 }
216}
217
218impl<W: InheritedNotifier> ComponentElement for InheritedNotifierElement<W> {
219 fn component_data(self: Handle<Self>, app: &App) -> &ComponentElementData {
220 &app.get(self).component
221 }
222
223 fn component_data_mut(self: Handle<Self>, app: &mut App) -> &mut ComponentElementData {
224 &mut app.get_mut(self).component
225 }
226
227 fn build(self: Handle<Self>, app: &mut App) -> WidgetRef {
228 if app.get(self).dirty {
229 let widget = self.as_element().widget(app).clone();
230 self.notify_clients(app, widget);
231 }
232 self.proxied_child(app)
233 }
234}
235
236impl<W: InheritedNotifier> ProxyElement for InheritedNotifierElement<W> {
237 fn proxied_child(self: Handle<Self>, app: &App) -> WidgetRef {
238 self.widget(app).child().clone()
239 }
240
241 fn updated(self: Handle<Self>, app: &mut App, old_widget: WidgetRef) {
242 let should_notify = {
243 let old =
244 &downcast_widget::<W>(&*old_widget).expect("the old widget has the same type");
245 self.widget(app).update_should_notify(old)
246 };
247 if should_notify {
248 self.notify_clients(app, old_widget);
249 }
250 }
251
252 fn notify_clients(self: Handle<Self>, app: &mut App, old_widget: WidgetRef) {
253 debug_assert!(debug_check_owner_build_target_exists(
254 self.as_element(),
255 app,
256 "notifyClients"
257 ));
258 let dependents: Vec<AnyElement> = app.get(self).dependents.keys().copied().collect();
259 for dependent in dependents {
260 if cfg!(debug_assertions) {
261 let mut ancestor = dependent.parent(app);
263 while let Some(current) = ancestor
264 && current != self.as_element()
265 {
266 ancestor = current.parent(app);
267 }
268 debug_assert!(ancestor == Some(self.as_element()));
269 debug_assert!(dependent.does_depend_on_inherited_element(app, self.as_element()));
271 }
272 self.notify_dependent(app, &old_widget, dependent);
273 }
274 app.get_mut(self).dirty = false;
275 }
276}
277
278impl<W: InheritedNotifier> Element for InheritedNotifierElement<W> {
279 crate::element_accessors!();
280
281 fn visit_children(self: Handle<Self>, app: &App, visitor: &mut dyn FnMut(AnyElement)) {
282 ComponentElement::visit_children_component(self, app, visitor);
283 }
284
285 fn render_object_attaching_child(self: Handle<Self>, app: &App) -> Option<AnyElement> {
286 ComponentElement::child(self, app)
287 }
288
289 fn forget_child(self: Handle<Self>, app: &mut App, child: AnyElement) {
290 ComponentElement::forget_child(self, app, child);
291 }
292
293 fn debug_doing_build(self: Handle<Self>, app: &App) -> bool {
294 self.component_data(app).debug_doing_build
295 }
296
297 #[inline(always)]
298 fn mount(
299 self: Handle<Self>,
300 app: &mut App,
301 parent: Option<AnyElement>,
302 new_slot: Option<Slot>,
303 ) {
304 ComponentElement::mount(self, app, parent, new_slot);
305 }
306
307 #[inline(always)]
308 fn update(self: Handle<Self>, app: &mut App, new_widget: WidgetRef) {
309 let old_notifier = self.widget(app).notifier();
310 let new_notifier = downcast_widget::<W>(&*new_widget)
311 .expect("the new widget has the same type")
312 .notifier();
313 if old_notifier != new_notifier {
314 if let Some(old_notifier) = old_notifier {
315 old_notifier.remove_listener(app, &self.update_listener());
316 }
317 if let Some(new_notifier) = new_notifier {
318 new_notifier.add_listener(app, self.update_listener());
319 }
320 }
321 ProxyElement::update(self, app, new_widget);
322 }
323
324 #[inline(always)]
325 fn perform_rebuild(self: Handle<Self>, app: &mut App) {
326 ComponentElement::perform_rebuild(self, app);
327 }
328
329 fn update_inheritance(self: Handle<Self>, app: &mut App) {
330 debug_assert!(self.as_element().lifecycle(app) == ElementLifecycle::Active);
331 let incoming = self
332 .as_element()
333 .parent(app)
334 .and_then(|parent| parent.inherited_elements(app));
335 let mut widgets: HashMap<TypeId, AnyElement> = incoming
336 .map(|incoming| (*incoming).clone())
337 .unwrap_or_default();
338 widgets.insert(TypeId::of::<W>(), self.as_element());
339 self.as_element()
340 .set_inherited_elements(app, Some(Rc::new(widgets)));
341 }
342
343 fn debug_deactivated(self: Handle<Self>, app: &mut App) {
344 debug_assert!(app.get(self).dependents.is_empty());
345 debug_assert!(self.as_element().lifecycle(app) == ElementLifecycle::Inactive);
346 }
347
348 fn unmount(self: Handle<Self>, app: &mut App) {
349 if let Some(notifier) = self.widget(app).notifier() {
350 notifier.remove_listener(app, &self.update_listener());
351 }
352 ElementBase::unmount(self, app);
353 }
354
355 const IS_INHERITED_ELEMENT: bool = true;
356
357 fn update_dependencies(
358 self: Handle<Self>,
359 app: &mut App,
360 dependent: AnyElement,
361 aspect: Option<Rc<dyn Any>>,
362 ) {
363 let _ = aspect;
364 self.set_dependencies(app, dependent, None);
365 }
366
367 fn remove_dependent(self: Handle<Self>, app: &mut App, dependent: AnyElement) {
368 app.get_mut(self).dependents.remove(&dependent);
369 }
370}