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

yew/
lib.rs

1#![allow(clippy::needless_doctest_main)]
2#![doc(html_logo_url = "https://yew.rs/img/logo.png")]
3#![cfg_attr(documenting, feature(doc_cfg))]
4#![cfg_attr(nightly_yew, feature(fn_traits, unboxed_closures))]
5
6//! # Yew Framework - API Documentation
7//!
8//! Yew is a modern Rust framework for creating multi-threaded front-end web apps using WebAssembly
9//!
10//! - Features a macro for declaring interactive HTML with Rust expressions. Developers who have
11//!   experience using JSX in React should feel quite at home when using Yew.
12//! - Achieves high performance by minimizing DOM API calls for each page render and by making it
13//!   easy to offload processing to background web workers.
14//! - Supports JavaScript interoperability, allowing developers to leverage NPM packages and
15//!   integrate with existing JavaScript applications.
16//!
17//! ### Supported Targets (Client-Side Rendering)
18//! - `wasm32-unknown-unknown`
19//!
20//! ### Note
21//!
22//! Server-Side Rendering should work on all targets when feature `ssr` is enabled.
23//!
24//! ### Supported Features:
25//! - `csr`: Enables Client-side Rendering support and [`Renderer`]. Only enable this feature if you
26//!   are making a Yew application (not a library).
27//! - `ssr`: Enables Server-side Rendering support and [`ServerRenderer`].
28//! - `hydration`: Enables Hydration support.
29//!
30//! ## Example
31//!
32//! ```rust,no_run
33//! use yew::prelude::*;
34//!
35//! enum Msg {
36//!     AddOne,
37//! }
38//!
39//! struct App {
40//!     value: i64,
41//! }
42//!
43//! impl Component for App {
44//!     type Message = Msg;
45//!     type Properties = ();
46//!
47//!     fn create(ctx: &Context<Self>) -> Self {
48//!         Self { value: 0 }
49//!     }
50//!
51//!     fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool {
52//!         match msg {
53//!             Msg::AddOne => {
54//!                 self.value += 1;
55//!                 true
56//!             }
57//!         }
58//!     }
59//!
60//!     fn view(&self, ctx: &Context<Self>) -> Html {
61//!         html! {
62//!             <div>
63//!                 <button onclick={ctx.link().callback(|_| Msg::AddOne)}>{ "+1" }</button>
64//!                 <p>{ self.value }</p>
65//!             </div>
66//!         }
67//!     }
68//! }
69//!
70//! fn main() {
71//!     yew::Renderer::<App>::new().render();
72//! }
73//! ```
74
75#![deny(
76    missing_docs,
77    missing_debug_implementations,
78    bare_trait_objects,
79    anonymous_parameters,
80    elided_lifetimes_in_paths
81)]
82#![allow(macro_expanded_macro_exports_accessed_by_absolute_paths)]
83#![recursion_limit = "512"]
84extern crate self as yew;
85
86/// This macro provides a convenient way to create [`Classes`].
87///
88/// The macro takes a list of items similar to the [`vec!`] macro and returns a [`Classes`]
89/// instance. Each item can be of any type that implements `Into<Classes>` (See the
90/// implementations on [`Classes`] to learn what types can be used).
91///
92/// # Example
93///
94/// ```
95/// # use yew::prelude::*;
96/// # fn test() {
97/// let conditional_class = Some("my-other-class");
98/// let vec_of_classes = vec![
99///     "one-bean",
100///     "two-beans",
101///     "three-beans",
102///     "a-very-small-casserole",
103/// ];
104///
105/// html! {
106///     <div class={classes!("my-container-class", conditional_class, vec_of_classes)}>
107///         // ...
108///     </div>
109/// };
110/// # }
111/// ```
112pub use yew_macro::classes;
113/// This macro implements JSX-like templates.
114///
115/// This macro always returns [`Html`].
116/// If you need to preserve the type of a component, use the [`html_nested!`] macro instead.
117///
118/// More information about using the `html!` macro can be found in the [Yew Docs]
119///
120/// [`Html`]: ./html/type.Html.html
121/// [`html_nested!`]: ./macro.html_nested.html
122/// [Yew Docs]: https://yew.rs/docs/next/concepts/html
123pub use yew_macro::html;
124/// This macro is similar to [`html!`], but preserves the component type instead
125/// of wrapping it in [`Html`].
126///
127/// That macro is useful when, for example, in a typical implementation of a list
128/// component (let's assume it's called `List`).
129/// In a typical implementation you might find two component types -- `List` and `ListItem`.
130/// Only `ListItem` components are allowed to be children of List`.
131///
132/// You can find an example implementation of this in the [`nested_list`] example.
133/// That example shows, how to create static lists with their children.
134///
135/// ```
136/// # use yew::prelude::*;
137/// use yew::html::ChildrenRenderer;
138/// use yew::virtual_dom::VChild;
139///
140/// #[derive(Clone, Properties, PartialEq)]
141/// struct ListProps {
142///     children: ChildrenRenderer<ListItem>,
143/// }
144///
145/// struct List;
146/// impl Component for List {
147/// #   type Message = ();
148///     type Properties = ListProps;
149///     // ...
150/// #   fn create(ctx: &Context<Self>) -> Self { Self }
151/// #   fn view(&self, ctx: &Context<Self>) -> Html { unimplemented!() }
152/// }
153///
154/// #[derive(Clone, PartialEq)]
155/// struct ListItem;
156/// impl Component for ListItem {
157/// #   type Message = ();
158/// #   type Properties = ();
159///     // ...
160/// #   fn create(ctx: &Context<Self>) -> Self { Self }
161/// #   fn view(&self, ctx: &Context<Self>) -> Html { unimplemented!() }
162/// }
163///
164/// // Required for ChildrenRenderer
165/// impl From<VChild<ListItem>> for ListItem {
166///     fn from(child: VChild<ListItem>) -> Self {
167///         Self
168///     }
169/// }
170///
171/// impl Into<Html> for ListItem {
172///     fn into(self) -> Html {
173///         html! { <self /> }
174///     }
175/// }
176/// // You can use `List` with nested `ListItem` components.
177/// // Using any other kind of element would result in a compile error.
178/// # fn test() -> Html {
179/// html! {
180///   <List>
181///     <ListItem/>
182///     <ListItem/>
183///     <ListItem/>
184///   </List>
185/// }
186/// # }
187/// # fn test_iter() -> Html {
188/// # let some_iter = (0..10);
189/// // In many cases you might want to create the content dynamically.
190/// // To do this, you can use the following code:
191/// html! {
192///   <List>
193///     { for some_iter.map(|_| html_nested!{ <ListItem/> }) }
194///   </List>
195/// }
196/// # }
197/// ```
198///
199/// If you used the [`html!`] macro instead of `html_nested!`, the code would
200/// not compile because we explicitly indicated to the compiler that `List`
201/// can only contain elements of type `ListItem` using [`ChildrenRenderer<ListItem>`],
202/// while [`html!`] creates items of type [`Html`].
203///
204///
205/// [`html!`]: ./macro.html.html
206/// [`Html`]: ./html/type.Html.html
207/// [`nested_list`]: https://github.com/yewstack/yew/tree/master/examples/nested_list
208/// [`ChildrenRenderer<ListItem>`]: ./html/struct.ChildrenRenderer.html
209pub use yew_macro::html_nested;
210/// Build [`Properties`] outside of the [`html!`] macro.
211///
212/// It's already possible to create properties like normal Rust structs
213/// but if there are lots of optional props the end result is often needlessly verbose.
214/// This macro allows you to build properties the same way the [`html!`] macro does.
215///
216/// The macro doesn't support special props like `ref` and `key`, they need to be set in the
217/// [`html!`] macro.
218///
219/// You can read more about `Properties` in the [Yew Docs].
220///
221/// # Example
222///
223/// ```
224/// # use yew::prelude::*;
225/// use std::borrow::Cow;
226///
227/// #[derive(Clone, Properties, PartialEq)]
228/// struct Props {
229///     #[prop_or_default]
230///     id: usize,
231///     name: Cow<'static, str>,
232/// }
233///
234/// struct MyComponent(Props);
235/// impl Component for MyComponent {
236/// #   type Message = ();
237///     type Properties = Props;
238///     // ...
239/// #   fn create(ctx: &Context<Self>) -> Self { unimplemented!() }
240/// #   fn view(&self, ctx: &Context<Self>) -> Html { unimplemented!() }
241/// }
242///
243/// # fn foo() -> Html {
244/// // You can build props directly ...
245/// let props = yew::props!(Props {
246///     name: Cow::from("Minka")
247/// });
248/// # assert_eq!(props.name, "Minka");
249/// // ... or build the associated properties of a component
250/// let props = yew::props!(MyComponent::Properties {
251///     id: 2,
252///     name: Cow::from("Lemmy")
253/// });
254/// # assert_eq!(props.id, 2);
255///
256/// // Use the Rust-like struct update syntax to create a component with the props.
257/// html! {
258///     <MyComponent key=1 ..props />
259/// }
260/// # }
261/// ```
262///
263/// [`html!`]: ./macro.html.html
264/// [`Properties`]: ./html/trait.Properties.html
265/// [Yew Docs]: https://yew.rs/concepts/components/properties
266pub use yew_macro::props;
267
268/// This module contains macros which implements html! macro and JSX-like templates
269pub mod macros {
270    pub use crate::{classes, html, html_nested, props};
271}
272
273pub mod callback;
274pub mod context;
275#[cfg(feature = "csr")]
276mod dom_bundle;
277pub mod functional;
278pub mod html;
279pub mod platform;
280pub mod scheduler;
281mod sealed;
282#[cfg(feature = "ssr")]
283mod server_renderer;
284pub mod suspense;
285pub mod utils;
286pub mod virtual_dom;
287#[cfg(feature = "ssr")]
288pub use server_renderer::*;
289
290#[cfg(feature = "csr")]
291mod app_handle;
292#[cfg(feature = "csr")]
293mod renderer;
294
295#[cfg(all(feature = "csr", any(test, feature = "test")))]
296#[allow(missing_docs)]
297pub mod tests;
298
299/// The module that contains all events available in the framework.
300pub mod events {
301    #[doc(no_inline)]
302    pub use web_sys::{
303        AnimationEvent, DragEvent, ErrorEvent, Event, FocusEvent, InputEvent, KeyboardEvent,
304        MouseEvent, PointerEvent, ProgressEvent, SubmitEvent, TouchEvent, TransitionEvent, UiEvent,
305        WheelEvent,
306    };
307
308    #[cfg(feature = "csr")]
309    pub use crate::dom_bundle::set_event_bubbling;
310    pub use crate::html::TargetCast;
311}
312
313#[cfg(feature = "csr")]
314pub use crate::app_handle::AppHandle;
315#[cfg(feature = "csr")]
316pub use crate::renderer::{set_custom_panic_hook, Renderer};
317
318pub mod prelude {
319    //! The Yew Prelude
320    //!
321    //! The purpose of this module is to alleviate imports of many common types:
322    //!
323    //! ```
324    //! # #![allow(unused_imports)]
325    //! use yew::prelude::*;
326    //! ```
327
328    #[cfg(feature = "csr")]
329    pub use crate::app_handle::AppHandle;
330    pub use crate::callback::{Callback, CallbackRef, CallbackRefMut};
331    pub use crate::context::{ContextHandle, ContextProvider};
332    pub use crate::events::*;
333    pub use crate::functional::*;
334    pub use crate::html::{
335        create_portal, BaseComponent, Children, ChildrenWithProps, Classes, Component, Context,
336        Html, HtmlResult, NodeRef, Properties,
337    };
338    pub use crate::macros::{classes, html, html_nested};
339    pub use crate::suspense::Suspense;
340    pub use crate::virtual_dom::AttrValue;
341}
342
343pub use self::prelude::*;