slack-messaging 0.7.8

Support building Slack Block Kit message
Documentation
use super::*;
use crate::blocks::elements::Image;

use paste::paste;

fn inner_validator<F>(mut value: Value<Image>, error: ValidationErrorKind, f: F) -> Value<Image>
where
    F: Fn(&Image) -> bool,
{
    if value.inner_ref().is_some_and(f) {
        value.push(error);
    }
    value
}

fn alt_text_max(max: usize, value: Value<Image>) -> Value<Image> {
    inner_validator(value, ValidationErrorKind::MaxAltTextLength(max), |v| {
        v.alt_text.as_ref().is_some_and(|t| t.len() > max)
    })
}

macro_rules! impl_alt_text_max {
    ($($e:expr),*) => {
        paste! {
            $(
                pub(crate) fn [<alt_text_max_ $e>](value: Value<Image>) -> Value<Image> {
                    alt_text_max($e, value)
                }
            )*
        }
    }
}

impl_alt_text_max!(2000);

#[cfg(test)]
mod tests {
    use super::*;

    mod fn_alt_text_max_2000 {
        use super::*;

        #[test]
        fn it_sets_error_if_the_alt_text_is_too_long() {
            let result = test("a".repeat(2001));
            assert_eq!(
                result.errors,
                vec![ValidationErrorKind::MaxAltTextLength(2000)]
            );
        }

        #[test]
        fn it_passes_if_the_alt_text_is_smaller_than_2000() {
            let result = test("a".repeat(2000));
            assert!(result.errors.is_empty());
        }

        fn test(alt_text: impl Into<String>) -> Value<Image> {
            let value = image(alt_text);
            alt_text_max_2000(Value::new(Some(value)))
        }

        fn image(alt_text: impl Into<String>) -> Image {
            Image {
                alt_text: Some(alt_text.into()),
                image_url: Some("http://placekitten.com/700/500".into()),
                slack_file: None,
            }
        }
    }
}