forked from yewstack/yew
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.rs
254 lines (210 loc) · 8.15 KB
/
mod.rs
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
//! Components wrapped with context including properties, state, and link
mod children;
#[cfg(any(feature = "csr", feature = "ssr"))]
mod lifecycle;
mod properties;
mod scope;
use super::{Html, HtmlResult, IntoHtmlResult};
pub use children::*;
pub use properties::*;
#[cfg(feature = "csr")]
pub(crate) use scope::Scoped;
pub use scope::{AnyScope, Scope, SendAsMessage};
use std::rc::Rc;
use std::sync::atomic::{AtomicUsize, Ordering};
/// A unique component ID.
///
/// This type is provided to better distinguish between component IDs and the older pointer-based
/// component ids.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Hash)]
pub(crate) struct ComponentId(usize);
impl Default for ComponentId {
fn default() -> Self {
static COMP_ID_COUNTER: AtomicUsize = AtomicUsize::new(0);
Self(COMP_ID_COUNTER.fetch_add(1, Ordering::SeqCst))
}
}
#[cfg(any(feature = "csr", feature = "ssr"))]
mod feat_csr_ssr {
use super::*;
impl ComponentId {
#[inline]
pub fn new() -> Self {
Self::default()
}
}
#[cfg(debug_assertions)]
thread_local! {
static EVENT_HISTORY: std::cell::RefCell<std::collections::HashMap<ComponentId, Vec<String>>>
= Default::default();
}
/// Push [Component] event to lifecycle debugging registry
#[cfg(debug_assertions)]
pub(crate) fn log_event(comp_id: ComponentId, event: impl ToString) {
EVENT_HISTORY.with(|h| {
h.borrow_mut()
.entry(comp_id)
.or_default()
.push(event.to_string())
});
}
/// Get [Component] event log from lifecycle debugging registry
#[cfg(debug_assertions)]
#[allow(dead_code)]
pub(crate) fn get_event_log(comp_id: ComponentId) -> Vec<String> {
EVENT_HISTORY.with(|h| {
h.borrow()
.get(&comp_id)
.map(|l| (*l).clone())
.unwrap_or_default()
})
}
}
#[cfg(debug_assertions)]
#[cfg(any(feature = "csr", feature = "ssr"))]
pub(crate) use feat_csr_ssr::*;
/// The [`Component`]'s context. This contains component's [`Scope`] and and props and
/// is passed to every lifecycle method.
#[derive(Debug)]
pub struct Context<COMP: BaseComponent> {
scope: Scope<COMP>,
props: Rc<COMP::Properties>,
}
impl<COMP: BaseComponent> Context<COMP> {
/// The component scope
#[inline]
pub fn link(&self) -> &Scope<COMP> {
&self.scope
}
/// The component's props
#[inline]
pub fn props(&self) -> &COMP::Properties {
&*self.props
}
}
pub(crate) mod sealed {
/// A Sealed trait that prevents direct implementation of
/// [BaseComponent].
pub trait SealedBaseComponent {}
}
/// The common base of both function components and struct components.
///
/// If you are taken here by doc links, you might be looking for [`Component`] or
/// [`#[function_component]`](crate::functional::function_component).
///
/// We provide a blanket implementation of this trait for every member that implements [`Component`].
pub trait BaseComponent: sealed::SealedBaseComponent + Sized + 'static {
/// The Component's Message.
type Message: 'static;
/// The Component's Properties.
type Properties: Properties;
/// Creates a component.
fn create(ctx: &Context<Self>) -> Self;
/// Updates component's internal state.
fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool;
/// React to changes of component properties.
fn changed(&mut self, ctx: &Context<Self>) -> bool;
/// Returns a component layout to be rendered.
fn view(&self, ctx: &Context<Self>) -> HtmlResult;
/// Notified after a layout is rendered.
fn rendered(&mut self, ctx: &Context<Self>, first_render: bool);
/// Notified before a component is destroyed.
fn destroy(&mut self, ctx: &Context<Self>);
}
/// Components are the basic building blocks of the UI in a Yew app. Each Component
/// chooses how to display itself using received props and self-managed state.
/// Components can be dynamic and interactive by declaring messages that are
/// triggered and handled asynchronously. This async update mechanism is inspired by
/// Elm and the actor model used in the Actix framework.
pub trait Component: Sized + 'static {
/// Messages are used to make Components dynamic and interactive. Simple
/// Component's can declare their Message type to be `()`. Complex Component's
/// commonly use an enum to declare multiple Message types.
type Message: 'static;
/// The Component's properties.
///
/// When the parent of a Component is re-rendered, it will either be re-created or
/// receive new properties in the context passed to the `changed` lifecycle method.
type Properties: Properties;
/// Called when component is created.
fn create(ctx: &Context<Self>) -> Self;
/// Called when a new message is sent to the component via its scope.
///
/// Components handle messages in their `update` method and commonly use this method
/// to update their state and (optionally) re-render themselves.
///
/// Returned bool indicates whether to render this Component after update.
#[allow(unused_variables)]
fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
false
}
/// Called when properties passed to the component change
///
/// Returned bool indicates whether to render this Component after changed.
#[allow(unused_variables)]
fn changed(&mut self, ctx: &Context<Self>) -> bool {
true
}
/// Components define their visual layout using a JSX-style syntax through the use of the
/// `html!` procedural macro. The full guide to using the macro can be found in [Yew's
/// documentation](https://yew.rs/concepts/html).
///
/// Note that `view()` calls do not always follow a render request from `update()` or
/// `changed()`. Yew may optimize some calls out to reduce virtual DOM tree generation overhead.
/// The `create()` call is always followed by a call to `view()`.
fn view(&self, ctx: &Context<Self>) -> Html;
/// The `rendered` method is called after each time a Component is rendered but
/// before the browser updates the page.
///
/// Note that `rendered()` calls do not always follow a render request from `update()` or
/// `changed()`. Yew may optimize some calls out to reduce virtual DOM tree generation overhead.
/// The `create()` call is always followed by a call to `view()` and later `rendered()`.
#[allow(unused_variables)]
fn rendered(&mut self, ctx: &Context<Self>, first_render: bool) {}
/// Called right before a Component is unmounted.
#[allow(unused_variables)]
fn destroy(&mut self, ctx: &Context<Self>) {}
}
impl<T> BaseComponent for T
where
T: Sized + Component + 'static,
{
type Message = <T as Component>::Message;
type Properties = <T as Component>::Properties;
fn create(ctx: &Context<Self>) -> Self {
Component::create(ctx)
}
fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
Component::update(self, ctx, msg)
}
fn changed(&mut self, ctx: &Context<Self>) -> bool {
Component::changed(self, ctx)
}
fn view(&self, ctx: &Context<Self>) -> HtmlResult {
Component::view(self, ctx).into_html_result()
}
fn rendered(&mut self, ctx: &Context<Self>, first_render: bool) {
Component::rendered(self, ctx, first_render)
}
fn destroy(&mut self, ctx: &Context<Self>) {
Component::destroy(self, ctx)
}
}
impl<T> sealed::SealedBaseComponent for T where T: Sized + Component + 'static {}
/// A trait that indicates a type is able to be converted into a component.
///
/// You may want to use this trait if you want to accept both function components and struct
/// components as a generic parameter.
pub trait IntoComponent {
/// The Component's Properties.
type Properties: Properties;
/// The Component Type.
type Component: BaseComponent<Properties = Self::Properties> + 'static;
}
impl<T> IntoComponent for T
where
T: BaseComponent + 'static,
{
type Properties = T::Properties;
type Component = T;
}