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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
//! # Option Group
//! [slack api docs 🔗]
//!
//! Provides a way to group options in a [select menu 🔗] or [multi-select menu 🔗].
//!
//! [select menu 🔗]: https://api.slack.com/reference/block-kit/block-elements#select
//! [multi-select menu 🔗]: https://api.slack.com/reference/block-kit/block-elements#multi_select
//! [slack api docs 🔗]: https://api.slack.com/reference/block-kit/composition-objects#option_group
//! [`plain_text` only text object 🔗]: https://api.slack.com/reference/block-kit/composition-objects#text

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

use super::{opt::{AnyText, NoUrl},
            text,
            Opt};
use crate::val_helpr::ValidationResult;

/// # Option Group
/// [slack api docs 🔗]
///
/// Provides a way to group options in a [select menu 🔗] or [multi-select menu 🔗].
///
/// [select menu 🔗]: https://api.slack.com/reference/block-kit/block-elements#select
/// [multi-select menu 🔗]: https://api.slack.com/reference/block-kit/block-elements#multi_select
/// [slack api docs 🔗]: https://api.slack.com/reference/block-kit/composition-objects#option_group
/// [`plain_text` only text object 🔗]: https://api.slack.com/reference/block-kit/composition-objects#text
#[derive(Clone, Debug, Deserialize, Hash, PartialEq, Serialize, Validate)]
pub struct OptGroup<'a, T = AnyText, U = NoUrl> {
  #[validate(custom = "validate::label")]
  label: text::Text,

  #[validate(length(max = 100))]
  options: Vec<Opt<'a, T, U>>,
}

impl<'a> OptGroup<'a> {
  /// Build a new option group composition object
  ///
  /// # Examples
  /// see example for `OptGroupBuilder`
  pub fn builder() -> build::OptGroupBuilderInit<'a> {
    build::OptGroupBuilderInit::new()
  }

  /// Construct an Option Group from a label and
  /// collection of options in the group
  ///
  /// # Arguments
  /// - `label` - A [`plain_text` only text object 🔗] that defines
  ///     the label shown above this group of options.
  ///     Maximum length for the `text` in this field is 75 characters.
  /// - `opts` - An array of [option objects 🔗] that belong to
  ///     this specific group. Maximum of 100 items.
  ///
  /// [option objects 🔗]: https://api.slack.comCURRENT_PAGEoption
  /// [`plain_text` only text object 🔗]: https://api.slack.comCURRENT_PAGEtext
  ///
  /// # Example
  /// ```
  /// use slack_blocks::blocks::Block;
  /// use slack_blocks::blocks::section::Contents as Section;
  /// use slack_blocks::blocks::Actions;
  /// use slack_blocks::text::{Mrkdwn};
  /// use slack_blocks::compose::{OptGroup, Opt};
  ///
  /// let prompt = "Choose your favorite city from each state!";
  ///
  /// let blocks: Vec<Block> = vec![
  ///     Section::from_text(Mrkdwn::from(prompt)).into(),
  ///     // TODO: insert option group once block elements are in place
  ///     Actions::from_action_elements(vec![]).into(),
  /// ];
  ///
  /// let groups: Vec<OptGroup<_>> = vec![
  ///     OptGroup::from_label_and_opts(
  ///         "Arizona",
  ///         vec![
  ///             Opt::from_mrkdwn_and_value("Phoenix", "az_phx"),
  ///             // etc...
  ///         ]
  ///     ),
  ///     OptGroup::from_label_and_opts(
  ///         "California",
  ///         vec![
  ///             Opt::from_mrkdwn_and_value("San Diego", "ca_sd"),
  ///             // etc...
  ///         ]
  ///     ),
  /// ];
  /// ```
  #[deprecated(since = "0.15.0", note = "Use OptGroup::builder instead")]
  pub fn from_label_and_opts<T, U>(label: impl Into<text::Plain>,
                                   options: impl IntoIterator<Item = Opt<'a,
                                                           T,
                                                           U>>)
                                   -> OptGroup<'a, T, U> {
    OptGroup { label: label.into().into(),
               options: options.into_iter().collect() }
  }
}

