Skip to main content

waft_widgets/framework/
inherited_model.rs

1//! Flutter counterpart: `widgets/inherited_model.dart` (`InheritedModel`,
2//! `InheritedModelElement`).
3//!
4//! [`InheritedModelElement`] is Dart's `InheritedModelElement extends InheritedElement`: the
5//! same struct as `InheritedElement` with `update_dependencies` and `notify_dependent`
6//! replaced. `InheritedElement` is a concrete struct with no override point, so the shared
7//! bodies are repeated here rather than inherited; see `PORTING.md`.
8
9use std::any::{Any, TypeId};
10use std::collections::{HashMap, HashSet};
11use std::fmt::{self, Debug};
12use std::hash::Hash;
13use std::marker::PhantomData;
14use std::rc::Rc;
15
16use waft_foundation::{App, Handle};
17
18use super::element::{
19    AnyElement, BuildContext, Element, ElementData, ElementLifecycle, Slot,
20    debug_check_owner_build_target_exists,
21};
22use super::elements::{ComponentElement, ComponentElementData, ProxyElement};
23use super::widget::{
24    InheritedWidget, IntoWidget, KeyRef, Widget, WidgetKind, WidgetRef, downcast_widget,
25    short_type_name,
26};
27
28/// An [`InheritedWidget`] that's intended to be used as the base class for models whose
29/// dependents may only depend on one part or "aspect" of the overall model.
30///
31/// An inherited widget's dependents are unconditionally rebuilt when the inherited widget
32/// changes per [`InheritedWidget::update_should_notify`]. This widget is similar except that
33/// dependents aren't rebuilt unconditionally.
34///
35/// Widgets that depend on an [`InheritedModel`] qualify their dependence with a value that
36/// indicates what "aspect" of the model they depend on. When the model is rebuilt,
37/// dependents will also be rebuilt, but only if there was a change in the model that
38/// corresponds to the aspect they provided.
39///
40/// The associated type [`Aspect`](Self::Aspect) is the type of the model aspect objects
41/// (Dart's type parameter `T`).
42///
43/// Widgets create a dependency on an [`InheritedModel`] with a static method:
44/// [`inherit_from`](Self::inherit_from). This method's `context` parameter defines the
45/// subtree that will be rebuilt when the model changes. Typically the `inherit_from` method
46/// is called from a model-specific static `maybe_of` or `of` methods, a convention that is
47/// present in many Flutter framework classes which look things up. For example:
48///
49/// ```text
50/// impl MyModel {
51///     fn maybe_of(app: &mut App, context: BuildContext, aspect: Option<String>) -> Option<MyModel> {
52///         MyModel::inherit_from(app, context, aspect).cloned()
53///     }
54/// }
55/// ```
56///
57/// Calling `MyModel::maybe_of(app, context, Some("foo".into()))` means that `context`
58/// should only be rebuilt when the `foo` aspect of `MyModel` changes. If the `aspect` is
59/// `None`, then the model supports all aspects.
60///
61/// When the inherited model is rebuilt the [`update_should_notify`](InheritedWidget::update_should_notify)
62/// and [`update_should_notify_dependent`](Self::update_should_notify_dependent) methods are
63/// used to decide what should be rebuilt. If `update_should_notify` returns true, then the
64/// inherited model's `update_should_notify_dependent` method is tested for each dependent
65/// and the set of aspect objects it depends on. The `update_should_notify_dependent` method
66/// must compare the set of aspect dependencies with the changes in the model itself.
67///
68/// The dependencies checked by `update_should_notify_dependent` are just the aspects
69/// passed to `depend_on_inherited_widget_of_exact_type_with_aspect`. They're represented as
70/// a set because one widget can depend on more than one aspect of the model. If a widget
71/// depends on the model but doesn't specify an aspect, then changes in the model will cause
72/// the widget to be rebuilt unconditionally.
73///
74/// A model is both an [`InheritedWidget`] and an [`InheritedModel`], so the kind tag of
75/// [`IntoWidget`] cannot be inferred for it: the model type names the conversion itself
76/// (`fn into_widget(self) -> WidgetRef { IntoWidget::<InheritedModelKind>::into_widget(self) }`).
77///
78/// See also:
79///
80/// * [`InheritedWidget`], an inherited widget that only notifies dependents when its value
81///   is different.
82/// * `InheritedNotifier`, an inherited widget whose value can be a `Listenable`, and which
83///   will notify dependents whenever the value sends notifications.
84pub trait InheritedModel: InheritedWidget {
85    /// The type of the model aspect objects; Dart's `T`.
86    type Aspect: Clone + Eq + Hash + 'static;
87
88    /// Return true if the changes between this model and `old_widget` match any of the
89    /// `dependencies`.
90    fn update_should_notify_dependent(
91        &self,
92        old_widget: &Self,
93        dependencies: &HashSet<Self::Aspect>,
94    ) -> bool;
95
96    /// Returns true if this model supports the given `aspect`.
97    ///
98    /// Returns true by default: this model supports all aspects.
99    ///
100    /// Subclasses may override this method to indicate that they do not support all model
101    /// aspects. This is typically done when a model can be used to "shadow" some aspects of
102    /// an ancestor.
103    fn is_supported_aspect(&self, aspect: &Self::Aspect) -> bool {
104        let _ = aspect;
105        true
106    }
107
108    /// Makes `context` dependent on the specified `aspect` of an [`InheritedModel`] of this
109    /// type.
110    ///
111    /// When the given `aspect` of the model changes, the `context` will be rebuilt. The
112    /// [`update_should_notify_dependent`](Self::update_should_notify_dependent) method must
113    /// determine if a change in the model widget corresponds to an `aspect` value.
114    ///
115    /// The dependencies created by this method target all [`InheritedModel`] ancestors of
116    /// this type up to and including the first one for which
117    /// [`is_supported_aspect`](Self::is_supported_aspect) returns true.
118    ///
119    /// If `aspect` is `None` this method is the same as
120    /// `context.depend_on_inherited_widget_of_exact_type::<Self>()`.
121    ///
122    /// If no ancestor of this type exists, `None` is returned.
123    ///
124    /// Dart's `InheritedModel.inheritFrom<T>(context, aspect: aspect)` is
125    /// `T::inherit_from(app, context, aspect)`.
126    fn inherit_from(
127        app: &mut App,
128        context: BuildContext,
129        aspect: Option<Self::Aspect>,
130    ) -> Option<&Self>
131    where
132        Self: Sized,
133    {
134        let Some(aspect) = aspect else {
135            return context.depend_on_inherited_widget_of_exact_type::<Self>(app);
136        };
137
138        // Create a dependency on all of the type T ancestor models up until
139        // a model is found for which isSupportedAspect(aspect) is true.
140        let mut models = Vec::new();
141        find_models::<Self>(app, context, &aspect, &mut models);
142        let last_model = *models.last()?;
143        for model in models {
144            let erased: Rc<dyn Any> = Rc::new(aspect.clone());
145            context.depend_on_inherited_element(app, model, Some(erased));
146            if model == last_model {
147                let widget: &WidgetRef = model.widget(app);
148                return downcast_widget::<Self>(&**widget);
149            }
150        }
151
152        unreachable!("the last model is in the list");
153    }
154}
155
156/// Dart's `InheritedModel._findModels`: `results` will be a list of all of `context`'s type
157/// `T` ancestors concluding with the one that supports the specified model `aspect`.
158fn find_models<T: InheritedModel>(
159    app: &App,
160    context: BuildContext,
161    aspect: &T::Aspect,
162    results: &mut Vec<AnyElement>,
163) {
164    let Some(model) = context.get_element_for_inherited_widget_of_exact_type::<T>(app) else {
165        return;
166    };
167
168    results.push(model);
169
170    let model_widget: &T = downcast_widget::<T>(&**model.widget(app))
171        .expect("an InheritedModel element holds its InheritedModel");
172    if model_widget.is_supported_aspect(aspect) {
173        return;
174    }
175
176    let mut model_parent = None;
177    model.visit_ancestor_elements(app, &mut |ancestor| {
178        model_parent = Some(ancestor);
179        false
180    });
181    let Some(model_parent) = model_parent else {
182        return;
183    };
184
185    find_models::<T>(app, model_parent, aspect, results);
186}
187
188// ---------------------------------------------------------------------------------------------
189// The erased form
190
191/// The kind tag of [`IntoWidget`] for an [`InheritedModel`].
192pub struct InheritedModelKind;
193
194/// The erased form of an [`InheritedModel`].
195pub struct InheritedModelWrapper<W: InheritedModel>(pub W, pub(crate) crate::CreationLocation);
196
197impl<W: InheritedModel> IntoWidget<InheritedModelKind> for W {
198    #[cfg_attr(debug_assertions, track_caller)]
199    fn into_widget(self) -> WidgetRef {
200        if cfg!(debug_assertions) {
201            InheritedWidget::debug_check_constructor(&self);
202        }
203        Rc::new(InheritedModelWrapper(
204            self,
205            crate::CreationLocation::of_caller(),
206        ))
207    }
208}
209
210impl<W: InheritedModel> Widget for InheritedModelWrapper<W> {
211    fn key(&self) -> Option<&KeyRef> {
212        self.0.key()
213    }
214
215    fn creation_location(&self) -> Option<&'static std::panic::Location<'static>> {
216        self.1.location()
217    }
218
219    fn debug_fill_properties(
220        &self,
221        app: &App,
222        properties: &mut waft_foundation::DiagnosticPropertiesBuilder,
223    ) {
224        InheritedWidget::debug_fill_properties(&self.0, app, properties);
225    }
226
227    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
228        InheritedModelElement::<W>::new(app, this).as_element()
229    }
230
231    fn as_any(&self) -> &dyn Any {
232        &self.0
233    }
234
235    fn widget_type(&self) -> TypeId {
236        TypeId::of::<W>()
237    }
238
239    fn type_name(&self) -> &'static str {
240        short_type_name::<W>()
241    }
242
243    fn kind(&self) -> WidgetKind {
244        WidgetKind::Other
245    }
246}
247
248impl<W: InheritedModel> Debug for InheritedModelWrapper<W> {
249    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
250        self.0.fmt(f)
251    }
252}
253
254// ---------------------------------------------------------------------------------------------
255// InheritedModelElement
256
257/// An [`Element`] that uses an [`InheritedModel`] as its configuration.
258///
259/// Dart's `_dependents` maps each dependent to `Object?`; here it holds what the model
260/// element's casts assert: the set of aspects the dependent depends on, empty when it
261/// depends on the whole model.
262pub struct InheritedModelElement<W: InheritedModel> {
263    element: ElementData,
264    component: ComponentElementData,
265    dependents: HashMap<AnyElement, HashSet<W::Aspect>>,
266    marker: PhantomData<fn() -> W>,
267}
268
269impl<W: InheritedModel> InheritedModelElement<W> {
270    /// Creates an element that uses the given widget as its configuration.
271    pub fn new(app: &mut App, widget: WidgetRef) -> Handle<Self> {
272        debug_assert!(downcast_widget::<W>(&*widget).is_some());
273        app.create(InheritedModelElement::<W> {
274            element: ElementData::new(widget),
275            component: ComponentElementData::default(),
276            dependents: HashMap::new(),
277            marker: PhantomData,
278        })
279        .into_tree_node(app)
280    }
281
282    /// The widget, typed.
283    pub fn widget(self: Handle<Self>, app: &App) -> &W {
284        downcast_widget::<W>(&**self.as_element().widget(app))
285            .expect("an InheritedModelElement holds its InheritedModel")
286    }
287
288    /// Returns the dependencies value recorded for `dependent` with
289    /// [`set_dependencies`](Self::set_dependencies): the aspects it depends on, or `None`
290    /// if it is not a dependent.
291    pub fn get_dependencies(
292        self: Handle<Self>,
293        app: &App,
294        dependent: AnyElement,
295    ) -> Option<&HashSet<W::Aspect>> {
296        app.get(self).dependents.get(&dependent)
297    }
298
299    /// Sets the value returned by [`get_dependencies`](Self::get_dependencies) value for
300    /// `dependent`.
301    pub fn set_dependencies(
302        self: Handle<Self>,
303        app: &mut App,
304        dependent: AnyElement,
305        value: HashSet<W::Aspect>,
306    ) {
307        app.get_mut(self).dependents.insert(dependent, value);
308    }
309
310    /// Called by [`notify_clients`](ProxyElement::notify_clients) for each dependent.
311    ///
312    /// Calls `dependent.did_change_dependencies()` when the dependent depends on the whole
313    /// model, or when [`InheritedModel::update_should_notify_dependent`] says one of its
314    /// aspects changed.
315    pub fn notify_dependent(
316        self: Handle<Self>,
317        app: &mut App,
318        old_widget: &WidgetRef,
319        dependent: AnyElement,
320    ) {
321        let Some(dependencies) = self.get_dependencies(app, dependent) else {
322            return;
323        };
324        let should_notify = dependencies.is_empty() || {
325            let old =
326                downcast_widget::<W>(&**old_widget).expect("the old widget has the same type");
327            self.widget(app)
328                .update_should_notify_dependent(old, dependencies)
329        };
330        if should_notify {
331            dependent.did_change_dependencies(app);
332        }
333    }
334}
335
336impl<W: InheritedModel> ComponentElement for InheritedModelElement<W> {
337    fn component_data(self: Handle<Self>, app: &App) -> &ComponentElementData {
338        &app.get(self).component
339    }
340
341    fn component_data_mut(self: Handle<Self>, app: &mut App) -> &mut ComponentElementData {
342        &mut app.get_mut(self).component
343    }
344
345    fn build(self: Handle<Self>, app: &mut App) -> WidgetRef {
346        self.proxied_child(app)
347    }
348}
349
350impl<W: InheritedModel> ProxyElement for InheritedModelElement<W> {
351    fn proxied_child(self: Handle<Self>, app: &App) -> WidgetRef {
352        self.widget(app).child().clone()
353    }
354
355    fn updated(self: Handle<Self>, app: &mut App, old_widget: WidgetRef) {
356        let should_notify = {
357            let old =
358                &downcast_widget::<W>(&*old_widget).expect("the old widget has the same type");
359            self.widget(app).update_should_notify(old)
360        };
361        if should_notify {
362            self.notify_clients(app, old_widget);
363        }
364    }
365
366    fn notify_clients(self: Handle<Self>, app: &mut App, old_widget: WidgetRef) {
367        debug_assert!(debug_check_owner_build_target_exists(
368            self.as_element(),
369            app,
370            "notifyClients"
371        ));
372        let dependents: Vec<AnyElement> = app.get(self).dependents.keys().copied().collect();
373        for dependent in dependents {
374            if cfg!(debug_assertions) {
375                // check that it really is our descendant
376                let mut ancestor = dependent.parent(app);
377                while let Some(current) = ancestor
378                    && current != self.as_element()
379                {
380                    ancestor = current.parent(app);
381                }
382                debug_assert!(ancestor == Some(self.as_element()));
383                // check that it really depends on us
384                debug_assert!(dependent.does_depend_on_inherited_element(app, self.as_element()));
385            }
386            self.notify_dependent(app, &old_widget, dependent);
387        }
388    }
389}
390
391impl<W: InheritedModel> Element for InheritedModelElement<W> {
392    crate::element_accessors!();
393
394    fn visit_children(self: Handle<Self>, app: &App, visitor: &mut dyn FnMut(AnyElement)) {
395        ComponentElement::visit_children_component(self, app, visitor);
396    }
397
398    fn render_object_attaching_child(self: Handle<Self>, app: &App) -> Option<AnyElement> {
399        ComponentElement::child(self, app)
400    }
401
402    fn forget_child(self: Handle<Self>, app: &mut App, child: AnyElement) {
403        ComponentElement::forget_child(self, app, child);
404    }
405
406    // `debug_doing_build` keeps the trait default: `ComponentElementData` does not expose the
407    // flag `ComponentElement::perform_rebuild` sets.
408
409    #[inline(always)]
410    fn mount(
411        self: Handle<Self>,
412        app: &mut App,
413        parent: Option<AnyElement>,
414        new_slot: Option<Slot>,
415    ) {
416        ComponentElement::mount(self, app, parent, new_slot);
417    }
418
419    #[inline(always)]
420    fn update(self: Handle<Self>, app: &mut App, new_widget: WidgetRef) {
421        ProxyElement::update(self, app, new_widget);
422    }
423
424    #[inline(always)]
425    fn perform_rebuild(self: Handle<Self>, app: &mut App) {
426        ComponentElement::perform_rebuild(self, app);
427    }
428
429    fn update_inheritance(self: Handle<Self>, app: &mut App) {
430        debug_assert!(self.as_element().lifecycle(app) == ElementLifecycle::Active);
431        let incoming = self
432            .as_element()
433            .parent(app)
434            .and_then(|parent| parent.inherited_elements(app));
435        let mut widgets: HashMap<TypeId, AnyElement> = incoming
436            .map(|incoming| (*incoming).clone())
437            .unwrap_or_default();
438        widgets.insert(TypeId::of::<W>(), self.as_element());
439        self.as_element()
440            .set_inherited_elements(app, Some(Rc::new(widgets)));
441    }
442
443    fn debug_deactivated(self: Handle<Self>, app: &mut App) {
444        debug_assert!(app.get(self).dependents.is_empty());
445        debug_assert!(self.as_element().lifecycle(app) == ElementLifecycle::Inactive);
446    }
447
448    const IS_INHERITED_ELEMENT: bool = true;
449
450    fn update_dependencies(
451        self: Handle<Self>,
452        app: &mut App,
453        dependent: AnyElement,
454        aspect: Option<Rc<dyn Any>>,
455    ) {
456        if self
457            .get_dependencies(app, dependent)
458            .is_some_and(HashSet::is_empty)
459        {
460            return;
461        }
462
463        match aspect {
464            None => self.set_dependencies(app, dependent, HashSet::new()),
465            Some(aspect) => {
466                let aspect = (*aspect)
467                    .downcast_ref::<W::Aspect>()
468                    .expect("an InheritedModel dependency names one of the model's aspects")
469                    .clone();
470                app.get_mut(self)
471                    .dependents
472                    .entry(dependent)
473                    .or_default()
474                    .insert(aspect);
475            }
476        }
477    }
478
479    fn remove_dependent(self: Handle<Self>, app: &mut App, dependent: AnyElement) {
480        app.get_mut(self).dependents.remove(&dependent);
481    }
482}