This is unreleased documentation for Yew Next version.
For up-to-date documentation, see the latest version on docs.rs.

yew/utils/
mod.rs

1//! This module contains useful utilities to get information about the current document.
2
3use std::marker::PhantomData;
4
5use yew::html::ChildrenRenderer;
6
7/// Map `IntoIterator<Item = Into<T>>` to `Iterator<Item = T>`
8pub fn into_node_iter<IT, T, R>(it: IT) -> impl Iterator<Item = R>
9where
10    IT: IntoIterator<Item = T>,
11    T: Into<R>,
12{
13    it.into_iter().map(|n| n.into())
14}
15
16/// A special type necessary for flattening components returned from nested html macros.
17#[derive(Debug)]
18pub struct NodeSeq<IN, OUT>(Vec<OUT>, PhantomData<IN>);
19
20impl<IN: Into<OUT>, OUT> From<IN> for NodeSeq<IN, OUT> {
21    fn from(val: IN) -> Self {
22        Self(vec![val.into()], PhantomData)
23    }
24}
25
26impl<IN: Into<OUT>, OUT> From<Option<IN>> for NodeSeq<IN, OUT> {
27    fn from(val: Option<IN>) -> Self {
28        Self(val.map(|s| vec![s.into()]).unwrap_or_default(), PhantomData)
29    }
30}
31
32impl<IN: Into<OUT>, OUT> From<Vec<IN>> for NodeSeq<IN, OUT> {
33    fn from(val: Vec<IN>) -> Self {
34        Self(val.into_iter().map(|x| x.into()).collect(), PhantomData)
35    }
36}
37
38impl<IN: Into<OUT> + Clone, OUT> From<&ChildrenRenderer<IN>> for NodeSeq<IN, OUT> {
39    fn from(val: &ChildrenRenderer<IN>) -> Self {
40        Self(val.iter().map(|x| x.into()).collect(), PhantomData)
41    }
42}
43
44impl<IN, OUT> IntoIterator for NodeSeq<IN, OUT> {
45    type IntoIter = std::vec::IntoIter<Self::Item>;
46    type Item = OUT;
47
48    fn into_iter(self) -> Self::IntoIter {
49        self.0.into_iter()
50    }
51}
52
53/// Hack to force type mismatch compile errors in yew-macro.
54// TODO: replace with `compile_error!`, when `type_name_of_val` is stabilised (https://github.com/rust-lang/rust/issues/66359).
55#[doc(hidden)]
56pub fn __ensure_type<T>(_: T) {}
57
58/// Print the [web_sys::Node]'s contents as a string for debugging purposes
59pub fn print_node(n: &web_sys::Node) -> String {
60    use wasm_bindgen::JsCast;
61
62    match n.dyn_ref::<web_sys::Element>() {
63        Some(el) => el.outer_html(),
64        None => n.text_content().unwrap_or_default(),
65    }
66}
67
68// NOTE: replace this by Rc::unwrap_or_clone() when it becomes stable
69pub(crate) trait RcExt<T: Clone> {
70    fn unwrap_or_clone(this: Self) -> T;
71}
72
73impl<T: Clone> RcExt<T> for std::rc::Rc<T> {
74    fn unwrap_or_clone(this: Self) -> T {
75        std::rc::Rc::try_unwrap(this).unwrap_or_else(|rc| (*rc).clone())
76    }
77}