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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
//! ## Builder
//!
//! `Builder` is the module which defines the prop builder trait.
//! In addition provides a Generic Props builder which exports all the possible properties in
//! the builder.

/**
 * MIT License
 *
 * tui-realm - Copyright (C) 2021 Christian Visintin
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
use super::borders::{BorderType, Borders};
use super::{PropPayload, Props, TextParts};

use tui::style::{Color, Modifier};

// -- Props builder

/// ## PropsBuilder
///
/// The PropsBuilder trait just defines the method build, which all the builders must implement.
/// This method must return the Props hold by the ProspBuilder.
/// If you're looking on how to implement a Props Builder, check out the `GenericPropsBuilder`.
pub trait PropsBuilder {
    /// ### build
    ///
    /// Build Props from builder
    /// You shouldn't allow this method to be called twice.
    /// Panic is ok.
    fn build(&mut self) -> Props;

    /// ### hidden
    ///
    /// Initialize props with visible set to False
    fn hidden(&mut self) -> &mut Self;

    /// ### visible
    ///
    /// Initialize props with visible set to True
    fn visible(&mut self) -> &mut Self;
}

/// ## GenericPropsBuilder
///
/// This props builder exports methods to set values for all the possible properties.
/// In a normal case you shouldn't use this builder, unless you can actually customize everything of your component.
/// For a Builder you should always implement only three traits: `Default`, `From<Props>` and `PropsBuilder`, then you should implement
/// the setter methods for it, for the only properties you need for the associated component.
pub struct GenericPropsBuilder {
    props: Option<Props>,
}

impl Default for GenericPropsBuilder {
    fn default() -> Self {
        GenericPropsBuilder {
            props: Some(Props::default()),
        }
    }
}

impl PropsBuilder for GenericPropsBuilder {
    fn build(&mut self) -> Props {
        self.props.take().unwrap()
    }

    fn hidden(&mut self) -> &mut Self {
        if let Some(props) = self.props.as_mut() {
            props.visible = false;
        }
        self
    }

    fn visible(&mut self) -> &mut Self {
        if let Some(props) = self.props.as_mut() {
            props.visible = true;
        }
        self
    }
}

impl From<Props> for GenericPropsBuilder {
    fn from(props: Props) -> Self {
        GenericPropsBuilder { props: Some(props) }
    }
}

impl GenericPropsBuilder {
    /// ### with_foreground
    ///
    /// Set foreground color for component
    pub fn with_foreground(&mut self, color: Color) -> &mut Self {
        if let Some(props) = self.props.as_mut() {
            props.foreground = color;
        }
        self
    }

    /// ### with_background
    ///
    /// Set background color for component
    pub fn with_background(&mut self, color: Color) -> &mut Self {
        if let Some(props) = self.props.as_mut() {
            props.background = color;
        }
        self
    }

    /// ### with_borders
    ///
    /// Set component borders style
    pub fn with_borders(
        &mut self,
        borders: Borders,
        variant: BorderType,
        color: Color,
    ) -> &mut Self {
        if let Some(props) = self.props.as_mut() {
            props.borders.borders = borders;
            props.borders.variant = variant;
            props.borders.color = color;
        }
        self
    }

    /// ### bold
    ///
    /// Set bold property for component
    pub fn bold(&mut self) -> &mut Self {
        if let Some(props) = self.props.as_mut() {
            props.modifiers |= Modifier::BOLD;
        }
        self
    }

    /// ### italic
    ///
    /// Set italic property for component
    pub fn italic(&mut self) -> &mut Self {
        if let Some(props) = self.props.as_mut() {
            props.modifiers |= Modifier::ITALIC;
        }
        self
    }

    /// ### underlined
    ///
    /// Set underlined property for component
    pub fn underlined(&mut self) -> &mut Self {
        if let Some(props) = self.props.as_mut() {
            props.modifiers |= Modifier::UNDERLINED;
        }
        self
    }

    /// ### slow_blink
    ///
    /// Set slow_blink property for component
    pub fn slow_blink(&mut self) -> &mut Self {
        if let Some(props) = self.props.as_mut() {
            props.modifiers |= Modifier::SLOW_BLINK;
        }
        self
    }

    /// ### rapid_blink
    ///
    /// Set rapid_blink property for component
    pub fn rapid_blink(&mut self) -> &mut Self {
        if let Some(props) = self.props.as_mut() {
            props.modifiers |= Modifier::RAPID_BLINK;
        }
        self
    }

    /// ### reversed
    ///
    /// Set reversed property for component
    pub fn reversed(&mut self) -> &mut Self {
        if let Some(props) = self.props.as_mut() {
            props.modifiers |= Modifier::REVERSED;
        }
        self
    }

    /// ### strikethrough
    ///
    /// Set strikethrough property for component
    pub fn strikethrough(&mut self) -> &mut Self {
        if let Some(props) = self.props.as_mut() {
            props.modifiers |= Modifier::CROSSED_OUT;
        }
        self
    }

    /// ### with_texts
    ///
    /// Set texts for component
    pub fn with_texts(&mut self, texts: TextParts) -> &mut Self {
        if let Some(props) = self.props.as_mut() {
            props.texts = texts;
        }
        self
    }

    /// ### with_custom_color
    ///
    /// Set a custom color inside the color palette
    pub fn with_custom_color(&mut self, name: &'static str, color: Color) -> &mut Self {
        if let Some(props) = self.props.as_mut() {
            props.palette.insert(name, color);
        }
        self
    }

    /// ### with_value
    ///
    /// Set a new key-value for component
    pub fn with_value(&mut self, key: &'static str, value: PropPayload) -> &mut Self {
        if let Some(props) = self.props.as_mut() {
            props.own.insert(key, value);
        }
        self
    }
}

#[cfg(test)]
mod test {

    use super::super::PropValue;
    use super::super::TextSpan;
    use super::*;

    use pretty_assertions::assert_eq;

    #[test]
    fn test_props_builder() {
        let props: Props = GenericPropsBuilder::default()
            .hidden()
            .with_background(Color::Blue)
            .with_foreground(Color::Green)
            .with_borders(Borders::BOTTOM, BorderType::Plain, Color::White)
            .bold()
            .italic()
            .underlined()
            .strikethrough()
            .reversed()
            .rapid_blink()
            .slow_blink()
            .with_custom_color("arrows", Color::Red)
            .with_texts(TextParts::new(
                Some(String::from("hello")),
                Some(vec![TextSpan::from("hey")]),
            ))
            .with_value(
                "input",
                PropPayload::One(PropValue::Str(String::from("Hello"))),
            )
            .build();
        assert_eq!(props.background, Color::Blue);
        assert_eq!(props.borders.borders, Borders::BOTTOM);
        assert_eq!(props.borders.color, Color::White);
        assert_eq!(props.borders.variant, BorderType::Plain);
        assert!(props.modifiers.intersects(Modifier::BOLD));
        assert!(props.modifiers.intersects(Modifier::ITALIC));
        assert!(props.modifiers.intersects(Modifier::UNDERLINED));
        assert!(props.modifiers.intersects(Modifier::SLOW_BLINK));
        assert!(props.modifiers.intersects(Modifier::RAPID_BLINK));
        assert!(props.modifiers.intersects(Modifier::REVERSED));
        assert!(props.modifiers.intersects(Modifier::CROSSED_OUT));
        assert_eq!(props.foreground, Color::Green);
        assert_eq!(props.texts.title.as_ref().unwrap().as_str(), "hello");
        if let Some(PropPayload::One(PropValue::Str(s))) = props.own.get("input") {
            assert_eq!(s.as_str(), "Hello");
        } else {
            panic!("Expected value to be a string");
        }
        assert_eq!(
            props
                .texts
                .spans
                .as_ref()
                .unwrap()
                .get(0)
                .unwrap()
                .content
                .as_str(),
            "hey"
        );
        assert_eq!(props.visible, false);
        let props: Props = GenericPropsBuilder::default()
            .visible()
            .with_background(Color::Blue)
            .with_foreground(Color::Green)
            .bold()
            .italic()
            .underlined()
            .with_texts(TextParts::new(
                Some(String::from("hello")),
                Some(vec![TextSpan::from("hey")]),
            ))
            .build();
        assert_eq!(props.background, Color::Blue);
        assert!(props.modifiers.intersects(Modifier::BOLD));
        assert_eq!(props.foreground, Color::Green);
        assert!(props.modifiers.intersects(Modifier::ITALIC));
        assert_eq!(props.texts.title.as_ref().unwrap().as_str(), "hello");
        assert_eq!(
            props
                .texts
                .spans
                .as_ref()
                .unwrap()
                .get(0)
                .unwrap()
                .content
                .as_str(),
            "hey"
        );
        assert!(props.modifiers.intersects(Modifier::UNDERLINED));
        assert_eq!(props.visible, true);
    }

    #[test]
    #[should_panic]
    fn test_props_build_twice() {
        let mut builder: GenericPropsBuilder = GenericPropsBuilder::default();
        let _ = builder.build();
        builder
            .hidden()
            .with_background(Color::Blue)
            .with_foreground(Color::Green)
            .bold()
            .italic()
            .underlined()
            .with_texts(TextParts::new(
                Some(String::from("hello")),
                Some(vec![TextSpan::from("hey")]),
            ));
        // Rebuild
        let _ = builder.build();
    }

    #[test]
    fn test_props_builder_from_props() {
        let props: Props = GenericPropsBuilder::default()
            .hidden()
            .with_background(Color::Blue)
            .with_foreground(Color::Green)
            .bold()
            .italic()
            .underlined()
            .with_texts(TextParts::new(
                Some(String::from("hello")),
                Some(vec![TextSpan::from("hey")]),
            ))
            .build();
        // Ok, now make a builder from properties
        let builder: GenericPropsBuilder = GenericPropsBuilder::from(props);
        assert!(builder.props.is_some());
    }
}