Skip to main content

waft_widgets/widgets/
inherited_notifier.rs

1//! Flutter counterpart: `widgets/inherited_notifier.dart`.
2
3use 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
18/// An inherited widget for a [`Listenable`](waft_foundation::Listenable) [`notifier`](Self::notifier), which updates its
19/// dependencies when the notifier is triggered.
20///
21/// This is a variant of [`InheritedWidget`], specialized for implementors of
22/// [`ListenableObject`], such as `ChangeNotifier` or `ValueNotifier`.
23///
24/// Dependents are notified whenever the notifier sends notifications, or
25/// whenever the identity of the notifier changes.
26///
27/// Multiple notifications are coalesced, so that dependents only rebuild once
28/// even if the notifier fires multiple times between two frames.
29///
30/// Typically this trait is implemented by a widget that provides an `of` associated function
31/// calling [`BuildContext::depend_on_inherited_widget_of_exact_type`](crate::AnyElement::depend_on_inherited_widget_of_exact_type)
32/// with that widget's type. The widget's `impl InheritedWidget` writes
33/// [`inherited_notifier_overrides!`](crate::inherited_notifier_overrides) to take Dart's
34/// `updateShouldNotify`, which compares the two notifiers; an implementor that wants other
35/// logic writes its own `update_should_notify` instead.
36///
37/// A widget is both an [`InheritedWidget`] and an [`InheritedNotifier`], so the kind tag of
38/// [`IntoWidget`] cannot be inferred for it: the widget type names the conversion itself
39/// (`fn into_widget(self) -> WidgetRef { IntoWidget::<InheritedNotifierKind>::into_widget(self) }`).
40///
41/// See also:
42///
43///  * `Animation`, an implementation of [`Listenable`](waft_foundation::Listenable) that ticks each frame to
44///    update a value.
45///  * [`ViewportOffset`](waft_rendering::ViewportOffset) or `ScrollPosition`,
46///    implementations of [`Listenable`](waft_foundation::Listenable) that trigger when a view is scrolled.
47///  * [`InheritedWidget`], an inherited widget that only notifies dependents
48///    when its value is different.
49///  * [`InheritedModel`](crate::InheritedModel), an inherited widget that allows clients to
50///    subscribe to changes for subparts of the value.
51pub trait InheritedNotifier: InheritedWidget {
52    /// The type of the notifier; Dart's type parameter `T extends Listenable`.
53    type Notifier: ListenableObject;
54
55    /// The [`Listenable`](waft_foundation::Listenable) object to which to listen.
56    ///
57    /// Whenever this object sends change notifications, the dependents of this
58    /// widget are triggered.
59    ///
60    /// By default, whenever the notifier is changed (including when changing to
61    /// or from `None`), if the old notifier is not equal to the new notifier,
62    /// notifications are sent. This behavior can be overridden by writing
63    /// [`InheritedWidget::update_should_notify`] by hand instead of using
64    /// [`inherited_notifier_overrides!`](crate::inherited_notifier_overrides).
65    ///
66    /// While the notifier is `None`, no notifications are sent, since the missing
67    /// object cannot itself send notifications.
68    fn notifier(&self) -> Option<Handle<Self::Notifier>>;
69}
70
71/// Dart's `InheritedNotifier.updateShouldNotify`. Write it inside
72/// `impl InheritedWidget for MyWidget { .. }`.
73#[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
83/// The kind tag of [`IntoWidget`] for an [`InheritedNotifier`].
84pub struct InheritedNotifierKind;
85
86/// The erased form of an [`InheritedNotifier`].
87pub 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
138// ---------------------------------------------------------------------------------------------
139// InheritedNotifierElement
140
141/// An [`Element`] that uses an [`InheritedNotifier`] as its configuration; Dart's
142/// `_InheritedNotifierElement`.
143pub 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    /// Creates an element that uses the given widget as its configuration.
153    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    /// The widget, typed.
171    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    /// Dart's `_handleUpdate` tear-off, which the notifier is listened to with.
177    fn update_listener(self: Handle<Self>) -> Listener {
178        Listener::handle_method(self, InheritedNotifierElement::<W>::handle_update)
179    }
180
181    /// Dart's `_handleUpdate`.
182    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    /// See [`InheritedElement::get_dependencies`](crate::InheritedElement::get_dependencies).
188    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    /// See [`InheritedElement::set_dependencies`](crate::InheritedElement::set_dependencies).
197    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    /// See [`InheritedElement::notify_dependent`](crate::InheritedElement::notify_dependent).
207    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                // check that it really is our descendant
262                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                // check that it really depends on us
270                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}