use crate::blocks::elements::{FeedbackButtons, IconButton};
use crate::validators::*;
use serde::Serialize;
use slack_messaging_derive::Builder;
#[derive(Debug, Clone, Serialize, PartialEq, Builder)]
#[serde(tag = "type", rename = "context_actions")]
pub struct ContextActions {
#[builder(push_item = "element", validate("required", "list::max_item_5"))]
pub(super) elements: Option<Vec<ContextActionsElement>>,
#[serde(skip_serializing_if = "Option::is_none")]
#[builder(validate("text::max_255"))]
pub(super) block_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, PartialEq)]
#[serde(untagged)]
pub enum ContextActionsElement {
FeedbackButtons(Box<FeedbackButtons>),
IconButton(Box<IconButton>),
}
macro_rules! context_actions_from {
($($ty:ident,)*) => {
$(
impl From<$ty> for ContextActionsElement {
fn from(value: $ty) -> Self {
Self::$ty(Box::new(value))
}
}
)*
}
}
context_actions_from! {
FeedbackButtons,
IconButton,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::blocks::elements::test_helpers::*;
use crate::errors::*;
#[test]
fn it_implements_builder() {
let expected = ContextActions {
block_id: Some("context_actions_0".into()),
elements: Some(vec![fb_buttons().into()]),
};
let val = ContextActions::builder()
.set_block_id(Some("context_actions_0"))
.set_elements(Some(vec![fb_buttons().into()]))
.build()
.unwrap();
assert_eq!(val, expected);
let val = ContextActions::builder()
.block_id("context_actions_0")
.elements(vec![fb_buttons().into()])
.build()
.unwrap();
assert_eq!(val, expected);
}
#[test]
fn it_implements_push_item_method() {
let expected = ContextActions {
block_id: None,
elements: Some(vec![fb_buttons().into()]),
};
let val = ContextActions::builder()
.element(fb_buttons())
.build()
.unwrap();
assert_eq!(val, expected);
}
#[test]
fn it_requires_elements_field() {
let err = ContextActions::builder().build().unwrap_err();
assert_eq!(err.object(), "ContextActions");
let errors = err.field("elements");
assert!(errors.includes(ValidationErrorKind::Required));
}
#[test]
fn it_requires_elements_list_size_less_than_5() {
let elements: Vec<ContextActionsElement> = (0..6).map(|_| fb_buttons().into()).collect();
let err = ContextActions::builder()
.elements(elements)
.build()
.unwrap_err();
assert_eq!(err.object(), "ContextActions");
let errors = err.field("elements");
assert!(errors.includes(ValidationErrorKind::MaxArraySize(5)));
}
#[test]
fn it_requires_block_id_less_than_255_characters_long() {
let err = ContextActions::builder()
.block_id("a".repeat(256))
.element(fb_buttons())
.build()
.unwrap_err();
assert_eq!(err.object(), "ContextActions");
let errors = err.field("block_id");
assert!(errors.includes(ValidationErrorKind::MaxTextLength(255)));
}
}