1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
use raui_core::{
    application::ChangeNotifier,
    widget::{component::WidgetComponent, context::*, node::WidgetNode, FnWidget, WidgetRef},
    Lifetime, LifetimeLazy, Managed, ValueReadAccess, ValueWriteAccess,
};
use std::{
    any::Any,
    marker::PhantomData,
    ops::{Deref, DerefMut},
    ptr::NonNull,
};

#[allow(unused_variables)]
pub trait ViewState: Any + Send + Sync {
    fn on_mount(&mut self, context: WidgetMountOrChangeContext) {}
    fn on_unmount(&mut self, context: WidgetUnmountContext) {}
    fn on_change(&mut self, context: WidgetMountOrChangeContext) {}
    fn on_render(&self, context: WidgetContext) -> WidgetNode;
    fn as_any(&self) -> &dyn Any;
    fn as_any_mut(&mut self) -> &mut dyn Any;
}

pub struct View<T: ViewState> {
    inner: Box<dyn ViewState>,
    lifetime: Lifetime,
    _phantom: PhantomData<fn() -> T>,
}

impl<T: ViewState + Default> Default for View<T> {
    fn default() -> Self {
        Self::new(T::default())
    }
}

impl<T: ViewState> View<T> {
    pub fn new(state: T) -> Self
    where
        T: 'static,
    {
        Self {
            inner: Box::new(state),
            lifetime: Default::default(),
            _phantom: Default::default(),
        }
    }

    pub fn into_inner(self) -> Box<dyn ViewState> {
        self.inner
    }

    pub fn as_dyn(&self) -> Option<ValueReadAccess<dyn ViewState>> {
        self.lifetime.read(&*self.inner)
    }

    pub fn as_dyn_mut(&mut self) -> Option<ValueWriteAccess<dyn ViewState>> {
        self.lifetime.write(&mut *self.inner)
    }

    pub fn read(&self) -> Option<ValueReadAccess<T>> {
        self.lifetime.read(self.inner.as_any().downcast_ref::<T>()?)
    }

    pub fn write(&mut self) -> Option<ValueWriteAccess<T>> {
        self.lifetime
            .write(self.inner.as_any_mut().downcast_mut::<T>()?)
    }

    pub fn lazy(&self) -> LazyView<T> {
        unsafe {
            let ptr = self.inner.as_any().downcast_ref::<T>().unwrap() as *const T as *mut T;
            LazyView {
                inner: NonNull::new_unchecked(ptr),
                lifetime: self.lifetime.lazy(),
            }
        }
    }

    pub fn component(&self) -> WidgetComponent {
        WidgetComponent::new(self.widget(), std::any::type_name::<Self>())
    }

    pub fn widget(&self) -> FnWidget {
        let this = self.lazy();
        FnWidget::closure(move |context| {
            let this_mount = this.clone();
            let this_unmount = this.clone();
            let this_change = this.clone();
            context.life_cycle.mount(move |context| {
                if let Some(mut this) = this_mount.write() {
                    this.on_mount(context);
                }
            });
            context.life_cycle.unmount(move |context| {
                if let Some(mut this) = this_unmount.write() {
                    this.on_unmount(context);
                }
            });
            context.life_cycle.change(move |context| {
                if let Some(mut this) = this_change.write() {
                    this.on_change(context);
                }
            });
            this.write()
                .map(|this| this.on_render(context))
                .unwrap_or_default()
        })
    }
}

pub struct LazyView<T: ViewState> {
    inner: NonNull<T>,
    lifetime: LifetimeLazy,
}

unsafe impl<T: ViewState> Send for LazyView<T> {}
unsafe impl<T: ViewState> Sync for LazyView<T> {}

impl<T: ViewState> Clone for LazyView<T> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner,
            lifetime: self.lifetime.clone(),
        }
    }
}

impl<T: ViewState> LazyView<T> {
    pub fn as_dyn(&self) -> Option<ValueReadAccess<dyn ViewState>> {
        unsafe { self.lifetime.read(self.inner.as_ref()) }
    }

    pub fn as_dyn_mut(&self) -> Option<ValueWriteAccess<dyn ViewState>> {
        unsafe { self.lifetime.write(self.inner.as_ptr().as_mut()?) }
    }

    pub fn read(&self) -> Option<ValueReadAccess<T>> {
        unsafe { self.lifetime.read(self.inner.as_ref()) }
    }

    pub fn write(&self) -> Option<ValueWriteAccess<T>> {
        unsafe { self.lifetime.write(self.inner.as_ptr().as_mut()?) }
    }
}

pub struct ViewValue<T> {
    inner: T,
    notifier: Option<ChangeNotifier>,
    id: WidgetRef,
}

impl<T> ViewValue<T> {
    pub fn new(value: T) -> Self {
        Self {
            inner: value,
            notifier: None,
            id: Default::default(),
        }
    }

    pub fn with_notifier(mut self, notifier: ChangeNotifier) -> Self {
        self.bind_notifier(notifier);
        self
    }

    pub fn bind_notifier(&mut self, notifier: ChangeNotifier) {
        if self.notifier.is_none() {
            if let Some(id) = self.id.read() {
                notifier.notify(id);
            }
        }
        self.notifier = Some(notifier);
    }

    pub fn unbind_notifier(&mut self) {
        self.notifier = None;
    }

    pub fn bound_notifier(&self) -> Option<&ChangeNotifier> {
        self.notifier.as_ref()
    }

    pub fn widget_ref(&self) -> WidgetRef {
        self.id.clone()
    }
}

impl<T> Deref for ViewValue<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl<T> DerefMut for ViewValue<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        if let Some(notifier) = self.notifier.as_ref() {
            if let Some(id) = self.id.read() {
                notifier.notify(id);
            }
        }
        &mut self.inner
    }
}

pub struct SharedView<T: ViewState> {
    inner: Managed<Option<View<T>>>,
}

impl<T: ViewState> Default for SharedView<T> {
    fn default() -> Self {
        Self {
            inner: Default::default(),
        }
    }
}

impl<T: ViewState> SharedView<T> {
    pub fn new(view: View<T>) -> Self {
        Self {
            inner: Managed::new(Some(view)),
        }
    }

    pub fn replace(&mut self, view: View<T>) {
        if let Some(mut inner) = self.inner.write() {
            *inner = Some(view);
        }
    }

    pub fn clear(&mut self) {
        if let Some(mut inner) = self.inner.write() {
            *inner = None;
        }
    }

    pub fn read(&self) -> Option<ValueReadAccess<View<T>>> {
        self.inner.read()?.remap(|inner| inner.as_ref()).ok()
    }

    pub fn write(&mut self) -> Option<ValueWriteAccess<View<T>>> {
        self.inner.write()?.remap(|inner| inner.as_mut()).ok()
    }
}

impl<T: ViewState> ViewState for SharedView<T> {
    fn on_render(&self, context: WidgetContext) -> WidgetNode {
        self.inner
            .read()
            .and_then(|inner| {
                inner
                    .as_ref()
                    .map(|inner| inner.component().key(context.key).into())
            })
            .unwrap_or_default()
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }
}