patternfly_yew/hooks/id.rs
1//! Hooks for handling IDs
2
3use crate::prelude::{random_id, Id};
4use yew::prelude::*;
5
6/// Use a random ID
7#[hook]
8pub fn use_random_id() -> UseStateHandle<Id> {
9 use_state_eq(Id::new)
10}
11
12/// Use an ID from properties, or random if none was provided
13///
14/// This value will not change when re-rendering.
15#[hook]
16pub fn use_prop_id<I>(id: I) -> std::rc::Rc<String>
17where
18 I: Into<Option<String>>,
19{
20 use_memo(id.into(), |id| id.clone().unwrap_or_else(random_id))
21}
22
23/// Use an ID from properties, or random if none was provided
24///
25/// This value will not change when re-rendering.
26#[hook]
27pub fn use_id<I>(id: I) -> AttrValue
28where
29 I: Into<Option<AttrValue>>,
30{
31 let s = use_memo(id.into(), |id| {
32 id.clone().unwrap_or_else(|| AttrValue::from(random_id()))
33 });
34 (*s).clone()
35}
36
37/// Use an ID, derived from another one.
38///
39/// It can be used in combination with [`use_id`].
40///
41/// ## Example
42///
43/// ```rust
44/// use yew::prelude::*;
45/// use patternfly_yew::prelude::*;
46///
47/// #[derive(PartialEq, Properties)]
48/// struct Properties {
49/// id: Option<AttrValue>,
50/// }
51///
52/// #[function_component(Example)]
53/// fn component(props: &Properties) -> Html {
54/// let id = use_id(props.id.clone());
55/// let child_id = use_derived_id(&id, |id| format!("{id}-child"));
56///
57/// html!({"..."})
58/// }
59/// ```
60///
61/// This value will not change when re-rendering.
62#[hook]
63pub fn use_derived_id<F>(id: &AttrValue, f: F) -> AttrValue
64where
65 F: FnOnce(&str) -> String,
66{
67 let s = use_memo(id.clone(), |id| AttrValue::from(f(id)));
68 (*s).clone()
69}
70
71/// Use an ID, derived from another one with a suffix.
72///
73/// It can be used in combination with [`use_id`].
74///
75/// ## Example
76///
77/// ```rust
78/// use yew::prelude::*;
79/// use patternfly_yew::prelude::*;
80///
81/// #[derive(PartialEq, Properties)]
82/// struct Properties {
83/// id: Option<AttrValue>,
84/// }
85///
86/// #[function_component(Example)]
87/// fn component(props: &Properties) -> Html {
88/// let id = use_id(props.id.clone());
89/// let child_id = use_suffixed_id(&id, "-child");
90///
91/// html!({"..."})
92/// }
93/// ```
94///
95/// This value will not change when re-rendering.
96#[hook]
97pub fn use_suffixed_id(id: &AttrValue, suffix: &str) -> AttrValue {
98 let s = use_memo(id.clone(), |id| AttrValue::from(id.to_string() + suffix));
99 (*s).clone()
100}