impl<'a, T, U> OptGroup<'a, T, U> {
  /// Validate that this Option Group object
  /// agrees with Slack's model requirements
  ///
  /// # Errors
  /// - If `from_label_and_opts` was called with `label`
  ///     longer than 75 chars
  /// - If `from_label_and_opts` was called with
  ///     more than 100 options
  ///
  /// # Example
  /// ```
  /// use std::iter::repeat;
  ///
  /// use slack_blocks::compose::{Opt, OptGroup};
  ///
  /// let long_string: String = repeat(' ').take(76).collect();
  ///
  /// let opt = Opt::from_mrkdwn_and_value("San Diego", "ca_sd");
  /// let grp = OptGroup::from_label_and_opts(long_string, vec![opt]);
  ///
  /// assert_eq!(true, matches!(grp.validate(), Err(_)));
  /// ```
  pub fn validate(&self) -> ValidationResult {
    Validate::validate(self)
  }
}

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

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

  /// Required builder methods
  #[allow(non_camel_case_types)]
  mod method {
    /// OptGroupBuilder.label
    #[derive(Copy, Clone, Debug)]
    pub struct label;
    /// OptGroupBuilder.options
    #[derive(Copy, Clone, Debug)]
    pub struct options;
  }

  ///  Option Group builder
  ///
  ///  Allows you to construct a Option Group object safely, with compile-time checks
  ///  on required setter methods.
  ///
  ///  # Required Methods
  ///  `OptGroup::build()` is only available if these methods have been called:
  ///   - `options`
  ///   - `label`
  ///
  ///  # Example
  ///  ```
  ///  use std::convert::TryFrom;
  ///
  ///  use slack_blocks::{elems::{select::Static, BlockElement},
  ///                     blocks::{Actions, Block},
  ///                     compose::{Opt, OptGroup}};
  ///
  ///  #[derive(Clone, Copy, PartialEq)]
  ///  enum LangStyle {
  ///    Functional,
  ///    ObjectOriented,
  ///    SomewhereInbetween,
  ///  }
  ///
  ///  use LangStyle::*;
  ///
  ///  #[derive(Clone, Copy)]
  ///  struct Lang {
  ///    name: &'static str,
  ///    code: &'static str,
  ///    style: LangStyle,
  ///  }
  ///
  ///  impl Lang {
  ///    fn new(name: &'static str, code: &'static str, style: LangStyle) -> Self {
  ///      Self {
  ///        name,
  ///        code,
  ///        style,
  ///      }
  ///    }
  ///  }
  ///
  ///  let langs = vec![
  ///    Lang::new("Rust", "rs", SomewhereInbetween),
  ///    Lang::new("C#", "cs", ObjectOriented),
  ///    Lang::new("Haskell", "hs", Functional),
  ///  ];
  ///
  ///  let langs_of_style = |needle: LangStyle| langs.iter()
  ///                                                .filter(|Lang {style, ..}| *style == needle)
  ///                                                .map(|lang| Opt::builder()
  ///                                                                .text_plain(lang.name)
  ///                                                                .value(lang.code)
  ///                                                                .build()
  ///                                                )
  ///                                                .collect::<Vec<_>>();
  ///
  ///  let groups = vec![
  ///    OptGroup::builder()
  ///             .label("Functional")
  ///             .options(langs_of_style(Functional))
  ///             .build(),
  ///
  ///    OptGroup::builder()
  ///             .label("Object-Oriented")
  ///             .options(langs_of_style(ObjectOriented))
  ///             .build(),
  ///
  ///    OptGroup::builder()
  ///             .label("Somewhere Inbetween")
  ///             .options(langs_of_style(SomewhereInbetween))
  ///             .build(),
  ///  ];
  ///
  ///  let select: BlockElement =
  ///    Static::builder().placeholder("Choose your favorite programming language!")
  ///                     .option_groups(groups)
  ///                     .action_id("lang_chosen")
  ///                     .build()
  ///                     .into();
  ///
  ///  let block: Block =
  ///    Actions::try_from(select).expect("actions supports select elements")
  ///                             .into();
  ///
  ///  // <send block to API>
  ///  ```
  #[derive(Debug)]
  pub struct OptGroupBuilder<'a, T, U, Options, Label> {
    label: Option<text::Text>,
    options: Option<Vec<Opt<'a, T, U>>>,
    state: PhantomData<(Options, Label)>,
  }

  /// Initial state for OptGroupBuilder
  pub type OptGroupBuilderInit<'a> =
    OptGroupBuilder<'a,
                    AnyText,
                    NoUrl,
                    RequiredMethodNotCalled<method::options>,
                    RequiredMethodNotCalled<method::label>>;

  impl<'a, T, U, O, L> OptGroupBuilder<'a, T, U, O, L> {
    /// Construct a new OptGroupBuilder
    pub fn new() -> Self {
      Self { label: None,
             options: None,
             state: PhantomData::<_> }
    }

    fn cast_state<O2, L2>(self) -> OptGroupBuilder<'a, T, U, O2, L2> {
      OptGroupBuilder { label: self.label,
                        options: self.options,
                        state: PhantomData::<_> }
    }

    /// Set the options of this group (**Required**)
    ///
    /// An array of [option objects 🔗] that belong to
    /// this specific group.
    ///
    /// Maximum of 100 items.
    ///
    /// [option objects 🔗]: https://api.slack.comCURRENT_PAGEoption
    pub fn options<T2, U2, I>(
      self,
      options: I)
      -> OptGroupBuilder<'a, T2, U2, Set<method::options>, L>
      where I: IntoIterator<Item = Opt<'a, T2, U2>>
    {
      OptGroupBuilder { label: self.label,
                        options: Some(options.into_iter().collect()),
                        state: PhantomData::<_> }
    }

    /// A [`plain_text` only text object 🔗] that defines
    /// the label shown above this group of options.
    ///
    /// Maximum length for the `text` in this field is 75 characters.
    ///
    /// [`plain_text` only text object 🔗]: https://api.slack.comCURRENT_PAGEtext
    pub fn label<S>(mut self,
                    label: S)
                    -> OptGroupBuilder<'a, T, U, O, Set<method::label>>
      where S: Into<text::Plain>
    {
      self.label = Some(label.into().into());
      self.cast_state()
    }
  }

  impl<'a, T, U>
    OptGroupBuilder<'a, T, U, Set<method::options>, Set<method::label>>
  {
    /// All done building, now give me a darn option group!
    ///
    /// > `no method name 'build' found for struct 'compose::opt_group::build::OptGroupBuilder<...>'`?
    /// Make sure all required setter methods have been called. See docs for `OptGroupBuilder`.
    ///
    /// ```compile_fail
    /// use slack_blocks::compose::OptGroup;
    ///
    /// let sel = OptGroup::builder()
    ///                    .build();
    /// /*                  ^^^^^ method not found in
    ///                    `OptGroupBuilder<'_, RequiredMethodNotCalled<options>, RequiredMethodNotCalled<value>, _>`
    /// */
    /// ```
    ///
    /// ```
    /// use slack_blocks::compose::{Opt, OptGroup};
    ///
    /// let sel = OptGroup::builder().options(vec![Opt::builder().text_plain("foo")
    ///                                                          .value("bar")
    ///                                                          .build()])
    ///                              .label("foo")
    ///                              .build();
    /// ```
    pub fn build(self) -> OptGroup<'a, T, U> {
      OptGroup { label: self.label.unwrap(),
                 options: self.options.unwrap() }
    }
  }
}

mod validate {
  use super::*;
  use crate::val_helpr::{below_len, ValidatorResult};

  pub(super) fn label(text: &text::Text) -> ValidatorResult {
    below_len("Option Group Label", 75, text.as_ref())
  }
}