blazegram 0.4.2

Telegram bot framework: clean chats, zero garbage, declarative screens, pure Rust MTProto.
Documentation
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
//! Form Wizard — declarative multi-step forms.

use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

use crate::ctx::Ctx;
use crate::error::HandlerResult;
use crate::i18n::{ft, ft_with};
use crate::keyboard::KeyboardBuilder;
use crate::screen::Screen;
use crate::types::*;

/// Collected form data — maps field names to their JSON values.
pub type FormData = HashMap<String, serde_json::Value>;

/// Async handler called with the Ctx and collected FormData when a form is submitted.
pub type FormCompleteHandler = Arc<
    dyn Fn(&mut Ctx, FormData) -> Pin<Box<dyn Future<Output = HandlerResult> + Send + '_>>
        + Send
        + Sync,
>;

/// Async handler called with the Ctx when the user cancels a form.
pub type FormCancelHandler =
    Arc<dyn Fn(&mut Ctx) -> Pin<Box<dyn Future<Output = HandlerResult> + Send + '_>> + Send + Sync>;

/// A multi-step form (wizard) that collects data from the user one field at a time.
pub struct Form {
    /// Unique form identifier.
    pub id: String,
    /// Ordered list of form steps.
    pub steps: Vec<FormStep>,
    /// Handler called with collected data when the form is submitted.
    pub on_complete: FormCompleteHandler,
    /// Handler called when the user cancels the form.
    pub on_cancel: Option<FormCancelHandler>,
}

/// Function that builds a screen for a form step.
pub type FormScreenFn = Arc<dyn Fn(&FormData, &str) -> Screen + Send + Sync>;

/// A single step (field) in a [`Form`].
pub struct FormStep {
    /// Unique step identifier.
    pub id: String,
    /// Field name (key in the result data map).
    pub field: String,
    /// Function that builds the screen for this step. Receives collected data so far and the user's language code.
    pub screen_fn: FormScreenFn,
    /// How this step parses and validates input.
    pub parser: FieldParser,
}

#[derive(Clone)]
/// How a form step parses and validates user input.
pub enum FieldParser {
    /// Free-form text with optional validation.
    Text {
        /// Validation function; `None` accepts anything.
        validator: Option<ValidatorFn>,
    },
    /// Numeric integer input with optional range.
    Integer {
        /// Minimum allowed value.
        min: Option<i64>,
        /// Maximum allowed value.
        max: Option<i64>,
    },
    /// Pick one from a list of labelled options.
    Choice {
        /// `(label, value)` pairs shown to the user.
        options: Vec<(String, String)>,
    },
    /// Photo.
    Photo,
}

impl FieldParser {
    /// Validate input. `lang` is the user's language for error messages.
    pub fn validate(&self, input: &str, lang: &str) -> Result<serde_json::Value, String> {
        match self {
            Self::Text { validator } => {
                if let Some(v) = validator {
                    v(input)?;
                }
                Ok(serde_json::Value::String(input.to_string()))
            }
            Self::Integer { min, max } => {
                let n: i64 = input.parse().map_err(|_| ft(lang, "bg-err-nan"))?;
                if let Some(min) = min {
                    if n < *min {
                        return Err(ft_with(lang, "bg-err-min", &[("min", &min.to_string())]));
                    }
                }
                if let Some(max) = max {
                    if n > *max {
                        return Err(ft_with(lang, "bg-err-max", &[("max", &max.to_string())]));
                    }
                }
                Ok(serde_json::Value::Number(n.into()))
            }
            Self::Choice { options } => {
                if options.iter().any(|(_, v)| v == input) {
                    Ok(serde_json::Value::String(input.to_string()))
                } else {
                    Err(ft(lang, "bg-err-choice"))
                }
            }
            Self::Photo => Err(ft(lang, "bg-err-photo")),
        }
    }
}

// ─── Builder ───

/// Fluent builder for constructing a [`Form`].
pub struct FormBuilder {
    id: String,
    steps: Vec<FormStep>,
    on_complete: Option<FormCompleteHandler>,
    on_cancel: Option<FormCancelHandler>,
}

impl Form {
    /// Start building a new form with the given ID.
    pub fn builder(id: &str) -> FormBuilder {
        FormBuilder {
            id: id.to_string(),
            steps: Vec::new(),
            on_complete: None,
            on_cancel: None,
        }
    }
}

