yew/virtual_dom/vtag.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
//! This module contains the implementation of a virtual element node [VTag].
use std::cmp::PartialEq;
use std::marker::PhantomData;
use std::mem;
use std::ops::{Deref, DerefMut};
use std::rc::Rc;
use wasm_bindgen::JsValue;
use web_sys::{HtmlInputElement as InputElement, HtmlTextAreaElement as TextAreaElement};
use super::{AttrValue, AttributeOrProperty, Attributes, Key, Listener, Listeners, VNode};
use crate::html::{ImplicitClone, IntoPropValue, NodeRef};
/// SVG namespace string used for creating svg elements
pub const SVG_NAMESPACE: &str = "http://www.w3.org/2000/svg";
/// MathML namespace string used for creating MathML elements
pub const MATHML_NAMESPACE: &str = "http://www.w3.org/1998/Math/MathML";
/// Default namespace for html elements
pub const HTML_NAMESPACE: &str = "http://www.w3.org/1999/xhtml";
/// Value field corresponding to an [Element]'s `value` property
#[derive(Debug, Eq, PartialEq)]
pub(crate) struct Value<T>(Option<AttrValue>, PhantomData<T>);
impl<T> Clone for Value<T> {
fn clone(&self) -> Self {
Self::new(self.0.clone())
}
}
impl<T> ImplicitClone for Value<T> {}
impl<T> Default for Value<T> {
fn default() -> Self {
Self::new(None)
}
}
impl<T> Value<T> {
/// Create a new value. The caller should take care that the value is valid for the element's
/// `value` property
fn new(value: Option<AttrValue>) -> Self {
Value(value, PhantomData)
}
/// Set a new value. The caller should take care that the value is valid for the element's
/// `value` property
fn set(&mut self, value: Option<AttrValue>) {
self.0 = value;
}
}
impl<T> Deref for Value<T> {
type Target = Option<AttrValue>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
/// Fields specific to
/// [InputElement](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) [VTag](crate::virtual_dom::VTag)s
#[derive(Debug, Clone, Default, Eq, PartialEq)]
pub(crate) struct InputFields {
/// Contains a value of an
/// [InputElement](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input).
pub(crate) value: Value<InputElement>,
/// Represents `checked` attribute of
/// [input](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-checked).
/// It exists to override standard behavior of `checked` attribute, because
/// in original HTML it sets `defaultChecked` value of `InputElement`, but for reactive
/// frameworks it's more useful to control `checked` value of an `InputElement`.
pub(crate) checked: Option<bool>,
}
impl ImplicitClone for InputFields {}
impl Deref for InputFields {
type Target = Value<InputElement>;
fn deref(&self) -> &Self::Target {
&self.value
}
}
impl DerefMut for InputFields {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.value
}
}
impl InputFields {
/// Crate new attributes for an [InputElement] element
fn new(value: Option<AttrValue>, checked: Option<bool>) -> Self {
Self {
value: Value::new(value),
checked,
}
}
}
/// [VTag] fields that are specific to different [VTag] kinds.
/// Decreases the memory footprint of [VTag] by avoiding impossible field and value combinations.
#[derive(Debug, Clone)]
pub(crate) enum VTagInner {
/// Fields specific to
/// [InputElement](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input)
/// [VTag]s
Input(InputFields),
/// Fields specific to
/// [TextArea](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea)
/// [VTag]s
Textarea {
/// Contains a value of an
/// [TextArea](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea)
value: Value<TextAreaElement>,
},
/// Fields for all other kinds of [VTag]s
Other {
/// A tag of the element.
tag: AttrValue,
/// children of the element.
children: VNode,
},
}
impl ImplicitClone for VTagInner {}
/// A type for a virtual
/// [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element)
/// representation.
#[derive(Debug, Clone)]
pub struct VTag {
/// [VTag] fields that are specific to different [VTag] kinds.
pub(crate) inner: VTagInner,
/// List of attached listeners.
pub(crate) listeners: Listeners,
/// A node reference used for DOM access in Component lifecycle methods
pub node_ref: NodeRef,
/// List of attributes.
pub attributes: Attributes,
pub key: Option<Key>,
}
impl ImplicitClone for VTag {}
impl VTag {
/// Creates a new [VTag] instance with `tag` name (cannot be changed later in DOM).
pub fn new(tag: impl Into<AttrValue>) -> Self {
let tag = tag.into();
Self::new_base(
match &*tag.to_ascii_lowercase() {
"input" => VTagInner::Input(Default::default()),
"textarea" => VTagInner::Textarea {
value: Default::default(),
},
_ => VTagInner::Other {
tag,
children: Default::default(),
},
},
Default::default(),
Default::default(),
Default::default(),
Default::default(),
)
}
/// Creates a new
/// [InputElement](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) [VTag]
/// instance.
///
/// Unlike [VTag::new()], this sets all the public fields of [VTag] in one call. This allows the
/// compiler to inline property and child list construction in the `html!` macro. This enables
/// higher instruction parallelism by reducing data dependency and avoids `memcpy` of Vtag
/// fields.
#[doc(hidden)]
#[allow(clippy::too_many_arguments)]
pub fn __new_input(
value: Option<AttrValue>,
checked: Option<bool>,
node_ref: NodeRef,
key: Option<Key>,
// at bottom for more readable macro-expanded coded
attributes: Attributes,
listeners: Listeners,
) -> Self {
VTag::new_base(
VTagInner::Input(InputFields::new(
value,
// In HTML node `checked` attribute sets `defaultChecked` parameter,
// but we use own field to control real `checked` parameter
checked,
)),
node_ref,
key,
attributes,
listeners,
)
}
/// Creates a new
/// [TextArea](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea) [VTag]
/// instance.
///
/// Unlike [VTag::new()], this sets all the public fields of [VTag] in one call. This allows the
/// compiler to inline property and child list construction in the `html!` macro. This enables
/// higher instruction parallelism by reducing data dependency and avoids `memcpy` of Vtag
/// fields.
#[doc(hidden)]
#[allow(clippy::too_many_arguments)]
pub fn __new_textarea(
value: Option<AttrValue>,
node_ref: NodeRef,
key: Option<Key>,
// at bottom for more readable macro-expanded coded
attributes: Attributes,
listeners: Listeners,
) -> Self {
VTag::new_base(
VTagInner::Textarea {
value: Value::new(value),
},
node_ref,
key,
attributes,
listeners,
)
}
/// Creates a new [VTag] instance with `tag` name (cannot be changed later in DOM).
///
/// Unlike [VTag::new()], this sets all the public fields of [VTag] in one call. This allows the
/// compiler to inline property and child list construction in the `html!` macro. This enables
/// higher instruction parallelism by reducing data dependency and avoids `memcpy` of Vtag
/// fields.
#[doc(hidden)]
#[allow(clippy::too_many_arguments)]
pub fn __new_other(
tag: AttrValue,
node_ref: NodeRef,
key: Option<Key>,
// at bottom for more readable macro-expanded coded
attributes: Attributes,
listeners: Listeners,
children: VNode,
) -> Self {
VTag::new_base(
VTagInner::Other { tag, children },
node_ref,
key,
attributes,
listeners,
)
}
/// Constructs a [VTag] from [VTagInner] and fields common to all [VTag] kinds
#[inline]
#[allow(clippy::too_many_arguments)]
fn new_base(
inner: VTagInner,
node_ref: NodeRef,
key: Option<Key>,
attributes: Attributes,
listeners: Listeners,
) -> Self {
VTag {
inner,
attributes,
listeners,
node_ref,
key,
}
}
/// Returns tag of an [Element](web_sys::Element). In HTML tags are always uppercase.
pub fn tag(&self) -> &str {
match &self.inner {
VTagInner::Input { .. } => "input",
VTagInner::Textarea { .. } => "textarea",
VTagInner::Other { tag, .. } => tag.as_ref(),
}
}
/// Add [VNode] child.
pub fn add_child(&mut self, child: VNode) {
if let VTagInner::Other { children, .. } = &mut self.inner {
children.to_vlist_mut().add_child(child)
}
}
/// Add multiple [VNode] children.
pub fn add_children(&mut self, children: impl IntoIterator<Item = VNode>) {
if let VTagInner::Other { children: dst, .. } = &mut self.inner {
dst.to_vlist_mut().add_children(children)
}
}
/// Returns a reference to the children of this [VTag], if the node can have
/// children
pub fn children(&self) -> Option<&VNode> {
match &self.inner {
VTagInner::Other { children, .. } => Some(children),
_ => None,
}
}
/// Returns a mutable reference to the children of this [VTag], if the node can have
/// children
pub fn children_mut(&mut self) -> Option<&mut VNode> {
match &mut self.inner {
VTagInner::Other { children, .. } => Some(children),
_ => None,
}
}
/// Returns the children of this [VTag], if the node can have
/// children
pub fn into_children(self) -> Option<VNode> {
match self.inner {
VTagInner::Other { children, .. } => Some(children),
_ => None,
}
}
/// Returns the `value` of an
/// [InputElement](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) or
/// [TextArea](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea)
pub fn value(&self) -> Option<&AttrValue> {
match &self.inner {
VTagInner::Input(f) => f.as_ref(),
VTagInner::Textarea { value } => value.as_ref(),
VTagInner::Other { .. } => None,
}
}
/// Sets `value` for an
/// [InputElement](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) or
/// [TextArea](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea)
pub fn set_value(&mut self, value: impl IntoPropValue<Option<AttrValue>>) {
match &mut self.inner {
VTagInner::Input(f) => {
f.set(value.into_prop_value());
}
VTagInner::Textarea { value: dst } => {
dst.set(value.into_prop_value());
}
VTagInner::Other { .. } => (),
}
}
/// Returns `checked` property of an
/// [InputElement](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input).
/// (Does not affect the value of the node's attribute).
pub fn checked(&self) -> Option<bool> {
match &self.inner {
VTagInner::Input(f) => f.checked,
_ => None,
}
}
/// Sets `checked` property of an
/// [InputElement](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input).
/// (Does not affect the value of the node's attribute).
pub fn set_checked(&mut self, value: bool) {
if let VTagInner::Input(f) = &mut self.inner {
f.checked = Some(value);
}
}
/// Keeps the current value of the `checked` property of an
/// [InputElement](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input).
/// (Does not affect the value of the node's attribute).
pub fn preserve_checked(&mut self) {
if let VTagInner::Input(f) = &mut self.inner {
f.checked = None;
}
}
/// Adds a key-value pair to attributes
///
/// Not every attribute works when it set as an attribute. We use workarounds for:
/// `value` and `checked`.
pub fn add_attribute(&mut self, key: &'static str, value: impl Into<AttrValue>) {
self.attributes.get_mut_index_map().insert(
AttrValue::Static(key),
AttributeOrProperty::Attribute(value.into()),
);
}
/// Set the given key as property on the element
///
/// [`js_sys::Reflect`] is used for setting properties.
pub fn add_property(&mut self, key: &'static str, value: impl Into<JsValue>) {
self.attributes.get_mut_index_map().insert(
AttrValue::Static(key),
AttributeOrProperty::Property(value.into()),
);
}
/// Sets attributes to a virtual node.
///
/// Not every attribute works when it set as an attribute. We use workarounds for:
/// `value` and `checked`.
pub fn set_attributes(&mut self, attrs: impl Into<Attributes>) {
self.attributes = attrs.into();
}
#[doc(hidden)]
pub fn __macro_push_attr(&mut self, key: &'static str, value: impl IntoPropValue<AttrValue>) {
self.attributes.get_mut_index_map().insert(
AttrValue::from(key),
AttributeOrProperty::Attribute(value.into_prop_value()),
);
}
/// Add event listener on the [VTag]'s [Element](web_sys::Element).
/// Returns `true` if the listener has been added, `false` otherwise.
pub fn add_listener(&mut self, listener: Rc<dyn Listener>) -> bool {
match &mut self.listeners {
Listeners::None => {
self.set_listeners([Some(listener)].into());
true
}
Listeners::Pending(listeners) => {
let mut listeners = mem::take(listeners).into_vec();
listeners.push(Some(listener));
self.set_listeners(listeners.into());
true
}
}
}
/// Set event listeners on the [VTag]'s [Element](web_sys::Element)
pub fn set_listeners(&mut self, listeners: Box<[Option<Rc<dyn Listener>>]>) {
self.listeners = Listeners::Pending(listeners);
}
}
impl PartialEq for VTag {
fn eq(&self, other: &VTag) -> bool {
use VTagInner::*;
(match (&self.inner, &other.inner) {
(Input(l), Input(r)) => l == r,
(Textarea { value: value_l }, Textarea { value: value_r }) => value_l == value_r,
(Other { tag: tag_l, .. }, Other { tag: tag_r, .. }) => tag_l == tag_r,
_ => false,
}) && self.listeners.eq(&other.listeners)
&& self.attributes == other.attributes
// Diff children last, as recursion is the most expensive
&& match (&self.inner, &other.inner) {
(Other { children: ch_l, .. }, Other { children: ch_r, .. }) => ch_l == ch_r,
_ => true,
}
}
}
#[cfg(feature = "ssr")]
mod feat_ssr {
use std::fmt::Write;
use super::*;
use crate::feat_ssr::VTagKind;
use crate::html::AnyScope;
use crate::platform::fmt::BufWriter;
use crate::virtual_dom::VText;
// Elements that cannot have any child elements.
static VOID_ELEMENTS: &[&str; 14] = &[
"area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param",
"source", "track", "wbr",
];
impl VTag {
pub(crate) async fn render_into_stream(
&self,
w: &mut BufWriter,
parent_scope: &AnyScope,
hydratable: bool,
) {
let _ = w.write_str("<");
let _ = w.write_str(self.tag());
let write_attr = |w: &mut BufWriter, name: &str, val: Option<&str>| {
let _ = w.write_str(" ");
let _ = w.write_str(name);
if let Some(m) = val {
let _ = w.write_str("=\"");
let _ = w.write_str(&html_escape::encode_double_quoted_attribute(m));
let _ = w.write_str("\"");
}
};
if let VTagInner::Input(_) = self.inner {
if let Some(m) = self.value() {
write_attr(w, "value", Some(m));
}
// Setting is as an attribute sets the `defaultChecked` property. Only emit this
// if it's explicitly set to checked.
if self.checked() == Some(true) {
write_attr(w, "checked", None);
}
}
for (k, v) in self.attributes.iter() {
write_attr(w, k, Some(v));
}
let _ = w.write_str(">");
match self.inner {
VTagInner::Input(_) => {}
VTagInner::Textarea { .. } => {
if let Some(m) = self.value() {
VText::new(m.to_owned())
.render_into_stream(w, parent_scope, hydratable, VTagKind::Other)
.await;
}
let _ = w.write_str("</textarea>");
}
VTagInner::Other {
ref tag,
ref children,
..
} => {
if !VOID_ELEMENTS.contains(&tag.as_ref()) {
children
.render_into_stream(w, parent_scope, hydratable, tag.into())
.await;
let _ = w.write_str("</");
let _ = w.write_str(tag);
let _ = w.write_str(">");
} else {
// We don't write children of void elements nor closing tags.
debug_assert!(
match children {
VNode::VList(m) => m.is_empty(),
_ => false,
},
"{tag} cannot have any children!"
);
}
}
}
}
}
}
#[cfg(any(not(target_arch = "wasm32"), target_os = "wasi"))]
#[cfg(feature = "ssr")]
#[cfg(test)]
mod ssr_tests {
use tokio::test;
use crate::prelude::*;
use crate::LocalServerRenderer as ServerRenderer;
#[cfg_attr(not(target_os = "wasi"), test)]
#[cfg_attr(target_os = "wasi", test(flavor = "current_thread"))]
async fn test_simple_tag() {
#[function_component]
fn Comp() -> Html {
html! { <div></div> }
}
let s = ServerRenderer::<Comp>::new()
.hydratable(false)
.render()
.await;
assert_eq!(s, "<div></div>");
}
#[cfg_attr(not(target_os = "wasi"), test)]
#[cfg_attr(target_os = "wasi", test(flavor = "current_thread"))]
async fn test_simple_tag_with_attr() {
#[function_component]
fn Comp() -> Html {
html! { <div class="abc"></div> }
}
let s = ServerRenderer::<Comp>::new()
.hydratable(false)
.render()
.await;
assert_eq!(s, r#"<div class="abc"></div>"#);
}
#[cfg_attr(not(target_os = "wasi"), test)]
#[cfg_attr(target_os = "wasi", test(flavor = "current_thread"))]
async fn test_simple_tag_with_content() {
#[function_component]
fn Comp() -> Html {
html! { <div>{"Hello!"}</div> }
}
let s = ServerRenderer::<Comp>::new()
.hydratable(false)
.render()
.await;
assert_eq!(s, r#"<div>Hello!</div>"#);
}
#[cfg_attr(not(target_os = "wasi"), test)]
#[cfg_attr(target_os = "wasi", test(flavor = "current_thread"))]
async fn test_simple_tag_with_nested_tag_and_input() {
#[function_component]
fn Comp() -> Html {
html! { <div>{"Hello!"}<input value="abc" type="text" /></div> }
}
let s = ServerRenderer::<Comp>::new()
.hydratable(false)
.render()
.await;
assert_eq!(s, r#"<div>Hello!<input value="abc" type="text"></div>"#);
}
#[cfg_attr(not(target_os = "wasi"), test)]
#[cfg_attr(target_os = "wasi", test(flavor = "current_thread"))]
async fn test_textarea() {
#[function_component]
fn Comp() -> Html {
html! { <textarea value="teststring" /> }
}
let s = ServerRenderer::<Comp>::new()
.hydratable(false)
.render()
.await;
assert_eq!(s, r#"<textarea>teststring</textarea>"#);
}
#[cfg_attr(not(target_os = "wasi"), test)]
#[cfg_attr(target_os = "wasi", test(flavor = "current_thread"))]
async fn test_escaping_in_style_tag() {
#[function_component]
fn Comp() -> Html {
html! { <style>{"body > a {color: #cc0;}"}</style> }
}
let s = ServerRenderer::<Comp>::new()
.hydratable(false)
.render()
.await;
assert_eq!(s, r#"<style>body > a {color: #cc0;}</style>"#);
}
#[cfg_attr(not(target_os = "wasi"), test)]
#[cfg_attr(target_os = "wasi", test(flavor = "current_thread"))]
async fn test_escaping_in_script_tag() {
#[function_component]
fn Comp() -> Html {
html! { <script>{"foo.bar = x < y;"}</script> }
}
let s = ServerRenderer::<Comp>::new()
.hydratable(false)
.render()
.await;
assert_eq!(s, r#"<script>foo.bar = x < y;</script>"#);
}
#[cfg_attr(not(target_os = "wasi"), test)]
#[cfg_attr(target_os = "wasi", test(flavor = "current_thread"))]
async fn test_multiple_vtext_in_style_tag() {
#[function_component]
fn Comp() -> Html {
let one = "html { background: black } ";
let two = "body > a { color: white } ";
html! {
<style>
{one}
{two}
</style>
}
}
let s = ServerRenderer::<Comp>::new()
.hydratable(false)
.render()
.await;
assert_eq!(
s,
r#"<style>html { background: black } body > a { color: white } </style>"#
);
}
}