forked from yewstack/yew
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.rs
738 lines (655 loc) · 22.5 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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
//! 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;
use crate::html::{AnyScope, NodeRef};
use indexmap::IndexMap;
use std::borrow::Cow;
use std::{collections::HashMap, fmt, hint::unreachable_unchecked, iter};
use web_sys::{Element, Node};
#[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 std::fmt::Formatter;
use std::ops::Deref;
use std::rc::Rc;
/// Attribute value
#[derive(Debug)]
pub enum AttrValue {
/// String living for `'static`
Static(&'static str),
/// Owned string
Owned(String),
/// Reference counted string
Rc(Rc<str>),
}
impl Deref for AttrValue {
type Target = str;
fn deref(&self) -> &Self::Target {
match self {
AttrValue::Static(s) => *s,
AttrValue::Owned(s) => s.as_str(),
AttrValue::Rc(s) => &*s,
}
}
}
impl From<&'static str> for AttrValue {
fn from(s: &'static str) -> Self {
AttrValue::Static(s)
}
}
impl From<String> for AttrValue {
fn from(s: String) -> Self {
AttrValue::Owned(s)
}
}
impl From<Rc<str>> for AttrValue {
fn from(s: Rc<str>) -> Self {
AttrValue::Rc(s)
}
}
impl From<Cow<'static, str>> for AttrValue {
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::Owned(s) => AttrValue::Owned(s.clone()),
AttrValue::Rc(s) => AttrValue::Rc(Rc::clone(s)),
}
}
}
impl AsRef<str> for AttrValue {
fn as_ref(&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::Owned(s) => write!(f, "{}", s),
AttrValue::Rc(s) => write!(f, "{}", s),
}
}
}
impl PartialEq for AttrValue {
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::Owned(s) => s,
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::Owned("String".to_string());
assert_eq!(av.into_string(), "String");
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");
let av = AttrValue::from(Cow::from("OwnedCow".to_string()));
assert_eq!(av.into_string(), "OwnedCow");
}
#[test]
fn test_equality() {
// construct 3 AttrValue with same embedded value; expectation is that all are equal
let a = AttrValue::Owned("same".to_string());
let b = AttrValue::Static("same");
let c = AttrValue::Rc("same".into());
assert_eq!(a, b);
assert_eq!(b, c);
assert_eq!(a, c);
assert_eq!(a, b);
assert_eq!(b, c);
assert_eq!(a, c);
}
}
/// Applies contained changes to DOM [Element]
trait Apply {
/// [Element] type to apply the changes to
type Element;
/// Apply contained values to [Element] with no ancestor
fn apply(&mut self, el: &Self::Element);
/// Apply diff between [self] and `ancestor` to [Element].
fn apply_diff(&mut self, el: &Self::Element, ancestor: Self);
}
/// 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<&'static str, 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 = (&'static 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, 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<&'static str, 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], 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| (*k, v)))
.collect(),
);
unpack!()
}
}
}
#[cold]
fn apply_diff_index_maps<'a, A, B>(
el: &Element,
// this makes it possible to diff `&'a IndexMap<_, A>` and `IndexMap<_, &'a A>`.
mut new_iter: impl Iterator<Item = (&'static str, &'a str)>,
new: &IndexMap<&'static str, A>,
old: &IndexMap<&'static str, B>,
) where
A: AsRef<str>,
B: AsRef<str>,
{
let mut old_iter = old.iter();
loop {
match (new_iter.next(), old_iter.next()) {
(Some((new_key, new_value)), Some((old_key, old_value))) => {
if new_key != *old_key {
break;
}
if new_value != old_value.as_ref() {
Self::set_attribute(el, new_key, new_value);
}
}
// new attributes
(Some(attr), None) => {
for (key, value) in iter::once(attr).chain(new_iter) {
match old.get(key) {
Some(old_value) => {
if value != old_value.as_ref() {
Self::set_attribute(el, key, value);
}
}
None => {
Self::set_attribute(el, key, value);
}
}
}
break;
}
// removed attributes
(None, Some(attr)) => {
for (key, _) in iter::once(attr).chain(old_iter) {
if !new.contains_key(key) {
Self::remove_attribute(el, key);
}
}
break;
}
(None, None) => break,
}
}
}
/// Convert [Attributes] pair to [HashMap]s and patch changes to `el`.
/// Works with any [Attributes] variants.
#[cold]
fn apply_diff_as_maps<'a>(el: &Element, new: &'a Self, old: &'a Self) {
fn collect<'a>(src: &'a Attributes) -> HashMap<&'static str, &'a str> {
use Attributes::*;
match src {
Static(arr) => (*arr).iter().map(|[k, v]| (*k, *v)).collect(),
Dynamic { keys, values } => keys
.iter()
.zip(values.iter())
.filter_map(|(k, v)| v.as_ref().map(|v| (*k, v.as_ref())))
.collect(),
IndexMap(m) => m.iter().map(|(k, v)| (*k, v.as_ref())).collect(),
}
}
let new = collect(new);
let old = collect(old);
// Update existing or set new
for (k, new) in new.iter() {
if match old.get(k) {
Some(old) => old != new,
None => true,
} {
el.set_attribute(k, new).unwrap();
}
}
// Remove missing
for k in old.keys() {
if !new.contains_key(k) {
Self::remove_attribute(el, k);
}
}
}
fn set_attribute(el: &Element, key: &str, value: &str) {
el.set_attribute(key, value).expect("invalid attribute key")
}
fn remove_attribute(el: &Element, key: &str) {
el.remove_attribute(key)
.expect("could not remove attribute")
}
}
impl Apply for Attributes {
type Element = Element;
fn apply(&mut self, el: &Element) {
match self {
Self::Static(arr) => {
for kv in arr.iter() {
Self::set_attribute(el, kv[0], kv[1]);
}
}
Self::Dynamic { keys, values } => {
for (k, v) in keys.iter().zip(values.iter()) {
if let Some(v) = v {
Self::set_attribute(el, k, v)
}
}
}
Self::IndexMap(m) => {
for (k, v) in m.iter() {
Self::set_attribute(el, k, v)
}
}
}
}
fn apply_diff(&mut self, el: &Element, ancestor: Self) {
#[inline]
fn ptr_eq<T>(a: &[T], b: &[T]) -> bool {
a.as_ptr() == b.as_ptr()
}
match (self, ancestor) {
// Hot path
(Self::Static(new), Self::Static(old)) if ptr_eq(new, old) => (),
// Hot path
(
Self::Dynamic {
keys: new_k,
values: new_v,
},
Self::Dynamic {
keys: old_k,
values: old_v,
},
) if ptr_eq(new_k, old_k) => {
// Double zipping does not optimize well, so use asserts and unsafe instead
assert!(new_k.len() == new_v.len());
assert!(new_k.len() == old_v.len());
for i in 0..new_k.len() {
macro_rules! key {
() => {
unsafe { new_k.get_unchecked(i) }
};
}
macro_rules! set {
($new:expr) => {
Self::set_attribute(el, key!(), $new)
};
}
match unsafe { (new_v.get_unchecked(i), old_v.get_unchecked(i)) } {
(Some(new), Some(old)) => {
if new != old {
set!(new);
}
}
(Some(new), None) => set!(new),
(None, Some(_)) => {
Self::remove_attribute(el, key!());
}
(None, None) => (),
}
}
}
// For VTag's constructed outside the html! macro
(Self::IndexMap(new), Self::IndexMap(old)) => {
let new_iter = new.iter().map(|(k, v)| (*k, v.as_ref()));
Self::apply_diff_index_maps(el, new_iter, new, &old);
}
// Cold path. Happens only with conditional swapping and reordering of `VTag`s with the
// same tag and no keys.
(new, ancestor) => {
Self::apply_diff_as_maps(el, new, &ancestor);
}
}
}
}
impl From<IndexMap<&'static str, AttrValue>> for Attributes {
fn from(v: IndexMap<&'static str, AttrValue>) -> Self {
Self::IndexMap(v)
}
}
impl Default for Attributes {
fn default() -> Self {
Self::Static(&[])
}
}
// TODO(#938): What about implementing `VDiff` for `Element`?
// It would make it possible to include ANY element into the tree.
// `Ace` editor embedding for example?
/// This trait provides features to update a tree by calculating a difference against another tree.
pub(crate) trait VDiff {
/// Remove self from parent.
///
/// Parent to detach is `true` if the parent element will also be detached.
fn detach(&mut self, parent: &Element, parent_to_detach: bool);
/// Move elements from one parent to another parent.
/// This is currently only used by `VSuspense` to preserve component state without detaching
/// (which destroys component state).
/// Prefer `detach` then apply if possible.
fn shift(&self, previous_parent: &Element, next_parent: &Element, next_sibling: NodeRef);
/// Scoped diff apply to other tree.
///
/// Virtual rendering for the node. It uses parent node and existing
/// children (virtual and DOM) to check the difference and apply patches to
/// the actual DOM representation.
///
/// Parameters:
/// - `parent_scope`: the parent `Scope` used for passing messages to the
/// parent `Component`.
/// - `parent`: the parent node in the DOM.
/// - `next_sibling`: the next sibling, used to efficiently find where to
/// put the node.
/// - `ancestor`: the node that this node will be replacing in the DOM. This
/// method will _always_ remove the `ancestor` from the `parent`.
///
/// Returns a reference to the newly inserted element.
///
/// ### Internal Behavior Notice:
///
/// Note that these modify the DOM by modifying the reference that _already_
/// exists on the `ancestor`. If `self.reference` exists (which it
/// _shouldn't_) this method will panic.
///
/// The exception to this is obviously `VRef` which simply uses the inner
/// `Node` directly (always removes the `Node` that exists).
fn apply(
&mut self,
parent_scope: &AnyScope,
parent: &Element,
next_sibling: NodeRef,
ancestor: Option<VNode>,
) -> NodeRef;
}
pub(crate) fn insert_node(node: &Node, parent: &Element, next_sibling: Option<&Node>) {
match next_sibling {
Some(next_sibling) => parent
.insert_before(node, Some(next_sibling))
.expect("failed to insert tag before next sibling"),
None => parent.append_child(node).expect("failed to append child"),
};
}
#[cfg(all(test, feature = "wasm_bench"))]
mod benchmarks {
use super::*;
use wasm_bindgen_test::{wasm_bindgen_test, wasm_bindgen_test_configure};
wasm_bindgen_test_configure!(run_in_browser);
macro_rules! run {
($name:ident => {
$( $old:expr => $new:expr )+
}) => {
// NB: these benchmarks only compare diffing. They do not take into account aspects like
// allocation impact, which is lower for both `Static` and `Dynamic`.
let results = vec![
$(
{
let mut old = $old.clone();
let new = $new.clone();
let el = gloo_utils::document().create_element("div").unwrap();
old.apply(&el);
(
format!("{} -> {}", attr_variant(&old), attr_variant(&new)),
easybench_wasm::bench_env_limit(
2.0,
(NodeCloner(el), new, old),
|(el, mut new, old)| new.apply_diff(&el.0, old),
),
)
},
)+
];
let max_name_len = results.iter().map(|(name, _)| name.len()).max().unwrap_or_default();
wasm_bindgen_test::console_log!(
"{}:{}",
stringify!($name),
results.into_iter().fold(String::new(), |mut acc, (name, res)| {
use std::fmt::Write;
write!(&mut acc, "\n\t\t{:<width$}: ", name, width=max_name_len).unwrap();
if res.ns_per_iter.is_nan() {
acc += "benchmark too slow to produce meaningful results";
} else {
write!(
&mut acc,
"{:>7.4} ns (R²={:.3}, {:>7} iterations in {:>3} samples)",
res.ns_per_iter,
res.goodness_of_fit,
res.iterations,
res.samples,
)
.unwrap();
}
acc
})
);
};
}
#[wasm_bindgen_test]
fn bench_diff_empty() {
let static_ = Attributes::Static(&[]);
let dynamic = Attributes::Dynamic {
keys: &[],
values: Box::new([]),
};
let map = Attributes::IndexMap(Default::default());
run! {
empty => {
static_ => static_
dynamic => dynamic
map => map
static_ => dynamic
static_ => map
dynamic => map
}
}
}
#[wasm_bindgen_test]
fn bench_diff_equal() {
let static_ = Attributes::Static(sample_attrs());
let dynamic = make_dynamic(sample_values());
let map = make_indexed_map(sample_values());
run! {
equal => {
static_ => static_
dynamic => dynamic
map => map
static_ => dynamic
static_ => map
dynamic => map
}
}
}
#[wasm_bindgen_test]
fn bench_diff_change_first() {
let old = sample_values();
let mut new = old.clone();
new[0] = AttrValue::Static("changed");
let dynamic = (make_dynamic(old.clone()), make_dynamic(new.clone()));
let map = (make_indexed_map(old), make_indexed_map(new));
run! {
changed_first => {
dynamic.0 => dynamic.1
map.0 => map.1
dynamic.0 => map.1
}
}
}
fn make_dynamic(values: Vec<AttrValue>) -> Attributes {
Attributes::Dynamic {
keys: sample_keys(),
values: values.into_iter().map(Some).collect(),
}
}
fn make_indexed_map(values: Vec<AttrValue>) -> Attributes {
Attributes::IndexMap(
sample_keys()
.iter()
.copied()
.zip(values.into_iter())
.collect(),
)
}
fn sample_keys() -> &'static [&'static str] {
&[
"oh", "boy", "pipes", "are", "from", "to", "and", "the", "side",
]
}
fn sample_values() -> Vec<AttrValue> {
[
"danny", "the", "the", "calling", "glen", "glen", "down", "mountain", "",
]
.iter()
.map(|v| AttrValue::Static(*v))
.collect()
}
fn sample_attrs() -> &'static [[&'static str; 2]] {
&[
["oh", "danny"],
["boy", "the"],
["pipes", "the"],
["are", "calling"],
["from", "glen"],
["to", "glen"],
["and", "down"],
["the", "mountain"],
["side", ""],
]
}
fn attr_variant(attrs: &Attributes) -> &'static str {
use Attributes::*;
match attrs {
Static(_) => "static",
Dynamic { .. } => "dynamic",
IndexMap(_) => "indexed_map",
}
}
/// Clones the node on [Clone] call
struct NodeCloner(Element);
impl Clone for NodeCloner {
fn clone(&self) -> Self {
use wasm_bindgen::JsCast;
Self(self.0.clone_node().unwrap().dyn_into().unwrap())
}
}
}