impl FormBuilder {
    /// Add a free-text input step.
    pub fn text_step(
        self,
        id: &str,
        field: &str,
        question: impl Into<String>,
    ) -> FormStepTextBuilder {
        FormStepTextBuilder {
            parent: self,
            id: id.to_string(),
            field: field.to_string(),
            question: question.into(),
            validator: None,
            placeholder: None,
        }
    }

    /// Add a numeric integer input step.
    pub fn integer_step(
        self,
        id: &str,
        field: &str,
        question: impl Into<String>,
    ) -> FormStepIntBuilder {
        FormStepIntBuilder {
            parent: self,
            id: id.to_string(),
            field: field.to_string(),
            question: question.into(),
            min: None,
            max: None,
        }
    }

    /// Add a multiple-choice step.
    pub fn choice_step(
        mut self,
        id: &str,
        field: &str,
        question: impl Into<String>,
        options: Vec<(impl Into<String>, impl Into<String>)>,
    ) -> Self {
        let options: Vec<(String, String)> = options
            .into_iter()
            .map(|(d, v)| (d.into(), v.into()))
            .collect();
        let q = question.into();
        let step_id = id.to_string();
        let opts_clone = options.clone();

        self.steps.push(FormStep {
            id: step_id.clone(),
            field: field.to_string(),
            screen_fn: Arc::new(move |_data, lang| {
                let mut kb = KeyboardBuilder::with_lang(lang);
                for (display, value) in &opts_clone {
                    kb = kb.button_row(display.clone(), format!("__form_choice:{}", value));
                }
                kb = kb.button_row(ft(lang, "bg-form-cancel"), "__form_cancel");
                Screen::builder(format!("__form__{}", step_id))
                    .text(q.clone())
                    .keyboard(move |_| kb)
                    .build()
            }),
            parser: FieldParser::Choice { options },
        });
        self
    }

    /// Add a photo upload step.
    pub fn photo_step(mut self, id: &str, field: &str, question: impl Into<String>) -> Self {
        let q = question.into();
        let step_id = id.to_string();

        self.steps.push(FormStep {
            id: step_id.clone(),
            field: field.to_string(),
            screen_fn: Arc::new(move |_data, lang| {
                Screen::builder(format!("__form__{}", step_id))
                    .text(q.clone())
                    .keyboard(|kb| kb.button_row(ft(lang, "bg-form-cancel"), "__form_cancel"))
                    .expect_photo()
                    .build()
            }),
            parser: FieldParser::Photo,
        });
        self
    }

    /// Add a final confirmation step that shows collected data.
    pub fn confirm_step(
        mut self,
        formatter: impl Fn(&FormData) -> String + Send + Sync + 'static,
    ) -> Self {
        self.steps.push(FormStep {
            id: "__confirm__".to_string(),
            field: "__confirmed__".to_string(),
            screen_fn: Arc::new(move |data, lang| {
                let summary = formatter(data);
                let text = ft_with(lang, "bg-form-review", &[("summary", &summary)]);
                Screen::builder("__form__confirm")
                    .text(text)
                    .keyboard(|kb| {
                        kb.confirm_cancel(
                            ft(lang, "bg-form-confirm"),
                            "__form_confirm:yes",
                            ft(lang, "bg-form-cancel"),
                            "__form_cancel",
                        )
                    })
                    .build()
            }),
            parser: FieldParser::Choice {
                options: vec![("yes".to_string(), "yes".to_string())],
            },
        });
        self
    }

    /// Set the handler called when the form is successfully completed.
    pub fn on_complete(
        mut self,
        handler: impl Fn(&mut Ctx, FormData) -> Pin<Box<dyn Future<Output = HandlerResult> + Send + '_>>
        + Send
        + Sync
        + 'static,
    ) -> Self {
        self.on_complete = Some(Arc::new(handler));
        self
    }

    /// Set the handler called when the user cancels.
    pub fn on_cancel(
        mut self,
        handler: impl Fn(&mut Ctx) -> Pin<Box<dyn Future<Output = HandlerResult> + Send + '_>>
        + Send
        + Sync
        + 'static,
    ) -> Self {
        self.on_cancel = Some(Arc::new(handler));
        self
    }

