forked from yewstack/yew
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.rs
392 lines (343 loc) · 10.6 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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
//! This module contains Yew's implementation of a reactive virtual DOM.
#[doc(hidden)]
pub mod key;
#[doc(hidden)]
pub mod listeners;
#[doc(hidden)]
pub mod vcomp;
#[doc(hidden)]
pub mod vlist;
#[doc(hidden)]
pub mod vnode;
#[doc(hidden)]
pub mod vportal;
#[doc(hidden)]
pub mod vsuspense;
#[doc(hidden)]
pub mod vtag;
#[doc(hidden)]
pub mod vtext;
#[doc(inline)]
pub use self::key::Key;
#[doc(inline)]
pub use self::listeners::*;
#[doc(inline)]
pub use self::vcomp::{VChild, VComp};
#[doc(inline)]
pub use self::vlist::VList;
#[doc(inline)]
pub use self::vnode::VNode;
#[doc(inline)]
pub use self::vportal::VPortal;
#[doc(inline)]
pub use self::vsuspense::VSuspense;
#[doc(inline)]
pub use self::vtag::VTag;
#[doc(inline)]
pub use self::vtext::VText;
use indexmap::IndexMap;
use std::borrow::{Borrow, Cow};
use std::fmt::Formatter;
use std::hash::{Hash, Hasher};
use std::ops::Deref;
use std::rc::Rc;
use std::{fmt, hint::unreachable_unchecked};
/// Attribute value
#[derive(Debug)]
pub enum AttrValue {
/// String living for `'static`
Static(&'static str),
/// Reference counted string
Rc(Rc<str>),
}
impl Deref for AttrValue {
type Target = str;
#[inline(always)]
fn deref(&self) -> &Self::Target {
match self {
AttrValue::Static(s) => *s,
AttrValue::Rc(s) => &*s,
}
}
}
impl Hash for AttrValue {
#[inline(always)]
fn hash<H: Hasher>(&self, state: &mut H) {
self.as_ref().hash(state);
}
}
impl From<&'static str> for AttrValue {
#[inline(always)]
fn from(s: &'static str) -> Self {
AttrValue::Static(s)
}
}
impl From<String> for AttrValue {
#[inline(always)]
fn from(s: String) -> Self {
AttrValue::Rc(Rc::from(s))
}
}
impl From<Rc<str>> for AttrValue {
#[inline(always)]
fn from(s: Rc<str>) -> Self {
AttrValue::Rc(s)
}
}
impl From<Cow<'static, str>> for AttrValue {
#[inline(always)]
fn from(s: Cow<'static, str>) -> Self {
match s {
Cow::Borrowed(s) => s.into(),
Cow::Owned(s) => s.into(),
}
}
}
impl Clone for AttrValue {
fn clone(&self) -> Self {
match self {
AttrValue::Static(s) => AttrValue::Static(s),
AttrValue::Rc(s) => AttrValue::Rc(Rc::clone(s)),
}
}
}
impl AsRef<str> for AttrValue {
#[inline(always)]
fn as_ref(&self) -> &str {
&*self
}
}
impl Borrow<str> for AttrValue {
fn borrow(&self) -> &str {
&*self
}
}
impl fmt::Display for AttrValue {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
AttrValue::Static(s) => write!(f, "{}", s),
AttrValue::Rc(s) => write!(f, "{}", s),
}
}
}
impl PartialEq for AttrValue {
#[inline(always)]
fn eq(&self, other: &Self) -> bool {
self.as_ref() == other.as_ref()
}
}
impl Eq for AttrValue {}
impl AttrValue {
/// Consumes the AttrValue and returns the owned String from the AttrValue whenever possible.
/// For AttrValue::Rc the <str> is cloned to String in case there are other Rc or Weak pointers to the
/// same allocation.
pub fn into_string(self) -> String {
match self {
AttrValue::Static(s) => (*s).to_owned(),
AttrValue::Rc(mut rc) => {
if let Some(s) = Rc::get_mut(&mut rc) {
(*s).to_owned()
} else {
rc.to_string()
}
}
}
}
}
#[cfg(test)]
mod tests_attr_value {
use super::*;
#[test]
fn test_into_string() {
let av = AttrValue::Static("str");
assert_eq!(av.into_string(), "str");
let av = AttrValue::Rc("Rc<str>".into());
assert_eq!(av.into_string(), "Rc<str>");
}
#[test]
fn test_from_string() {
let av = AttrValue::from("str");
assert_eq!(av.into_string(), "str");
let av = AttrValue::from("String".to_string());
assert_eq!(av.into_string(), "String");
let av = AttrValue::from(Cow::from("BorrowedCow"));
assert_eq!(av.into_string(), "BorrowedCow");
}
#[test]
fn test_equality() {
// construct 3 AttrValue with same embedded value; expectation is that all are equal
let a = AttrValue::Static("same");
let b = AttrValue::Rc("same".into());
assert_eq!(a, b);
assert_eq!(a, b);
}
}
#[cfg(any(feature = "ssr", feature = "hydration"))]
mod feat_ssr_hydration {
/// A collectable.
///
/// This indicates a kind that can be collected from fragment to be processed at a later time
pub(crate) enum Collectable {
#[cfg(debug_assertions)]
Component(&'static str),
#[cfg(not(debug_assertions))]
Component,
Suspense,
}
impl Collectable {
pub fn open_start_mark(&self) -> &'static str {
match self {
#[cfg(debug_assertions)]
Self::Component(_) => "<[",
#[cfg(not(debug_assertions))]
Self::Component => "<[",
Self::Suspense => "<?",
}
}
pub fn close_start_mark(&self) -> &'static str {
match self {
#[cfg(debug_assertions)]
Self::Component(_) => "</[",
#[cfg(not(debug_assertions))]
Self::Component => "</[",
Self::Suspense => "</?",
}
}
pub fn end_mark(&self) -> &'static str {
match self {
#[cfg(debug_assertions)]
Self::Component(_) => "]>",
#[cfg(not(debug_assertions))]
Self::Component => "]>",
Self::Suspense => ">",
}
}
#[cfg(feature = "ssr")]
pub fn write_open_tag(&self, w: &mut String) {
w.push_str("<!--");
w.push_str(self.open_start_mark());
#[cfg(debug_assertions)]
match self {
Self::Component(type_name) => w.push_str(type_name),
Self::Suspense => {}
}
w.push_str(self.end_mark());
w.push_str("-->");
}
#[cfg(feature = "ssr")]
pub fn write_close_tag(&self, w: &mut String) {
w.push_str("<!--");
w.push_str(self.close_start_mark());
#[cfg(debug_assertions)]
match self {
Self::Component(type_name) => w.push_str(type_name),
Self::Suspense => {}
}
w.push_str(self.end_mark());
w.push_str("-->");
}
#[cfg(feature = "hydration")]
pub fn name(&self) -> super::Cow<'static, str> {
match self {
#[cfg(debug_assertions)]
Self::Component(m) => format!("Component({})", m).into(),
#[cfg(not(debug_assertions))]
Self::Component => "Component".into(),
Self::Suspense => "Suspense".into(),
}
}
}
}
#[cfg(any(feature = "ssr", feature = "hydration"))]
pub(crate) use feat_ssr_hydration::*;
/// A collection of attributes for an element
#[derive(PartialEq, Eq, Clone, Debug)]
pub enum Attributes {
/// Static list of attributes.
///
/// Allows optimizing comparison to a simple pointer equality check and reducing allocations,
/// if the attributes do not change on a node.
Static(&'static [[&'static str; 2]]),
/// Static list of attribute keys with possibility to exclude attributes and dynamic attribute
/// values.
///
/// Allows optimizing comparison to a simple pointer equality check and reducing allocations,
/// if the attributes keys do not change on a node.
Dynamic {
/// Attribute keys. Includes both always set and optional attribute keys.
keys: &'static [&'static str],
/// Attribute values. Matches [keys](Attributes::Dynamic::keys). Optional attributes are designated by setting [None].
values: Box<[Option<AttrValue>]>,
},
/// IndexMap is used to provide runtime attribute deduplication in cases where the html! macro
/// was not used to guarantee it.
IndexMap(IndexMap<AttrValue, AttrValue>),
}
impl Attributes {
/// Construct a default Attributes instance
pub fn new() -> Self {
Self::default()
}
/// Return iterator over attribute key-value pairs.
/// This function is suboptimal and does not inline well. Avoid on hot paths.
pub fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = (&'a str, &'a str)> + 'a> {
match self {
Self::Static(arr) => Box::new(arr.iter().map(|kv| (kv[0], kv[1] as &'a str))),
Self::Dynamic { keys, values } => Box::new(
keys.iter()
.zip(values.iter())
.filter_map(|(k, v)| v.as_ref().map(|v| (*k, v.as_ref()))),
),
Self::IndexMap(m) => Box::new(m.iter().map(|(k, v)| (k.as_ref(), v.as_ref()))),
}
}
/// Get a mutable reference to the underlying `IndexMap`.
/// If the attributes are stored in the `Vec` variant, it will be converted.
pub fn get_mut_index_map(&mut self) -> &mut IndexMap<AttrValue, AttrValue> {
macro_rules! unpack {
() => {
match self {
Self::IndexMap(m) => m,
// SAFETY: unreachable because we set self to the `IndexMap` variant above.
_ => unsafe { unreachable_unchecked() },
}
};
}
match self {
Self::IndexMap(m) => m,
Self::Static(arr) => {
*self = Self::IndexMap(arr.iter().map(|kv| (kv[0].into(), kv[1].into())).collect());
unpack!()
}
Self::Dynamic { keys, values } => {
*self = Self::IndexMap(
std::mem::take(values)
.iter_mut()
.zip(keys.iter())
.filter_map(|(v, k)| v.take().map(|v| (AttrValue::from(*k), v)))
.collect(),
);
unpack!()
}
}
}
}
impl From<IndexMap<AttrValue, AttrValue>> for Attributes {
fn from(v: IndexMap<AttrValue, AttrValue>) -> Self {
Self::IndexMap(v)
}
}
impl From<IndexMap<&'static str, AttrValue>> for Attributes {
fn from(v: IndexMap<&'static str, AttrValue>) -> Self {
let v = v
.into_iter()
.map(|(k, v)| (AttrValue::Static(k), v))
.collect();
Self::IndexMap(v)
}
}
impl Default for Attributes {
fn default() -> Self {
Self::Static(&[])
}
}