-
Notifications
You must be signed in to change notification settings - Fork 0
/
kbui.lua
134 lines (96 loc) · 2.61 KB
/
kbui.lua
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
local kbui = {}
kbui.elements = {}
function kbui.createElement(render, events)
local el = {render = render}
if type(events) == "function" then
el.events = events(el)
else
el.events = events
end
kbui.addElement(el)
return el
end
function kbui.handleEvent(event)
function handleEventFor(element, event)
if not element.events then
return
elseif type(element.events) == "function" then
element.events(unpack(event))
elseif type(element.events) == "table" then
local events1 = element.events[event[1]]
if type(events1) == "function" then
events1(unpack(event))
elseif type(events1) == "table" then
local events2 = events1[event[2]]
if type(events2) == "function" then
events2(unpack(event))
elseif type(events1['all']) == "function" then
events1['all'](unpack(event))
elseif type(element.events['all']) == "function" then
element.events['all'](unpack(event))
end
elseif type(element.events['all']) == "function" then
element.events['all'](unpack(event))
end
end
end
if kbui.selected then
return handleEventFor(kbui.selected, event)
end
for _,v in pairs(kbui.elements) do
handleEventFor(v, event)
end
end
function kbui.redraw()
term.clear()
for _,v in pairs(kbui.elements) do
if v.render then v.render(v == kbui.selected) end
end
end
function kbui.select(el)
kbui.selected = el
end
function kbui.unselect(el)
if kbui.selected == el then kbui.selected = nil end
end
function kbui.addElement(el)
kbui.elements[#kbui.elements + 1] = el
end
local running = false
function kbui.run()
running = true
while running do
kbui.redraw()
local event = {os.pullEvent()}
kbui.handleEvent(event)
end
end
function kbui.stop()
running = false
end
--- UI elements
kbui.components = {}
function kbui.components.textCenter(y, text, textColor, bgColor)
local comp = {}
comp.y = y or 1
comp.text = text or "unknown"
comp.textColor = textColor or colors.white
comp.bgColor = bgColor or colors.white
comp.x = 1
comp.width = "term"
function comp.render()
local width = comp.width
if not width or width == "term" then
-- Fill up remaining space
width = term.getSize() - comp.x + 1
end
local pad = (width - #comp.text) / 2
local fulltext = string.rep(" ", math.floor(pad)) .. comp.text .. string.ceil(" ", math.floor(pad))
term.setCursorPos(comp.x, comp.y)
term.setTextColor(comp.textColor)
term.setBackgroundColor(comp.bgColor)
term.write(fulltext)
end
return comp
end
return kbui,