1use 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
28pub trait InheritedModel: InheritedWidget {
85 type Aspect: Clone + Eq + Hash + 'static;
87
88 fn update_should_notify_dependent(
91 &self,
92 old_widget: &Self,
93 dependencies: &HashSet<Self::Aspect>,
94 ) -> bool;
95
96 fn is_supported_aspect(&self, aspect: &Self::Aspect) -> bool {
104 let _ = aspect;
105 true
106 }
107
108 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 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
156fn 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
188pub struct InheritedModelKind;
193
194pub 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
254pub 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 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 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 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 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 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 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 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 #[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}