CycleButton.lua 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. local Button = require('elements/Button')
  2. ---@alias CycleState {value: any; icon: string; active?: boolean}
  3. ---@alias CycleButtonProps {prop: string; states: CycleState[]; anchor_id?: string; tooltip?: string}
  4. ---@class CycleButton : Button
  5. local CycleButton = class(Button)
  6. ---@param id string
  7. ---@param props CycleButtonProps
  8. function CycleButton:new(id, props) return Class.new(self, id, props) --[[@as CycleButton]] end
  9. ---@param id string
  10. ---@param props CycleButtonProps
  11. function CycleButton:init(id, props)
  12. local is_state_prop = itable_index_of({'shuffle'}, props.prop)
  13. self.prop = props.prop
  14. self.states = props.states
  15. Button.init(self, id, props)
  16. self.icon = self.states[1].icon
  17. self.active = self.states[1].active
  18. self.current_state_index = 1
  19. self.on_click = function()
  20. local new_state = self.states[self.current_state_index + 1] or self.states[1]
  21. local new_value = new_state.value
  22. if self.owner then
  23. mp.commandv('script-message-to', self.owner, 'set', self.prop, new_value)
  24. elseif is_state_prop then
  25. if itable_index_of({'yes', 'no'}, new_value) then new_value = new_value == 'yes' end
  26. set_state(self.prop, new_value)
  27. else
  28. mp.set_property(self.prop, new_value)
  29. end
  30. end
  31. local function handle_change(name, value)
  32. value = type(value) == 'boolean' and (value and 'yes' or 'no') or tostring(value or '')
  33. local index = itable_find(self.states, function(state) return state.value == value end)
  34. self.current_state_index = index or 1
  35. self.icon = self.states[self.current_state_index].icon
  36. self.active = self.states[self.current_state_index].active
  37. request_render()
  38. end
  39. local prop_parts = split(self.prop, '@')
  40. if #prop_parts == 2 then -- External prop with a script owner
  41. self.prop, self.owner = prop_parts[1], prop_parts[2]
  42. self['on_external_prop_' .. self.prop] = function(_, value) handle_change(self.prop, value) end
  43. handle_change(self.prop, external[self.prop])
  44. elseif is_state_prop then -- uosc's state props
  45. self['on_prop_' .. self.prop] = function(self, value) handle_change(self.prop, value) end
  46. handle_change(self.prop, state[self.prop])
  47. else
  48. self:observe_mp_property(self.prop, 'string', handle_change)
  49. end
  50. end
  51. return CycleButton