Added dynatos_util::ElementWithTextContent.

This commit is contained in:
Filipe Rodrigues 2024-02-04 00:41:26 +00:00
parent e3d871a672
commit 955b683f37
Signed by: zenithsiz
SSH Key Fingerprint: SHA256:Mb5ppb3Sh7IarBO/sBTXLHbYEOz37hJAlslLQPPAPaU
3 changed files with 35 additions and 0 deletions

1
Cargo.lock generated
View File

@ -54,6 +54,7 @@ name = "dynatos-util"
version = "0.1.0"
dependencies = [
"anyhow",
"duplicate",
"extend",
"js-sys",
"wasm-bindgen",

View File

@ -6,6 +6,7 @@ edition = "2021"
[dependencies]
anyhow = { workspace = true }
duplicate = { workspace = true }
extend = { workspace = true }
js-sys = { workspace = true }
wasm-bindgen = { workspace = true }

View File

@ -61,3 +61,36 @@ pub impl js_sys::Object {
js_sys::Object::define_property(self, &JsValue::from_str(property), &descriptor);
}
}
/// Extension trait to set the text content in a builder-style.
#[extend::ext_sized(name = ElementWithTextContent)]
pub impl web_sys::Element {
fn with_text_content<T>(self, text: T) -> Self
where
T: AsTextContent,
{
self.set_text_content(text.as_text_content());
self
}
}
/// Types that may be used for [`ElementWithTextContent`]
pub trait AsTextContent {
/// Returns the text content
fn as_text_content(&self) -> Option<&str>;
}
// Note: We only add a single impl for `Option<_>` to ensure
// that calling `with_text_content(None)` works without
// specifying any type annotations
#[duplicate::duplicate_item(
Ty body;
[ &'_ str ] [ Some(self) ];
[ String ] [ Some(self.as_str()) ];
[ Option<String> ] [ self.as_deref() ];
)]
impl AsTextContent for Ty {
fn as_text_content(&self) -> Option<&str> {
body
}
}