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 {
41 Self(text.into())
42 }
43}
44
45impl<T: Into<String>> From<T> for RawText {
46 fn from(value: T) -> Self {
47 Self::new(value)
48 }
49}
50
51impl Serialize for RawText {
52 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
53 where
54 S: serde::Serializer
55 {
56 use serde::ser::SerializeStruct;
57
58 let mut state = serializer.serialize_struct("RawText", 2)?;
59 state.serialize_field("type", "raw_text")?;
60 state.serialize_field("text", &self.0)?;
61 state.end()
62 }
63}
64
65#[cfg(test)]
66mod tests {
67 use super::*;
68 use crate::blocks::rich_text::{RichTextSection, types::RichTextElementLink};
69
70 #[test]
71 fn it_serializes_into_raw_text_cell() {
72 let cell = TableCell::RawText("Data 1A".into());
73
74 let expected = serde_json::json!({
75 "type": "raw_text",
76 "text": "Data 1A",
77 });
78
79 let json = serde_json::to_value(cell).unwrap();
80 assert_eq!(json, expected);
81 }
82
83 #[test]
84 fn it_serializes_into_rich_text_cell() {
85 let cell = TableCell::RichText(rich_text());
86
87 let expected = serde_json::json!({
88 "type": "rich_text",
89 "elements": [
90 {
91 "type": "rich_text_section",
92 "elements": [
93 {
94 "text": "Data 1B",
95 "type": "link",
96 "url": "https://slack.com"
97 }
98 ]
99 }
100 ]
101 });
102
103 let json = serde_json::to_value(cell).unwrap();
104 assert_eq!(json, expected);
105 }
106
107 fn rich_text() -> RichText {
108 RichText::builder()
109 .element(
110 RichTextSection::builder()
111 .element(
112 RichTextElementLink::builder()
113 .text("Data 1B")
114 .url("https://slack.com")
115 .build()
116 .unwrap(),
117 )
118 .build()
119 .unwrap(),
120 )
121 .build()
122 .unwrap()
123 }
124}