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
/// A convenience macro to [`create_element()`](crate::create_element()) for
/// creating HTML element nodes.
///
/// Returns an [`H<HtmlTag>`](crate::props::H) struct that provides
/// auto-completion for HTML attributes and events.
///
/// # Example
///
/// ```
/// # use wasm_react::*;
/// # fn f() -> VNode {
/// h!(div)
/// .attr("id", &"app".into())
/// .build(c![
/// h!(h1).build(c!["Hello World!"])
/// ])
/// # }
///
/// // <div id="app"><h1>Hello World!</h1></div>
///
/// # fn g() -> VNode {
/// h!("web-component")
/// .build(c!["Hello World!"])
/// # }
///
/// // <web-component>Hello World!</web-component>
/// ```
///
/// It is also possible to add an id and/or classes to the element using a terse
/// notation. You can use the same syntax as [`classnames!`](crate::classnames!).
///
/// ```
/// # use wasm_react::*;
/// # fn f() -> VNode {
/// h!(div[#"app"."some-class"."warning"])
/// .build(c!["This is a warning!"])
/// # }
///
/// // <div id="app" class="some-class warning">This is a warning!</div>
/// ```
#[macro_export]
macro_rules! h {
($tag:literal $( [$( #$id:literal )? $( .$( $classnames:tt )+ )?] )?) => {
$crate::props::H::new($crate::props::HtmlTag($tag)) $(
$( .id($id) )?
$( .class_name(&$crate::classnames![.$( $classnames )+]) )?
)?
};
($tag:ident $( [$( #$id:literal )? $( .$( $classnames:tt )+ )?] )?) => {
$crate::props::H::new($crate::props::HtmlTag(stringify!($tag))) $(
$( .id($id) )?
$( .class_name(&$crate::classnames![.$( $classnames )+]) )?
)?
};
}
/// This macro can take various objects to build a [`VNodeList`].
///
/// [`VNodeList`]: crate::VNodeList
///
/// # Example
///
/// ```
/// # use wasm_react::*;
/// #
/// # struct SomeComponent { some_prop: () }
/// # impl Component for SomeComponent {
/// # fn render(&self) -> VNode { VNode::empty() }
/// # }
/// #
/// # fn f(some_prop: (), vec: Vec<&str>, some_bool: bool) -> VNode {
/// h!(div).build(c![
/// "Counter: ", 5,
///
/// SomeComponent {
/// some_prop,
/// }
/// .build(),
///
/// some_bool.then(||
/// h!(p).build(c!["Conditional rendering"]),
/// ),
///
/// h!(h1).build(c!["Hello World"]),
///
/// ..vec.iter()
/// .map(|x| h!(p).build(c![*x])),
/// ])
/// # }
/// ```
#[macro_export]
macro_rules! c {
[@single $list:ident <<] => {};
// Handle iterators
[@single $list:ident << ..$vnode_list:expr $(, $( $tail:tt )* )?] => {
$list.extend($vnode_list);
$crate::c![@single $list << $( $( $tail )* )?];
};
// Handle `Into<VNode>`
[@single $list:ident << $into_vnode:expr $(, $( $tail:tt )* )?] => {
$list.push(&$into_vnode.into());
$crate::c![@single $list << $( $( $tail )* )?];
};
[] => {
$crate::VNodeList::new()
};
[$( $tt:tt )*] => {
{
let mut list = $crate::VNodeList::new();
$crate::c![@single list << $( $tt )*];
list
}
};
}
/// Constructs a [`String`] based on various types that implement
/// [`Classnames`](crate::props::Classnames).
///
/// # Example
///
/// ```
/// # use wasm_react::*;
/// assert_eq!(
/// classnames![."button"."blue"],
/// "button blue ".to_string(),
/// );
///
/// let blue = false;
/// let disabled = true;
///
/// assert_eq!(
/// classnames![."button".blue.disabled],
/// "button disabled ".to_string(),
/// );
///
/// let is_blue = Some("blue");
/// let disabled = "disabled".to_string();
///
/// assert_eq!(
/// classnames![."button".{is_blue}.{&disabled}],
/// "button blue disabled ",
/// );
/// ```
#[macro_export]
macro_rules! classnames {
[@single $result:ident <<] => {};
// Handle string literals
[@single $result:ident << .$str:literal $( $tail:tt )*] => {
$crate::props::Classnames::append_to(&$str, &mut $result);
$crate::classnames![@single $result << $( $tail ) *];
};
// Handle boolean variables
[@single $result:ident << .$bool:ident $( $tail:tt )*] => {
$crate::props::Classnames::append_to(
&$bool.then(|| stringify!($bool)),
&mut $result
);
$crate::classnames![@single $result << $( $tail ) *];
};
// Handle block expressions
[@single $result:ident << .$block:block $( $tail:tt )*] => {
$crate::props::Classnames::append_to(&$block, &mut $result);
$crate::classnames![@single $result << $( $tail ) *];
};
[] => {
String::new()
};
[$( $tt:tt )*] => {
{
let mut result = String::new();
$crate::classnames![@single result << $( $tt )*];
result
}
};
}
/// This macro can be used to expose your [`Component`](crate::Component) for JS
/// consumption via `wasm-bindgen`.
///
/// Requirement is that you implement the [`TryFrom<JsValue, Error = JsValue>`](core::convert::TryFrom)
/// trait on your component and that you do not export anything else that has
/// the same name as your component.
///
/// Therefore, it is only recommended to use this macro if you're writing a
/// library for JS consumption only, or if you're writing a standalone
/// application, since this will pollute the export namespace, which isn't
/// desirable if you're writing a library for Rust consumption only.
///
/// # Example
///
/// Implement [`TryFrom<JsValue, Error = JsValue>`](core::convert::TryFrom) on
/// your component and export it:
///
/// ```
/// # use wasm_react::*;
/// # use wasm_bindgen::prelude::*;
/// # use js_sys::Reflect;
/// #
/// pub struct Counter {
/// counter: i32,
/// }
///
/// impl Component for Counter {
/// # fn render(&self) -> VNode { VNode::empty() }
/// /* ... */
/// }
///
/// impl TryFrom<JsValue> for Counter {
/// type Error = JsValue;
///
/// fn try_from(value: JsValue) -> Result<Self, Self::Error> {
/// let diff = Reflect::get(&value, &"counter".into())?
/// .as_f64()
/// .ok_or(JsError::new("`counter` property not found"))?;
///
/// Ok(Counter { counter: diff as i32 })
/// }
/// }
///
/// export_components! { Counter }
/// ```
///
/// In JS, you can use it like any other component:
///
/// ```js
/// import React from "react";
/// import init, { Counter } from "./path/to/pkg/project.js";
///
/// function SomeOtherJsComponent(props) {
/// return (
/// <div>
/// <Counter counter={0} />
/// </div>
/// );
/// }
/// ```
///
/// You can export multiple components and also rename them:
///
/// ```
/// # use wasm_react::*;
/// # use wasm_bindgen::prelude::*;
/// # pub struct App; pub struct Counter;
/// # impl Component for App { fn render(&self) -> VNode { VNode::empty() } }
/// # impl TryFrom<JsValue> for App {
/// # type Error = JsValue;
/// # fn try_from(_: JsValue) -> Result<Self, Self::Error> { todo!() }
/// # }
/// # impl Component for Counter { fn render(&self) -> VNode { VNode::empty() } }
/// # impl TryFrom<JsValue> for Counter {
/// # type Error = JsValue;
/// # fn try_from(_: JsValue) -> Result<Self, Self::Error> { todo!() }
/// # }
/// export_components! { App as CounterApp, Counter }
/// ```
#[macro_export]
macro_rules! export_components {
{} => {};
{ $Component:ident $( , $( $tail:tt )* )? } => {
$crate::export_components! { $Component as $Component $( , $( $tail )* )? }
};
{ $Component:ty as $Name:ident $( , $( $tail:tt )* )? } => {
$crate::paste! {
#[allow(non_snake_case)]
#[allow(dead_code)]
#[doc(hidden)]
#[wasm_bindgen::prelude::wasm_bindgen(js_name = $Name)]
pub fn [<__WasmReact_Export_ $Name>](
props: wasm_bindgen::JsValue,
) -> Result<wasm_bindgen::JsValue, wasm_bindgen::JsValue>
where
$Component: $crate::Component
+ TryFrom<wasm_bindgen::JsValue, Error = wasm_bindgen::JsValue>,
{
let component = $Component::try_from(props)?;
Ok($crate::Component::render(&component).into())
}
}
$( $crate::export_components! { $( $tail )* } )?
};
}
/// This macro can be used to import JS React components for Rust consumption
/// via `wasm-bindgen`.
///
/// Make sure that the components you import use the same React runtime as
/// specified for `wasm-react`.
///
/// # Example
///
/// Assume the JS components are defined and exported in `/.dummy/myComponents.js`:
///
/// ```js
/// import "https://unpkg.com/react/umd/react.production.min.js";
///
/// export function MyComponent(props) { /* ... */ }
/// export function PublicComponent(props) { /* ... */ }
/// export function RenamedComponent(props) { /* ... */ }
/// ```
///
/// Then you can import them using [`import_components!`]:
///
/// ```
/// # use wasm_react::*;
/// # use wasm_bindgen::prelude::*;
/// import_components! {
/// #[wasm_bindgen(module = "/.dummy/myComponents.js")]
///
/// /// Some doc comment for the imported component.
/// MyComponent,
/// /// This imported component will be made public.
/// pub PublicComponent,
/// /// You can rename imported components.
/// RenamedComponent as pub OtherComponent,
/// }
/// ```
///
/// Now you can include the imported components in your render function:
///
/// ```
/// # use wasm_react::{*, props::*};
/// # use wasm_bindgen::prelude::*;
/// # import_components! { #[wasm_bindgen(inline_js = "")] MyComponent }
/// # struct App;
/// # impl Component for App {
/// fn render(&self) -> VNode {
/// h!(div).build(c![
/// MyComponent::new().attr("prop", &"Hello World!".into())
/// .build(c![])
/// ])
/// }
/// # }
/// ```
#[macro_export]
macro_rules! import_components {
{ #[$from:meta] } => {};
{
#[$from:meta]
$( #[$meta:meta] )*
$vis:vis $Component:ident $( , $( $tail:tt )* )?
} => {
$crate::import_components! {
#[$from]
$( #[$meta] )*
$Component as $vis $Component $( , $( $tail )* )?
}
};
{
#[$from:meta]
$( #[$meta:meta] )*
$Component:ident as $vis:vis $Name:ident $( , $( $tail:tt )* )?
} => {
$crate::paste! {
#[$from]
extern "C" {
#[wasm_bindgen::prelude::wasm_bindgen(js_name = $Component)]
static [<__WASMREACT_IMPORT_ $Name:upper>]: wasm_bindgen::JsValue;
}
$( #[$meta] )*
#[derive(Debug, Clone, Copy)]
$vis struct $Name;
impl $Name {
/// Returns an `H<ImportedComponent>` struct that provides convenience
/// methods for adding props.
pub fn new()
-> $crate::props::H<$crate::props::ImportedComponent<'static>>
{
$crate::props::H::new(
$crate::props::ImportedComponent(
&[<__WASMREACT_IMPORT_ $Name:upper>]
)
)
}
}
}
$( $crate::import_components! { #[$from] $( $tail )* } )?
};
}