forked from yewstack/yew
-
Notifications
You must be signed in to change notification settings - Fork 0
/
attributes.rs
316 lines (284 loc) · 10 KB
/
attributes.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
use std::collections::HashMap;
use std::ops::Deref;
use indexmap::IndexMap;
use wasm_bindgen::JsValue;
use web_sys::{Element, HtmlInputElement as InputElement, HtmlTextAreaElement as TextAreaElement};
use yew::AttrValue;
use super::Apply;
use crate::dom_bundle::BSubtree;
use crate::virtual_dom::vtag::{InputFields, Value};
use crate::virtual_dom::Attributes;
impl<T: AccessValue> Apply for Value<T> {
type Bundle = Self;
type Element = T;
fn apply(self, _root: &BSubtree, el: &Self::Element) -> Self {
if let Some(v) = self.deref() {
el.set_value(v);
}
self
}
fn apply_diff(self, _root: &BSubtree, el: &Self::Element, bundle: &mut Self) {
match (self.deref(), (*bundle).deref()) {
(Some(new), Some(_)) => {
// Refresh value from the DOM. It might have changed.
if new.as_ref() != el.value() {
el.set_value(new);
}
}
(Some(new), None) => el.set_value(new),
(None, Some(_)) => el.set_value(""),
(None, None) => (),
}
}
}
macro_rules! impl_access_value {
($( $type:ty )*) => {
$(
impl AccessValue for $type {
#[inline]
fn value(&self) -> String {
<$type>::value(&self)
}
#[inline]
fn set_value(&self, v: &str) {
<$type>::set_value(&self, v)
}
}
)*
};
}
impl_access_value! {InputElement TextAreaElement}
/// Able to have its value read or set
pub(super) trait AccessValue {
fn value(&self) -> String;
fn set_value(&self, v: &str);
}
impl Apply for InputFields {
type Bundle = Self;
type Element = InputElement;
fn apply(mut self, root: &BSubtree, el: &Self::Element) -> Self {
// IMPORTANT! This parameter has to be set every time
// to prevent strange behaviour in the browser when the DOM changes
el.set_checked(self.checked);
self.value = self.value.apply(root, el);
self
}
fn apply_diff(self, root: &BSubtree, el: &Self::Element, bundle: &mut Self) {
// IMPORTANT! This parameter has to be set every time
// to prevent strange behaviour in the browser when the DOM changes
el.set_checked(self.checked);
self.value.apply_diff(root, el, &mut bundle.value);
}
}
impl Attributes {
#[cold]
fn apply_diff_index_maps(
el: &Element,
new: &IndexMap<AttrValue, AttrValue>,
old: &IndexMap<AttrValue, AttrValue>,
) {
for (key, value) in new.iter() {
match old.get(key) {
Some(old_value) => {
if value != old_value {
Self::set_attribute(el, key, value);
}
}
None => Self::set_attribute(el, key, value),
}
}
for (key, _value) in old.iter() {
if !new.contains_key(key) {
Self::remove_attribute(el, key);
}
}
}
/// 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(src: &Attributes) -> HashMap<&str, &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.as_ref(), 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) {
match key {
// need to be attributes because, otherwise query selectors fail
"class" | "id" => el.set_attribute(key, value).expect("invalid attribute key"),
_ => {
let key = JsValue::from_str(key);
let value = JsValue::from_str(value);
js_sys::Reflect::set(el.as_ref(), &key, &value).expect("invalid attribute key");
}
}
}
fn remove_attribute(el: &Element, key: &str) {
match key {
// need to be attributes because, otherwise query selectors fail
"class" | "id" => el
.remove_attribute(key)
.expect("could not remove attribute"),
_ => {
let key = JsValue::from_str(key);
js_sys::Reflect::set(el.as_ref(), &key, &JsValue::UNDEFINED)
.expect("could not remove attribute");
}
}
}
}
impl Apply for Attributes {
type Bundle = Self;
type Element = Element;
fn apply(self, _root: &BSubtree, el: &Element) -> Self {
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)
}
}
}
self
}
fn apply_diff(self, _root: &BSubtree, el: &Element, bundle: &mut Self) {
#[inline]
fn ptr_eq<T>(a: &[T], b: &[T]) -> bool {
std::ptr::eq(a, b)
}
let ancestor = std::mem::replace(bundle, self);
let bundle = &*bundle; // reborrow it immutably from here
match (bundle, 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_eq!(new_k.len(), new_v.len());
assert_eq!(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(ref old)) => {
Self::apply_diff_index_maps(el, &*new, &*old);
}
// Cold path. Happens only with conditional swapping and reordering of `VTag`s with the
// same tag and no keys.
(new, ref ancestor) => {
Self::apply_diff_as_maps(el, new, ancestor);
}
}
}
}
#[cfg(target_arch = "wasm32")]
#[cfg(test)]
mod tests {
use super::*;
use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure};
use gloo::utils::document;
use js_sys::Reflect;
wasm_bindgen_test_configure!(run_in_browser);
fn create_element() -> (Element, BSubtree) {
let element = document().create_element("a").expect("failed to create element");
let btree = BSubtree::create_root(&element);
(element, btree)
}
#[test]
fn properties_are_set() {
let attrs = Attributes::Static(&[
["href", "https://example.com/"],
["alt", "somewhere"],
]);
let (element, btree) = create_element();
attrs.apply(&btree, &element);
assert_eq!(
Reflect::get(element.as_ref(), &JsValue::from_str("href")).expect("no href").as_string().expect("not a string"),
"https://example.com/",
"property `href` not set properly"
);
assert_eq!(
Reflect::get(element.as_ref(), &JsValue::from_str("alt")).expect("no alt").as_string().expect("not a string"),
"somewhere",
"property `alt` not set properly"
);
}
#[test]
fn class_id_are_attrs() {
let attrs = Attributes::Static(&[
["id", "foo"],
["class", "thing"],
]);
let (element, btree) = create_element();
attrs.apply(&btree, &element);
assert_eq!(element.get_attribute("id").unwrap(), "foo");
assert_eq!(element.get_attribute("class").unwrap(), "thing");
}
}