slack_messaging/blocks/table/
cell.rs1use crate::blocks::RichText;
2use serde::Serialize;
3
4#[derive(Debug, Clone, Serialize, PartialEq)]
6#[serde(untagged)]
7pub enum TableCell {
8 RawText(RawText),
10
11 RichText(RichText),
13}
14
15impl<T: Into<String>> From<T> for TableCell {
16 fn from(value: T) -> Self {
17 Self::RawText(RawText::from(value))
18 }
19}
20
21impl From<RawText> for TableCell {
22 fn from(value: RawText) -> Self {
23 Self::RawText(value)
24 }
25}
26
27impl From<RichText> for TableCell {
28 fn from(value: RichText) -> Self {
29 Self::RichText(value)
30 }
31}
32
33#[derive(Debug, Clone, PartialEq)]
36pub struct RawText(String);
37
38impl RawText {
39 pub fn new<T: Into<String>>(text: T) -> Self {
40 Self(text.into())
41 }
42}
43
44impl<T: Into<String>> From<T> for RawText {
45 fn from(value: T) -> Self {
46 Self::new(value)
47 }
48}
49
50impl Serialize for RawText {
51 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
52 where
53 S: serde::Serializer
54 {
55 use serde::ser::SerializeStruct;
56
57 let mut state = serializer.serialize_struct("RawText", 2)?;
58 state.serialize_field("type", "raw_text")?;
59 state.serialize_field("text", &self.0)?;
60 state.end()
61 }
62}
63
64#[cfg(test)]
65mod tests {
66 use super::*;
67 use crate::blocks::rich_text::{RichTextSection, types::RichTextElementLink};
68
69 #[test]
70 fn it_serializes_into_raw_text_cell() {
71 let cell = TableCell::RawText("Data 1A".into());
72
73 let expected = serde_json::json!({
74 "type": "raw_text",
75 "text": "Data 1A",
76 });
77
78 let json = serde_json::to_value(cell).unwrap();
79 assert_eq!(json, expected);
80 }
81
82 #[test]
83 fn it_serializes_into_rich_text_cell() {
84 let cell = TableCell::RichText(rich_text());
85
86 let expected = serde_json::json!({
87 "type": "rich_text",
88 "elements": [
89 {
90 "type": "rich_text_section",
91 "elements": [
92 {
93 "text": "Data 1B",
94 "type": "link",
95 "url": "https://slack.com"
96 }
97 ]
98 }
99 ]
100 });
101
102 let json = serde_json::to_value(cell).unwrap();
103 assert_eq!(json, expected);
104 }
105
106 fn rich_text() -> RichText {
107 RichText::builder()
108 .element(
109 RichTextSection::builder()
110 .element(
111 RichTextElementLink::builder()
112 .text("Data 1B")
113 .url("https://slack.com")
114 .build()
115 .unwrap(),
116 )
117 .build()
118 .unwrap(),
119 )
120 .build()
121 .unwrap()
122 }
123}