patternfly_yew/components/code_block.rs
1//! Code block
2use yew::prelude::*;
3
4/// Properties for [`CodeBlock`]
5#[derive(Clone, Debug, PartialEq, Properties)]
6pub struct CodeBlockProperties {
7 #[prop_or_default]
8 pub expandable: bool,
9 #[prop_or_default]
10 pub children: Html,
11 #[prop_or_default]
12 pub actions: ChildrenWithProps<CodeBlockAction>,
13}
14
15/// Code Block component
16///
17/// > A **code block** is a component that contains 2 or more lines of read-only code. The code in a code block can be copied to the clipboard.
18///
19/// See: <https://www.patternfly.org/components/code-block>
20///
21/// ## Properties
22///
23/// Defined by [`CodeBlockProperties`].
24///
25/// ## Children
26///
27/// A code block can contain any children, but is expected to contain a [`CodeBlockCode`] component.
28///
29/// It may also be wrapped with a detached [`crate::prelude::ExpandableSection`] component. The
30/// [`crate::prelude::ExpandableSectionToggle`] would then be a child of this component, but stay outside the nested
31/// code component.
32///
33/// ## Example
34///
35/// A simple example would be:
36///
37/// ```rust
38/// use yew::prelude::*;
39/// use patternfly_yew::prelude::*;
40///
41/// #[function_component(Example)]
42/// fn example() -> Html {
43/// html!(
44/// <CodeBlock>
45/// <CodeBlockCode>{r#"some code"#}</CodeBlockCode>
46/// </CodeBlock>
47/// )
48/// }
49/// ```
50#[function_component(CodeBlock)]
51pub fn code_block(props: &CodeBlockProperties) -> Html {
52 html!(
53 <div class="pf-v6-c-code-block">
54 if !props.actions.is_empty() {
55 <div class="pf-v6-c-code-block__header">
56 <div class="pf-v6-c-code-block__actions">{ for props.actions.iter() }</div>
57 </div>
58 }
59 <div
60 class="pf-v6-c-code-block__content"
61 >
62 { props.children.clone() }
63 </div>
64 </div>
65 )
66}
67
68/// Properties for [`CodeBlockCode`]
69#[derive(Clone, Debug, PartialEq, Properties)]
70pub struct CodeBlockCodeProperties {
71 #[prop_or_default]
72 pub children: Html,
73}
74
75/// The actual code component of the Code Block component.
76///
77/// ## Properties
78///
79/// Defined by [`CodeBlockCodeProperties`].
80#[function_component(CodeBlockCode)]
81pub fn code_block_code(props: &CodeBlockCodeProperties) -> Html {
82 html!(
83 <pre class="pf-v6-c-code-block__pre">
84 <code class="pf-v6-c-code-block__code">{ props.children.clone() }</code>
85 </pre>
86 )
87}
88
89/// Properties for [`CodeBlockAction`]
90#[derive(Clone, Debug, PartialEq, Properties)]
91pub struct CodeBlockActionProperties {
92 #[prop_or_default]
93 pub children: Html,
94}
95
96/// An action of a [`CodeBlock`]
97#[function_component(CodeBlockAction)]
98pub fn code_block_action(props: &CodeBlockActionProperties) -> Html {
99 html!(<div class="pf-v6-c-code-block__actions-item">{ props.children.clone() }</div>)
100}