    /// Consume the builder and produce a [`Form`].
    ///
    /// Returns `Err` if `.on_complete()` was not set.
    pub fn build(self) -> Result<Form, &'static str> {
        Ok(Form {
            id: self.id,
            steps: self.steps,
            on_complete: self
                .on_complete
                .ok_or("Form::build(): .on_complete() handler is required")?,
            on_cancel: self.on_cancel,
        })
    }
}

// ─── Text step builder ───

/// Builder for a free-text form step.
pub struct FormStepTextBuilder {
    parent: FormBuilder,
    id: String,
    field: String,
    question: String,
    validator: Option<ValidatorFn>,
    placeholder: Option<String>,
}

impl FormStepTextBuilder {
    /// Set a validation function for this text step.
    pub fn validator(
        mut self,
        f: impl Fn(&str) -> Result<(), String> + Send + Sync + 'static,
    ) -> Self {
        self.validator = Some(Arc::new(f));
        self
    }

    /// Set placeholder text for the input field.
    pub fn placeholder(mut self, p: impl Into<String>) -> Self {
        self.placeholder = Some(p.into());
        self
    }

    /// Finish configuring this step and return to the form builder.
    pub fn done(self) -> FormBuilder {
        let q = self.question;
        let step_id = self.id.clone();
        let validator = self.validator.clone();

        let step = FormStep {
            id: self.id,
            field: self.field,
            screen_fn: Arc::new(move |_data, lang| {
                let mut builder = Screen::builder(format!("__form__{}", step_id)).text(q.clone());
                builder = builder
                    .keyboard(|kb| kb.button_row(ft(lang, "bg-form-cancel"), "__form_cancel"));
                builder.build()
            }),
            parser: FieldParser::Text { validator },
        };

        let mut parent = self.parent;
        parent.steps.push(step);
        parent
    }

    // Chain shortcuts
    /// Add a free-text input step.
    pub fn text_step(
        self,
        id: &str,
        field: &str,
        question: impl Into<String>,
    ) -> FormStepTextBuilder {
        self.done().text_step(id, field, question)
    }

    /// Add a numeric integer input step.
    pub fn integer_step(
        self,
        id: &str,
        field: &str,
        question: impl Into<String>,
    ) -> FormStepIntBuilder {
        self.done().integer_step(id, field, question)
    }

    /// Set the handler called when the form is successfully completed.
    pub fn on_complete(
        self,
        handler: impl Fn(&mut Ctx, FormData) -> Pin<Box<dyn Future<Output = HandlerResult> + Send + '_>>
        + Send
        + Sync
        + 'static,
    ) -> FormBuilder {
        self.done().on_complete(handler)
    }

    /// Consume the builder and produce a [`Form`].
    pub fn build(self) -> Result<Form, &'static str> {
        self.done().build()
    }
}

// ─── Integer step builder ───

/// Builder for an integer form step with optional min/max bounds.
pub struct FormStepIntBuilder {
    parent: FormBuilder,
    id: String,
    field: String,
    question: String,
    min: Option<i64>,
    max: Option<i64>,
}

impl FormStepIntBuilder {
    /// Set the minimum allowed value.
    pub fn min(mut self, min: i64) -> Self {
        self.min = Some(min);
        self
    }

    /// Set the maximum allowed value.
    pub fn max(mut self, max: i64) -> Self {
        self.max = Some(max);
        self
    }

    /// Finish configuring this step and return to the form builder.
    pub fn done(self) -> FormBuilder {
        let q = self.question;
        let step_id = self.id.clone();

        let step = FormStep {
            id: self.id,
            field: self.field,
            screen_fn: Arc::new(move |_data, lang| {
                Screen::builder(format!("__form__{}", step_id))
                    .text(q.clone())
                    .keyboard(|kb| kb.button_row(ft(lang, "bg-form-cancel"), "__form_cancel"))
                    .build()
            }),
            parser: FieldParser::Integer {
                min: self.min,
                max: self.max,
            },
        };

        let mut parent = self.parent;
        parent.steps.push(step);
        parent
    }

