slack_messaging/composition_objects/
text.rs

1use super::{MrkdwnText, PlainText};
2use serde::Serialize;
3
4/// [Text object](https://docs.slack.dev/reference/block-kit/composition-objects/text-object)
5/// that can be either plain text or markdown.
6///
7/// Use this enum instead of [`PlainText`] or [`MrkdwnText`] in case of both of them can be used.
8///
9/// On the other hand, use [`PlainText`] instead of this enum incase of only [`PlainText`]
10/// is allowed to use.
11///
12/// ### example to use [`Text`]
13///
14/// * The `text` and `description` field of [`Opt`](crate::composition_objects::Opt)
15///   object in the [`Checkboxes`](crate::blocks::elements::Checkboxes) and [`RadioButtonGroup`](crate::blocks::elements::RadioButtonGroup) element
16/// * The `text` field of [`Section`](crate::blocks::Section) block
17///
18/// ### example to use [`PlainText`]
19///
20/// * The `text` field of [`Button`](crate::blocks::elements::Button) element.
21///
22#[derive(Debug, Clone, Serialize)]
23#[serde(untagged)]
24pub enum Text {
25    Plain(PlainText),
26    Mrkdwn(MrkdwnText),
27}
28
29impl From<PlainText> for Text {
30    fn from(value: PlainText) -> Self {
31        Self::Plain(value)
32    }
33}
34
35impl From<MrkdwnText> for Text {
36    fn from(value: MrkdwnText) -> Self {
37        Self::Mrkdwn(value)
38    }
39}
40
41#[cfg(test)]
42mod tests {
43    use super::*;
44
45    #[test]
46    fn it_is_serialized_without_enum_tag() {
47        let text: Text = PlainText::builder()
48            .text("hello world")
49            .emoji(true)
50            .build()
51            .into();
52
53        let json = serde_json::to_value(text).unwrap();
54
55        let expected = serde_json::json!({
56            "type": "plain_text",
57            "text": "hello world",
58            "emoji": true
59        });
60
61        assert_eq!(json, expected);
62
63        let text: Text = MrkdwnText::builder()
64            .text("hello world")
65            .verbatim(true)
66            .build()
67            .into();
68
69        let json = serde_json::to_value(text).unwrap();
70
71        let expected = serde_json::json!({
72            "type": "mrkdwn",
73            "text": "hello world",
74            "verbatim": true
75        });
76
77        assert_eq!(json, expected);
78    }
79}