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 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976
//! Traits and types for building elements.
#[cfg(debug_assertions)]
use std::collections::HashSet;
use std::{
self, fmt,
future::Future,
marker::PhantomData,
pin::{pin, Pin},
};
use discard::DiscardOnDrop;
use futures::StreamExt;
use futures_signals::{
cancelable_future,
signal::{Signal, SignalExt},
signal_vec::{always, SignalVec, SignalVecExt},
CancelableFutureHandle,
};
use silkenweb_base::document;
use silkenweb_signals_ext::value::{Executor, RefSignalOrValue, SignalOrValue, Value};
use wasm_bindgen::{JsCast, JsValue};
use self::child_vec::{ChildVec, ParentUnique};
use super::{ChildNode, Node, Resource};
use crate::{
attribute::Attribute,
clone,
dom::{
private::{DomElement, DomText, EventStore, InstantiableDomElement},
DefaultDom, Dom, Hydro, InDom, InstantiableDom, Template, Wet,
},
empty_str,
hydration::HydrationStats,
intern_str,
node::text,
task,
};
pub(crate) mod child_vec;
/// A generic HTML element.
///
/// Where available, specific DOM elements from [`crate::elements::html`] should
/// be used in preference to this.
///
/// `Mutability` should be one of [`Mut`] or [`Const`].
pub struct GenericElement<D: Dom = DefaultDom, Mutability = Mut> {
static_child_count: usize,
child_vec: Option<Pin<Box<dyn SignalVec<Item = Node<D>>>>>,
resources: Vec<Resource>,
events: EventStore,
element: D::Element,
#[cfg(debug_assertions)]
attributes: HashSet<String>,
phantom: PhantomData<Mutability>,
}
impl<D: Dom> GenericElement<D> {
/// Construct an element with type `tag` in `namespace`.
pub fn new(namespace: &Namespace, tag: &str) -> Self {
Self::from_dom(D::Element::new(namespace, tag), 0)
}
/// Make this element immutable.
pub fn freeze(mut self) -> GenericElement<D, Const> {
self.build();
GenericElement {
static_child_count: self.static_child_count,
child_vec: self.child_vec,
resources: self.resources,
events: self.events,
element: self.element,
#[cfg(debug_assertions)]
attributes: self.attributes,
phantom: PhantomData,
}
}
pub(crate) fn from_dom(element: D::Element, static_child_count: usize) -> Self {
Self {
static_child_count,
child_vec: None,
resources: Vec::new(),
events: EventStore::default(),
element,
#[cfg(debug_assertions)]
attributes: HashSet::new(),
phantom: PhantomData,
}
}
pub(crate) fn store_child(&mut self, mut child: Self) {
child.build();
self.resources.append(&mut child.resources);
self.events.combine(child.events);
}
fn check_attribute_unique(&mut self, name: &str) {
#[cfg(debug_assertions)]
debug_assert!(self.attributes.insert(name.into()));
let _ = name;
}
async fn class_signal<T>(mut element: D::Element, class: impl Signal<Item = T>)
where
T: AsRef<str>,
{
let mut class = pin!(class.to_stream());
if let Some(new_value) = class.next().await {
Self::check_class(&new_value);
element.add_class(intern_str(new_value.as_ref()));
let mut previous_value = new_value;
while let Some(new_value) = class.next().await {
Self::check_class(&new_value);
element.remove_class(previous_value.as_ref());
element.add_class(intern_str(new_value.as_ref()));
previous_value = new_value;
}
}
}
async fn classes_signal<T>(
mut element: D::Element,
classes: impl Signal<Item = impl IntoIterator<Item = T>>,
) where
T: AsRef<str>,
{
let mut classes = pin!(classes.to_stream());
let mut previous_classes: Vec<T> = Vec::new();
while let Some(new_classes) = classes.next().await {
for to_remove in previous_classes.drain(..) {
element.remove_class(to_remove.as_ref());
}
for to_add in new_classes {
Self::check_class(&to_add);
element.add_class(intern_str(to_add.as_ref()));
previous_classes.push(to_add);
}
}
}
fn check_class(name: &impl AsRef<str>) {
assert!(
!name.as_ref().is_empty(),
"Class names must not be empty. Use `.classes` with `Option::None` to unset an optional class."
);
debug_assert!(
!name.as_ref().contains(char::is_whitespace),
"Class names must not contain whitespace."
)
}
}
impl<D: Dom, Mutability> GenericElement<D, Mutability> {
fn build(&mut self) {
if let Some(children) = self.child_vec.take() {
let child_vec =
ChildVec::<D, ParentUnique>::new(self.element.clone(), self.static_child_count);
let handle = child_vec.run(children);
self.resources.push(Resource::Any(Box::new(handle)));
}
}
}
impl<Param, D> GenericElement<Template<Param, D>>
where
Param: 'static,
D: InstantiableDom,
{
pub fn on_instantiate(
mut self,
f: impl 'static + Fn(GenericElement<D>, &Param) -> GenericElement<D>,
) -> Self {
self.element.on_instantiate(f);
self
}
}
impl<D: Dom> ParentElement<D> for GenericElement<D> {
fn text<'a, T>(mut self, child: impl RefSignalOrValue<'a, Item = T>) -> Self
where
T: 'a + AsRef<str> + Into<String>,
{
if self.child_vec.is_some() {
return self.child(child.map(|child| text(child.as_ref())));
}
self.static_child_count += 1;
child.select_spawn(
|parent, child| {
parent
.element
.append_child(&D::Text::new(child.as_ref()).into());
},
|parent, child_signal| {
let mut text_node = D::Text::new(empty_str());
parent.element.append_child(&text_node.clone().into());
child_signal.for_each(move |new_value| {
text_node.set_text(new_value.as_ref());
async {}
})
},
&mut self,
);
self
}
fn optional_child(self, child: impl SignalOrValue<Item = Option<impl ChildNode<D>>>) -> Self {
child.select(
|mut parent, child| {
if let Some(child) = child {
if parent.child_vec.is_some() {
return parent.children_signal(always(vec![child]));
}
parent.static_child_count += 1;
let child = child.into();
parent.element.append_child(&child.node);
parent.resources.append(&mut child.resources.into_vec());
parent.events.combine(child.events);
}
parent
},
|parent, child| {
let child_vec = child
.map(|child| child.into_iter().collect::<Vec<_>>())
.to_signal_vec();
parent.children_signal(child_vec)
},
self,
)
}
fn children<N>(mut self, children: impl IntoIterator<Item = N>) -> Self
where
N: Into<Node<D>>,
{
if self.child_vec.is_some() {
let children = children
.into_iter()
.map(|node| node.into())
.collect::<Vec<_>>();
return self.children_signal(always(children));
}
for child in children {
self = self.child(child.into());
}
self
}
fn children_signal<N>(mut self, children: impl SignalVec<Item = N> + 'static) -> Self
where
N: Into<Node<D>>,
{
let new_children = children.map(|child| child.into());
let boxed_children = if let Some(child_vec) = self.child_vec.take() {
child_vec.chain(new_children).boxed_local()
} else {
new_children.boxed_local()
};
self.child_vec = Some(boxed_children);
self
}
}
impl<Mutability> GenericElement<Wet, Mutability> {
pub(crate) fn dom_element(&self) -> web_sys::Element {
self.element.dom_element()
}
}
impl<Mutability> GenericElement<Hydro, Mutability> {
pub(crate) fn hydrate(
mut self,
element: &web_sys::Element,
tracker: &mut HydrationStats,
) -> GenericElement<Wet, Const> {
self.build();
GenericElement {
static_child_count: self.static_child_count,
child_vec: None,
resources: self.resources,
events: self.events,
element: self.element.hydrate(element, tracker),
#[cfg(debug_assertions)]
attributes: self.attributes,
phantom: PhantomData,
}
}
}
impl<D: InstantiableDom> ShadowRootParent<D> for GenericElement<D> {
fn attach_shadow_children<N>(mut self, children: impl IntoIterator<Item = N> + 'static) -> Self
where
N: Into<Node<D>>,
{
let children: Vec<_> = children
.into_iter()
.map(|child| {
let child = child.into();
let child_node = child.node;
self.resources.append(&mut child.resources.into_vec());
self.events.combine(child.events);
child_node
})
.collect();
self.element.attach_shadow_children(children);
self
}
}
impl<D: Dom> Element for GenericElement<D> {
type Dom = D;
type DomElement = web_sys::Element;
fn class<'a, T>(mut self, class: impl RefSignalOrValue<'a, Item = T>) -> Self
where
T: 'a + AsRef<str>,
{
class.select_spawn(
|elem, class| {
Self::check_class(&class);
elem.element.add_class(intern_str(class.as_ref()))
},
|elem, class| Self::class_signal(elem.element.clone(), class),
&mut self,
);
self
}
fn classes<'a, T, Iter>(mut self, classes: impl RefSignalOrValue<'a, Item = Iter>) -> Self
where
T: 'a + AsRef<str>,
Iter: 'a + IntoIterator<Item = T>,
{
classes.select_spawn(
|elem, classes| {
for class in classes {
Self::check_class(&class);
elem.element.add_class(intern_str(class.as_ref()));
}
},
|elem, classes| Self::classes_signal(elem.element.clone(), classes),
&mut self,
);
self
}
fn attribute<'a>(
mut self,
name: &str,
value: impl RefSignalOrValue<'a, Item = impl Attribute>,
) -> Self {
self.check_attribute_unique(name);
value.select_spawn(
|elem, value| elem.element.attribute(name, value),
|elem, value| {
let name = name.to_owned();
clone!(mut elem.element);
value.for_each(move |new_value| {
element.attribute(&name, new_value);
async {}
})
},
&mut self,
);
self
}
fn style_property<'a>(
mut self,
name: impl Into<String>,
value: impl RefSignalOrValue<'a, Item = impl AsRef<str> + 'a>,
) -> Self {
#[cfg(debug_assertions)]
debug_assert!(!self.attributes.contains("style"));
let name = name.into();
value.select_spawn(
|elem, value| elem.element.style_property(&name, value.as_ref()),
|elem, value| {
clone!(name, mut elem.element);
value.for_each(move |new_value| {
element.style_property(&name, new_value.as_ref());
async {}
})
},
&mut self,
);
self
}
fn effect(mut self, f: impl FnOnce(&Self::DomElement) + 'static) -> Self {
self.element.effect(f);
self
}
fn effect_signal<T>(
self,
sig: impl Signal<Item = T> + 'static,
f: impl Clone + Fn(&Self::DomElement, T) + 'static,
) -> Self
where
T: 'static,
{
clone!(mut self.element);
let future = sig.for_each(move |x| {
clone!(f);
element.effect(move |elem| f(elem, x));
async {}
});
self.spawn_future(future)
}
fn map_element(self, f: impl FnOnce(&Self::DomElement) + 'static) -> Self {
if let Some(element) = self.element.try_dom_element() {
f(&element);
}
self
}
fn map_element_signal<T>(
self,
sig: impl Signal<Item = T> + 'static,
f: impl Clone + Fn(&Self::DomElement, T) + 'static,
) -> Self
where
T: 'static,
{
clone!(mut self.element);
let future = sig.for_each(move |x| {
if let Some(element) = element.try_dom_element() {
f(&element, x);
}
async {}
});
self.spawn_future(future)
}
fn handle(&self) -> ElementHandle<Self::Dom, Self::DomElement> {
ElementHandle(self.element.clone(), PhantomData)
}
fn spawn_future(mut self, future: impl Future<Output = ()> + 'static) -> Self {
self.spawn(future);
self
}
fn on(mut self, name: &'static str, f: impl FnMut(JsValue) + 'static) -> Self {
self.element.on(name, f, &mut self.events);
self
}
}
impl<D: Dom> Executor for GenericElement<D> {
fn spawn(&mut self, future: impl Future<Output = ()> + 'static) {
self.resources
.push(Resource::FutureHandle(spawn_cancelable_future(future)));
}
}
impl<D: Dom, Mutability> Value for GenericElement<D, Mutability> {}
impl<D: Dom, Mutability> InDom for GenericElement<D, Mutability> {
type Dom = D;
}
impl<D: Dom, Mutability> From<GenericElement<D, Mutability>> for Node<D> {
fn from(mut elem: GenericElement<D, Mutability>) -> Self {
elem.build();
Self {
node: elem.element.into(),
resources: elem.resources.into_boxed_slice(),
events: elem.events,
}
}
}
/// Trait alias for elements that can be used as a child
pub trait ChildElement<D: Dom = DefaultDom>:
Into<GenericElement<D, Const>> + Into<Node<D>> + Value + 'static
{
}
impl<D, T> ChildElement<D> for T
where
D: Dom,
T: Into<GenericElement<D, Const>> + Into<Node<D>> + Value + 'static,
{
}
/// An HTML element.
pub trait Element: Sized {
type Dom: Dom;
type DomElement: JsCast + 'static;
/// Add a class to the element.
///
/// This method can be called multiple
/// times to add multiple classes.
///
/// `class` must not be the empty string, or contain whitespace. Use
/// [`Self::classes`] with an `Option` for optional classes.
///
/// Classes must be unique across all
/// invocations of this method and [`Self::classes`], otherwise the results
/// are undefined. Any class signal values, past or present, must be unique
/// w.r.t. other invocations.
///
/// # Panics
///
/// This panics if `class` is the empty string, or contains whitespace.
///
/// # Examples
///
/// Add static class names:
///
/// ```
/// # use html::{div, Div};
/// # use silkenweb::{dom::Dry, prelude::*};
/// let app: Div<Dry> = div().class("my-class").class("my-other-class");
/// assert_eq!(
/// app.freeze().to_string(),
/// r#"<div class="my-class my-other-class"></div>"#
/// );
/// ```
///
/// Add dynamic class names:
///
/// ```
/// # use html::{div, Div};
/// # use silkenweb::{dom::Dry, prelude::*, task::{render_now, scope, server}};
/// # server::block_on(scope(async {
/// let my_class = Mutable::new("my-class");
/// let my_other_class = Mutable::new("my-other-class");
/// let app: Div<Dry> = div()
/// .class(Sig(my_class.signal()))
/// .class(Sig(my_other_class.signal()));
/// let app = app.freeze();
///
/// render_now().await;
/// assert_eq!(
/// app.to_string(),
/// r#"<div class="my-class my-other-class"></div>"#
/// );
///
/// my_other_class.set("my-other-class-updated");
///
/// render_now().await;
/// assert_eq!(
/// app.to_string(),
/// r#"<div class="my-class my-other-class-updated"></div>"#
/// );
/// # }))
/// ```
fn class<'a, T>(self, class: impl RefSignalOrValue<'a, Item = T>) -> Self
where
T: 'a + AsRef<str>;
/// Set the classes on an element
///
/// All `classes` must not contain spaces, or be the empty string. This
/// method can be called multiple times and will add to existing
/// classes.
///
/// Classes must be unique across all invocations of this method and
/// [`Self::class`], otherwise the results are undefined. Any class signal
/// values, past or present, must be unique w.r.t. other invocations.
///
/// # Panics
///
/// Panics if any of the items in `classes` contain whitespace, or are empty
/// strings.
///
/// # Examples
///
/// Add static class names:
///
/// ```
/// # use html::{div, Div};
/// # use silkenweb::{dom::Dry, prelude::*};
/// let app: Div<Dry> = div().classes(["class0", "class1"]);
/// assert_eq!(
/// app.freeze().to_string(),
/// r#"<div class="class0 class1"></div>"#
/// );
/// ```
///
/// Add dynamic class names:
///
/// ```
/// # use html::{div, Div};
/// # use silkenweb::{dom::Dry, prelude::*, task::{render_now, scope, server}};
/// # server::block_on(scope(async {
/// let my_classes = Mutable::new(vec!["class0", "class1"]);
/// let app: Div<Dry> = div().classes(Sig(my_classes.signal_cloned()));
/// let app = app.freeze();
///
/// render_now().await;
/// assert_eq!(app.to_string(), r#"<div class="class0 class1"></div>"#);
///
/// my_classes.set(vec![]);
///
/// render_now().await;
/// assert_eq!(app.to_string(), r#"<div class=""></div>"#);
/// # }))
/// ```
fn classes<'a, T, Iter>(self, classes: impl RefSignalOrValue<'a, Item = Iter>) -> Self
where
T: 'a + AsRef<str>,
Iter: 'a + IntoIterator<Item = T>;
/// Set an attribute
///
/// The attribute can either be a value or a signal. Signals should be
/// wrapped in the [`Sig`] newtype.`Option<impl Attribute>` can be used to
/// add/remove an attribute based on a signal.
///
/// [`Sig`]: crate::value::Sig
fn attribute<'a>(
self,
name: &str,
value: impl RefSignalOrValue<'a, Item = impl Attribute>,
) -> Self;
/// Set an inline style property
///
/// The property can be a value or a signal. Signals should be wrapped in
/// the [`Sig`] newtype.
///
/// [`Sig`]: crate::value::Sig
fn style_property<'a>(
self,
name: impl Into<String>,
value: impl RefSignalOrValue<'a, Item = impl AsRef<str> + 'a>,
) -> Self;
/// Apply an effect after the next render.
///
/// Effects give you access to the underlying DOM element.
///
/// # Example
///
/// Set the focus to an `HTMLInputElement`.
///
/// ```no_run
/// # use web_sys::HtmlInputElement;
/// # use html::{input, Input};
/// # use silkenweb::prelude::*;
/// # let input: Input =
/// input().effect(|elem: &HtmlInputElement| elem.focus().unwrap());
/// ```
fn effect(self, f: impl FnOnce(&Self::DomElement) + 'static) -> Self;
/// Apply an effect after the next render each time a signal yields a new
/// value.
fn effect_signal<T: 'static>(
self,
sig: impl Signal<Item = T> + 'static,
f: impl Fn(&Self::DomElement, T) + Clone + 'static,
) -> Self;
/// Map a function over the element.
fn map_element(self, f: impl FnOnce(&Self::DomElement) + 'static) -> Self;
/// Map a function over the element each time a signal changes.
fn map_element_signal<T: 'static>(
self,
sig: impl Signal<Item = T> + 'static,
f: impl Fn(&Self::DomElement, T) + Clone + 'static,
) -> Self;
/// Get a handle to the element.
///
/// Handles can be cloned and used within click handlers, for example.
///
/// # Example
///
/// ```no_run
/// # use html::{button, div, input, Div};
/// # use silkenweb::prelude::*;
/// let text = Mutable::new("".to_string());
/// let input = input();
/// let input_handle = input.handle();
/// let app: Div = div()
/// .child(input)
/// .child(button().text("Read Input").on_click({
/// clone!(text);
/// move |_, _| text.set(input_handle.dom_element().value())
/// }))
/// .text(Sig(text.signal_cloned()));
/// ```
fn handle(&self) -> ElementHandle<Self::Dom, Self::DomElement>;
/// Spawn a future on the element.
///
/// The future will be dropped when this element is dropped.
fn spawn_future(self, future: impl Future<Output = ()> + 'static) -> Self;
/// Register an event handler.
///
/// `name` is the name of the event. See the [MDN Events] page for a list.
///
/// `f` is the callback when the event fires and will be passed the
/// javascript `Event` object.
///
/// [MDN Events]: https://developer.mozilla.org/en-US/docs/Web/Events
fn on(self, name: &'static str, f: impl FnMut(JsValue) + 'static) -> Self;
}
/// An element that can have children.
pub trait ParentElement<D: Dom = DefaultDom>: Element {
/// Add a text child to this element
///
/// # Example
///
/// Static text:
///
/// ```no_run
/// # use html::{div, Div};
/// # use silkenweb::prelude::*;
/// # let d: Div =
/// div().text("Hello, world!");
/// ```
///
/// Dynamic text:
///
/// ```no_run
/// # use html::{div, Div};
/// # use silkenweb::prelude::*;
/// let text = Mutable::new("Hello, world!");
/// # let d: Div =
/// div().text(Sig(text.signal()));
/// ```
fn text<'a, T>(self, child: impl RefSignalOrValue<'a, Item = T>) -> Self
where
T: 'a + AsRef<str> + Into<String>;
/// Add a child to the element.
///
/// # Example
///
/// Add static children:
///
/// ```no_run
/// # use html::{div, p, Div};
/// # use silkenweb::prelude::*;
/// # let div: Div =
/// div().child(p().text("Hello,")).child(p().text("world!"));
/// ```
///
/// Add a dynamic child:
///
/// ```no_run
/// # use html::{div, Div};
/// # use silkenweb::prelude::*;
/// let text = Mutable::new("Hello, world!");
///
/// # let d: Div =
/// div().child(Sig(text.signal().map(|text| div().text(text))));
/// ```
fn child(self, child: impl SignalOrValue<Item = impl ChildNode<D>>) -> Self {
self.optional_child(child.map(Some))
}
/// Add an optional child to the element.
///
/// The child will update when the signal changes to `Some(..)`, and will be
/// removed when the signal changes to `None`.
///
/// # Example
///
/// Add a static optional child:
///
/// ```no_run
/// # use html::{div, p, Div};
/// # use silkenweb::prelude::*;
/// let text = Mutable::new("hello");
///
/// # let div: Div =
/// div().optional_child(Some(p().text("Hello, world!")));
/// ```
///
/// Add a dynamic optional child:
///
/// ```no_run
/// # use html::{div, Div};
/// # use silkenweb::prelude::*;
/// let text = Mutable::new("hello");
///
/// # let div: Div =
/// div().optional_child(Sig(text.signal().map(|text| {
/// if text.is_empty() {
/// None
/// } else {
/// Some(div().text(text))
/// }
/// })));
/// ```
fn optional_child(self, child: impl SignalOrValue<Item = Option<impl ChildNode<D>>>) -> Self;
/// Add children to the element.
///
/// # Example
///
/// ```no_run
/// # use html::{div, p, Div};
/// # use silkenweb::prelude::*;
/// # let div: Div =
/// div().children([p().text("Hello,"), p().text("world!")]);
/// ```
fn children<N>(self, children: impl IntoIterator<Item = N>) -> Self
where
N: Into<Node<D>>;
/// Add children from a [`SignalVec`] to the element.
///
/// See [counter_list](https://github.com/silkenweb/silkenweb/tree/main/examples/counter-list/src/main.rs)
/// for an example
fn children_signal<N>(self, children: impl SignalVec<Item = N> + 'static) -> Self
where
N: Into<Node<D>>;
}
/// An element that can be a shadow host.
pub trait ShadowRootParent<D: InstantiableDom = DefaultDom>: Element {
/// Attach an open shadow root to `self` and add `children` to it.
///
/// If there's already a shadow root, the `children` are appended to it.
///
/// See [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/Element/attachShadow)
fn attach_shadow_children<N>(self, children: impl IntoIterator<Item = N> + 'static) -> Self
where
N: Into<Node<D>>;
}
impl<D> fmt::Display for GenericElement<D, Const>
where
D: Dom,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.element.fmt(f)
}
}
impl<Param, D> GenericElement<Template<Param, D>, Const>
where
D: InstantiableDom,
Param: 'static,
{
/// Instantiate a template with `param`.
///
/// See [`Template`] for an example.
pub fn instantiate(&self, param: &Param) -> GenericElement<D> {
self.element.instantiate(param)
}
}
fn spawn_cancelable_future(
future: impl Future<Output = ()> + 'static,
) -> DiscardOnDrop<CancelableFutureHandle> {
let (handle, cancelable_future) = cancelable_future(future, || ());
task::spawn_local(cancelable_future);
handle
}
/// A handle to an element in the DOM.
///
/// The handle will only be valid for [`Wet`] DOM elements, so the methods
/// should only be used inside event handlers and effects.
///
/// See [`Element::handle`] for an example.
#[derive(Clone)]
pub struct ElementHandle<D: Dom, DomElement>(D::Element, PhantomData<DomElement>);
impl<D: Dom, DomElement: JsCast + Clone> ElementHandle<D, DomElement> {
/// Get the associated DOM element, if it is a [`Wet`] element.
///
/// If the referenced element is not [`Wet`] or a hydrated [`Hydro`]
/// element, this will return [`None`].
pub fn try_dom_element(&self) -> Option<DomElement> {
self.0
.try_dom_element()
.map(|elem| elem.dyn_into().unwrap())
}
/// Get the associated DOM element, or panic.
///
/// # Panics
///
/// This will panic if [`Self::try_dom_element`] would return [`None`], or
/// `self` was created from an invalid [`ElementHandle::cast`].
pub fn dom_element(&self) -> DomElement {
self.0.dom_element().dyn_into().unwrap()
}
}
impl<D: Dom> ElementHandle<D, web_sys::Element> {
/// Cast the dom type of an [`ElementHandle`].
///
/// It is the clients responsibility to ensure the new type is correct.
pub fn cast<T: JsCast>(self) -> ElementHandle<D, T> {
ElementHandle(self.0, PhantomData)
}
}
/// The namespace of a DOM element.
#[derive(Clone, Eq, PartialEq)]
pub enum Namespace {
/// New elements in the `Html` namespace are created with `create_element`,
/// thus avoiding converting the namespace to a javascript string.
Html,
Svg,
MathML,
Other(String),
}
impl Namespace {
pub(crate) fn create_element(&self, tag: &str) -> web_sys::Element {
match self {
Namespace::Html => document::create_element(tag),
_ => document::create_element_ns(intern_str(self.as_str()), tag),
}
}
pub(crate) fn as_str(&self) -> &str {
match self {
Namespace::Html => "http://www.w3.org/1999/xhtml",
Namespace::Svg => "http://www.w3.org/2000/svg",
Namespace::MathML => "http://www.w3.org/1998/Math/MathML",
Namespace::Other(ns) => ns,
}
}
}
/// Marker type for mutable elements.
pub struct Mut;
/// Marker type for immutable elements.
pub struct Const;