    /// Set the handler called when the form is successfully completed.
    pub fn on_complete(
        self,
        handler: impl Fn(&mut Ctx, FormData) -> Pin<Box<dyn Future<Output = HandlerResult> + Send + '_>>
        + Send
        + Sync
        + 'static,
    ) -> FormBuilder {
        self.done().on_complete(handler)
    }

    /// Consume the builder and produce a [`Form`].
    pub fn build(self) -> Result<Form, &'static str> {
        self.done().build()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ctx::Ctx;
    use crate::error::HandlerResult;
    use std::future::Future;
    use std::pin::Pin;

    fn dummy_handler()
    -> impl Fn(&mut Ctx, FormData) -> Pin<Box<dyn Future<Output = HandlerResult> + Send + '_>>
    + Send
    + Sync
    + 'static {
        |_ctx: &mut Ctx, _data: FormData| Box::pin(async { Ok(()) })
    }

    fn dummy_cancel()
    -> impl Fn(&mut Ctx) -> Pin<Box<dyn Future<Output = HandlerResult> + Send + '_>>
    + Send
    + Sync
    + 'static {
        |_ctx: &mut Ctx| Box::pin(async { Ok(()) })
    }

    #[test]
    fn form_builder_text_step() {
        let form = Form::builder("reg")
            .text_step("name", "name", "What is your name?")
            .done()
            .on_complete(dummy_handler())
            .build()
            .unwrap();
        assert_eq!(form.id, "reg");
        assert_eq!(form.steps.len(), 1);
        assert_eq!(form.steps[0].id, "name");
    }

    #[test]
    fn form_builder_multiple_steps() {
        let form = Form::builder("survey")
            .text_step("q1", "answer1", "Question 1?")
            .done()
            .text_step("q2", "answer2", "Question 2?")
            .done()
            .on_complete(dummy_handler())
            .build()
            .unwrap();
        assert_eq!(form.steps.len(), 2);
    }

    #[test]
    fn form_builder_integer_step() {
        let form = Form::builder("age")
            .integer_step("age", "age", "How old are you?")
            .min(1)
            .max(150)
            .done()
            .on_complete(dummy_handler())
            .build()
            .unwrap();
        assert_eq!(form.steps.len(), 1);
        assert!(matches!(form.steps[0].parser, FieldParser::Integer { .. }));
    }

    #[test]
    fn form_builder_choice_step() {
        let form = Form::builder("pick")
            .choice_step(
                "color",
                "color",
                "Pick a color",
                vec![("Red", "red"), ("Blue", "blue")],
            )
            .on_complete(dummy_handler())
            .build()
            .unwrap();
        assert_eq!(form.steps.len(), 1);
        assert!(matches!(form.steps[0].parser, FieldParser::Choice { .. }));
    }

    #[test]
    fn field_parser_text_valid() {
        let parser = FieldParser::Text { validator: None };
        assert!(parser.validate("anything", "en").is_ok());
    }

    #[test]
    fn field_parser_text_with_validator() {
        let parser = FieldParser::Text {
            validator: Some(std::sync::Arc::new(|s| {
                if s.len() >= 3 {
                    Ok(())
                } else {
                    Err("too short".into())
                }
            })),
        };
        assert!(parser.validate("abc", "en").is_ok());
        assert!(parser.validate("ab", "en").is_err());
    }

    #[test]
    fn field_parser_integer() {
        let parser = FieldParser::Integer {
            min: Some(1),
            max: Some(100),
        };
        assert!(parser.validate("50", "en").is_ok());
        assert!(parser.validate("0", "en").is_err());
        assert!(parser.validate("101", "en").is_err());
        assert!(parser.validate("abc", "en").is_err());
    }

    #[test]
    fn field_parser_choice() {
        let parser = FieldParser::Choice {
            options: vec![
                ("A Label".into(), "a".into()),
                ("B Label".into(), "b".into()),
            ],
        };
        assert!(parser.validate("a", "en").is_ok());
        assert!(parser.validate("c", "en").is_err());
    }

    #[test]
    fn form_has_cancel_handler() {
        let form = Form::builder("x")
            .text_step("s", "f", "Q")
            .done()
            .on_cancel(dummy_cancel())
            .on_complete(dummy_handler())
            .build()
            .unwrap();
        assert!(form.on_cancel.is_some());
    }
}