1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
//! # Context Block
//!
//! _[slack api docs 🔗][context_docs]_
//!
//! Displays message context, which can include both images and text.
//!
//! [context_docs]: https://api.slack.com/reference/block-kit/blocks#context

use std::borrow::Cow;

use serde::{Deserialize, Serialize};
use validator::Validate;

use crate::{convert, elems::Image, text, val_helpr::ValidationResult};

/// # Context Block
///
/// _[slack api docs 🔗][context_docs]_
///
/// Displays message context, which can include both images and text.
///
/// [context_docs]: https://api.slack.com/reference/block-kit/blocks#context
#[derive(Clone,
           Debug,
           Default,
           Deserialize,
           Hash,
           PartialEq,
           Serialize,
           Validate)]
pub struct Context<'a> {
  #[validate(length(max = 10))]
  elements: Vec<ImageOrText<'a>>,

  #[serde(skip_serializing_if = "Option::is_none")]
  #[validate(custom = "super::validate_block_id")]
  block_id: Option<Cow<'a, str>>,
}

impl<'a> Context<'a> {
  /// Build a new Context block.
  ///
  /// For example, see docs for ContextBuilder.
  pub fn builder() -> build::ContextBuilderInit<'a> {
    build::ContextBuilderInit::new()
  }

  /// Create an empty Context block (shorthand for `Default::default()`)
  ///
  /// # Example
  /// ```
  /// use slack_blocks::{blocks::{context, Block},
  ///                    text};
  ///
  /// let context = context::Context::new()
  ///     .with_element(text::Plain::from("my unformatted text"));
  ///
  /// let block: Block = context.into();
  /// // < send block to slack's API >
  /// ```
  #[deprecated(since = "0.19.2", note = "use Context::builder")]
  pub fn new() -> Self {
    Default::default()
  }

  /// Set the `block_id` for interactions on an existing `context::Context`
  ///
  /// # Arguments
  /// - `block_id` - A string acting as a unique identifier for a block.
  ///     You can use this `block_id` when you receive an interaction payload
  ///     to [identify the source of the action 🔗].
  ///     If not specified, a `block_id` will be generated.
  ///     Maximum length for this field is 255 characters.
  ///
  /// [identify the source of the action 🔗]: https://api.slack.com/interactivity/handling#payloads
  ///
  /// # Example
  /// ```
  /// use slack_blocks::{blocks::{context, Block},
  ///                    text};
  ///
  /// let text = text::Mrkdwn::from("_flavor_ *text*");
  /// let context: Block = context::Context::new().with_element(text)
  ///                                             .with_block_id("msg_id_12346")
  ///                                             .into();
  ///
  /// // < send block to slack's API >
  /// ```
  #[deprecated(since = "0.19.2", note = "use Context::builder")]
  pub fn with_block_id(mut self, block_id: impl Into<Cow<'a, str>>) -> Self {
    self.block_id = Some(block_id.into());
    self
  }

  /// Add a composition object to a context block.
  ///
  /// This is chainable, and can be used to easily
  /// populate the elements of a context block
  /// right after invoking `new`.
  ///
  /// # Arguments
  /// - `element` - A composition object;
  ///     Must be image elements or text objects.
  ///     Maximum number of items is 10.
  ///
  /// # Example
  /// ```
  /// use slack_blocks::{blocks::{context, Block},
  ///                    text};
  ///
  /// let context = context::Context::new()
  ///     .with_element(text::Plain::from("my unformatted text"));
  ///
  /// let block: Block = context.into();
  /// // < send block to slack's API >
  /// ```
  #[deprecated(since = "0.19.2", note = "use Context::builder")]
  pub fn with_element(mut self,
                      element: impl Into<self::ImageOrText<'a>>)
                      -> Self {
    self.elements.push(element.into());
    self
  }

  /// Construct a new `context::Context` from a collection of
  /// composition objects that are may not be supported by Context
  /// Blocks.
  ///
  /// If you _can't_ guarantee that a collection only contains image
  /// or text objects, `from_elements` may be more ergonomic for you.
  ///
  /// # Arguments
  /// - `elements` - An array of composition objects;
  ///     Must be image elements or text objects.
  ///     Maximum number of items is 10.
  ///
  /// # Examples
  /// ```
  /// use slack_blocks::{blocks::{context, Block},
  ///                    text};
  ///
  /// pub fn main() {
  ///   let objs: Vec<text::Mrkdwn> = vec![text::Mrkdwn::from("*s i c k*"),
  ///                                      text::Mrkdwn::from("*t i g h t*"),];
  ///   let context = context::Context::from_context_elements(objs);
  ///   let block: Block = context.into();
  ///   // < send block to slack's API >
  /// }
  /// ```
  #[deprecated(since = "0.19.2", note = "use Context::builder")]
  pub fn from_context_elements(elements: impl IntoIterator<Item = impl Into<ImageOrText<'a>>>)
                               -> Self {
    elements.into_iter()
            .map(|i| i.into())
            .collect::<Vec<_>>()
            .into()
  }

  /// Validate that this Context block agrees with Slack's model requirements
  ///
  /// # Errors
  /// - If `with_block_id` was called with a block id longer
  ///     than 255 chars
  /// - If `from_elements`, `from_context_elements`, or `with_element` was called with
  ///     more than 10 objects
  ///
  /// # Example
  /// ```
  /// use slack_blocks::blocks;
  ///
  /// let long_string = std::iter::repeat(' ').take(256).collect::<String>();
  ///
  /// let block = blocks::context::Context::new().with_block_id(long_string);
  ///
  /// assert_eq!(true, matches!(block.validate(), Err(_)));
  /// ```
  pub fn validate(&self) -> ValidationResult {
    Validate::validate(self)
  }
}

/// Context block builder
pub mod build {
  use std::marker::PhantomData;

  use super::*;
  use crate::build::*;

  /// Compile-time markers for builder methods
  #[allow(non_camel_case_types)]
  pub mod method {
    /// ContextBuilder.elements
    #[derive(Clone, Copy, Debug)]
    pub struct elements;
  }

  /// Initial state for `ContextBuilder`
  pub type ContextBuilderInit<'a> =
    ContextBuilder<'a, RequiredMethodNotCalled<method::elements>>;

  /// Build an Context block
  ///
  /// Allows you to construct safely, with compile-time checks
  /// on required setter methods.
  ///
  /// # Required Methods
  /// `ContextBuilder::build()` is only available if these methods have been called:
  ///  - `element`
  ///
  /// # Example
  /// ```
  /// use slack_blocks::{blocks::Context, elems::Image, text::ToSlackPlaintext};
  ///
  /// let block = Context::builder().element("foo".plaintext())
  ///                               .element(Image::builder().image_url("foo.png")
  ///                                                        .alt_text("pic of foo")
  ///                                                        .build())
  ///                               .build();
  /// ```
  #[derive(Debug)]
  pub struct ContextBuilder<'a, Elements> {
    elements: Option<Vec<ImageOrText<'a>>>,
    block_id: Option<Cow<'a, str>>,
    state: PhantomData<Elements>,
  }

  impl<'a, E> ContextBuilder<'a, E> {
    /// Create a new ContextBuilder
    pub fn new() -> Self {
      Self { elements: None,
             block_id: None,
             state: PhantomData::<_> }
    }

    /// Add an `element` (**Required**, can be called many times)
    ///
    /// A composition object; Must be image elements or text objects.
    ///
    /// Maximum number of items is 10.
    pub fn element<El>(self,
                       element: El)
                       -> ContextBuilder<'a, Set<method::elements>>
      where El: Into<ImageOrText<'a>>
    {
      let mut elements = self.elements.unwrap_or_default();
      elements.push(element.into());

      ContextBuilder { block_id: self.block_id,
                       elements: Some(elements),
                       state: PhantomData::<_> }
    }

    /// Set `block_id` (Optional)
    ///
    /// A string acting as a unique identifier for a block.
    ///
    /// You can use this `block_id` when you receive an interaction payload
    /// to [identify the source of the action 🔗].
    ///
    /// If not specified, a `block_id` will be generated.
    ///
    /// Maximum length for this field is 255 characters.
    ///
    /// [identify the source of the action 🔗]: https://api.slack.com/interactivity/handling#payloads
    pub fn block_id<S>(mut self, block_id: S) -> Self
      where S: Into<Cow<'a, str>>
    {
      self.block_id = Some(block_id.into());
      self
    }
  }

  impl<'a> ContextBuilder<'a, Set<method::elements>> {
    /// All done building, now give me a darn actions block!
    ///
    /// > `no method name 'build' found for struct 'ContextBuilder<...>'`?
    /// Make sure all required setter methods have been called. See docs for `ContextBuilder`.
    ///
    /// ```compile_fail
    /// use slack_blocks::blocks::Context;
    ///
    /// let foo = Context::builder().build(); // Won't compile!
    /// ```
    ///
    /// ```
    /// use slack_blocks::{blocks::Context,
    ///                    compose::text::ToSlackPlaintext,
    ///                    elems::Image};
    ///
    /// let block = Context::builder().element("foo".plaintext())
    ///                               .element(Image::builder().image_url("foo.png")
    ///                                                        .alt_text("pic of foo")
    ///                                                        .build())
    ///                               .build();
    /// ```
    pub fn build(self) -> Context<'a> {
      Context { elements: self.elements.unwrap(),
                block_id: self.block_id }
    }
  }
}

impl<'a> From<Vec<ImageOrText<'a>>> for Context<'a> {
  fn from(elements: Vec<ImageOrText<'a>>) -> Self {
    Self { elements,
           ..Default::default() }
  }
}

/// The Composition objects supported by this block
#[derive(Clone, Debug, Deserialize, Hash, PartialEq, Serialize)]
#[allow(missing_docs)]
pub enum ImageOrText<'a> {
  Text(text::Text),
  Image(Image<'a>),
}

convert!(impl From<text::Text> for ImageOrText<'static> => |txt| ImageOrText::Text(txt));
convert!(impl<'a> From<Image<'a>> for ImageOrText<'a> => |i| ImageOrText::Image(i));
convert!(impl From<text::Plain> for ImageOrText<'static> => |t| text::Text::from(t).into());
convert!(impl From<text::Mrkdwn> for ImageOrText<'static> => |t| text::Text::from(t).into());