list.lua 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. local text = require "text"
  2. local list = text:extend()
  3. list.value_index = 1
  4. list.editable = true
  5. list.selectable = true
  6. list.loop = true
  7. list.format = "%s"
  8. list.event_fn = function () end
  9. -- lynx.observer(variable, key, format, params)
  10. -- values: table
  11. -- event_fn: function (self, value)
  12. -- params: table
  13. --
  14. function list:new(values, event_fn, params)
  15. text.new(self, nil, params)
  16. if event_fn then
  17. self.event_fn = event_fn
  18. end
  19. self.values = values or {}
  20. self.value = self.values[self.value_index]
  21. self.selected = false
  22. self.text = self:format_fn(false)
  23. end
  24. function list:format_fn(locked)
  25. local str = string.format(self.format, self.value)
  26. if locked then
  27. if self.value_index > 1 or self.loop then
  28. str = "< " .. str
  29. end
  30. if self.value_index < #self.values or self.loop then
  31. str = str .. " >"
  32. end
  33. end
  34. return str
  35. end
  36. function list:input(menu, key, state)
  37. if (not self.allow_repeat and state == "down") or state == "up" then
  38. return
  39. end
  40. if self.editable then
  41. if menu.funcs.simple_key(key) == "enter" and state == "pressed" then
  42. self.selected = not self.selected
  43. menu.locked = self.selected
  44. self.text = self:format_fn(self.selected)
  45. elseif self.selected then
  46. if menu.funcs.simple_key(key) == "left" then
  47. self.value_index = self.value_index - 1
  48. if self.value_index == 0 then
  49. self.value_index = self.loop and #self.values or 1
  50. end
  51. self.value = self.values[self.value_index]
  52. self:event_fn(menu, self.value)
  53. self.text = self:format_fn(self.selected)
  54. elseif menu.funcs.simple_key(key) == "right" then
  55. self.value_index = self.value_index + 1
  56. if self.value_index == #self.values + 1 then
  57. self.value_index = self.loop and 1 or #self.values
  58. end
  59. self.value = self.values[self.value_index]
  60. self:event_fn(menu, self.value)
  61. self.text = self:format_fn(self.selected)
  62. end
  63. end
  64. end
  65. end
  66. function list:mouse(menu, x, y, btn)
  67. if btn == 1 then
  68. self:input(menu, "enter", "pressed")
  69. end
  70. end
  71. function list:__tostring()
  72. return "lynx.list"
  73. end
  74. return list