numeric_input.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package tgbot
  2. import (
  3. "strconv"
  4. "github.com/mymmrac/telego"
  5. tu "github.com/mymmrac/telego/telegoutil"
  6. )
  7. // updateNumericInput applies one number-pad key: -2 clears, -1 backspaces, and 0..9 append.
  8. // Callers retain their own validation and keyboard labels.
  9. func updateNumericInput(value, key int) int {
  10. switch key {
  11. case -2:
  12. return 0
  13. case -1:
  14. if value > 0 {
  15. return value / 10
  16. }
  17. return value
  18. default:
  19. return value*10 + key
  20. }
  21. }
  22. // numericKeypadSpec describes one number-pad flow. dataBase is the callback
  23. // prefix without its "_in"/"_c" suffix, and dataArgs carries any leading
  24. // argument (an email plus its separating space) the flow threads through.
  25. type numericKeypadSpec struct {
  26. dataBase string
  27. dataArgs string
  28. cancelData string
  29. confirmLabelKey string
  30. }
  31. // numericKeypad builds the shared digit pad: cancel, confirm, 1-9, clear, 0 and
  32. // backspace. Every numeric callback flow renders the same grid, so the layout
  33. // and the callback wording live here rather than once per flow.
  34. func (t *Tgbot) numericKeypad(spec numericKeypadSpec, inputNumber int) *telego.InlineKeyboardMarkup {
  35. value := strconv.Itoa(inputNumber)
  36. key := func(label, k string) telego.InlineKeyboardButton {
  37. return tu.InlineKeyboardButton(label).
  38. WithCallbackData(t.encodeQuery(spec.dataBase + "_in " + spec.dataArgs + value + " " + k))
  39. }
  40. return tu.InlineKeyboard(
  41. tu.InlineKeyboardRow(
  42. tu.InlineKeyboardButton(t.I18nBot("tgbot.buttons.cancel")).WithCallbackData(t.encodeQuery(spec.cancelData)),
  43. ),
  44. tu.InlineKeyboardRow(
  45. tu.InlineKeyboardButton(t.I18nBot(spec.confirmLabelKey, "Num=="+value)).
  46. WithCallbackData(t.encodeQuery(spec.dataBase+"_c "+spec.dataArgs+value)),
  47. ),
  48. tu.InlineKeyboardRow(key("1", "1"), key("2", "2"), key("3", "3")),
  49. tu.InlineKeyboardRow(key("4", "4"), key("5", "5"), key("6", "6")),
  50. tu.InlineKeyboardRow(key("7", "7"), key("8", "8"), key("9", "9")),
  51. tu.InlineKeyboardRow(key("🔄", "-2"), key("0", "0"), key("⬅️", "-1")),
  52. )
  53. }