use std::cell::RefCell;
use std::rc::{Rc, Weak};
use typemap::TypeMap;
use crate::{control::ControlObject, ObservableCollection};
pub struct ViewContext {
pub attached_values: TypeMap,
pub children: Box<dyn ObservableCollection<Rc<RefCell<dyn ControlObject>>>>,
}
impl ViewContext {
pub fn empty() -> ViewContext {
ViewContext {
attached_values: TypeMap::new(),
children: Box::new(Vec::new()),
}
}
}
pub trait ViewModel {
fn create_view(view_model: &Rc<RefCell<Self>>) -> Rc<RefCell<dyn ControlObject>>;
}
pub trait ViewModelObject {
fn create_view(&self) -> Rc<RefCell<dyn ControlObject>>;
fn box_clone(&self) -> Box<dyn ViewModelObject>;
fn downgrade(&self) -> Box<dyn WeakViewModelObject>;
}
impl<T: ViewModel + 'static> ViewModelObject for Rc<RefCell<T>> {
fn create_view(&self) -> Rc<RefCell<dyn ControlObject>> {
ViewModel::create_view(self)
}
fn box_clone(&self) -> Box<dyn ViewModelObject> {
Box::new(std::clone::Clone::clone(self))
}
fn downgrade(&self) -> Box<dyn WeakViewModelObject> {
Box::new(Rc::downgrade(self))
}
}
impl Clone for Box<dyn ViewModelObject> {
fn clone(&self) -> Self {
(*self).box_clone()
}
}
pub trait WeakViewModelObject {
fn box_clone(&self) -> Box<dyn WeakViewModelObject>;
fn upgrade(&self) -> Option<Box<dyn ViewModelObject>>;
}
impl<T: ViewModel + 'static> WeakViewModelObject for Weak<RefCell<T>> {
fn box_clone(&self) -> Box<dyn WeakViewModelObject> {
Box::new(std::clone::Clone::clone(self))
}
fn upgrade(&self) -> Option<Box<dyn ViewModelObject>> {
self.upgrade()
.map(|rc| Box::new(rc) as Box<(dyn ViewModelObject + 'static)>)
}
}
impl Clone for Box<dyn WeakViewModelObject> {
fn clone(&self) -> Self {
(*self).box_clone()
}
}