cc/tabview.lua

91 lines
2.2 KiB
Lua
Raw Normal View History

2024-06-01 14:20:00 +00:00
local parent = term.current()
local allTabs = {}
local tabOrder = {}
local currentTab = nil
local function setTerm(new_term)
parent = new_term
end
local function addTab(tab, order_idx)
assert(tab.name, "tab needs a unique name")
local isCurrentTab = currentTab == nil
if isCurrentTab then
currentTab = tab
end
local tw, th = parent.getSize()
tab.window = window.create(parent, 1, 1, tw, th, isCurrentTab)
tab.scrollPos = 1
tab.pageDown = function ()
local tw, th = tab.window.getSize()
tab.scrollPos = tab.scrollPos + th
end
tab.pageUp = function ()
local tw, th = tab.window.getSize()
tab.scrollPos = math.max(1, tab.scrollPos-th)
end
allTabs[tab.name] = tab
tabOrder[order_idx] = tab.name
return tab
end
local function showTab(name)
if currentTab ~= nil then
currentTab.window.setVisible(false)
end
currentTab = allTabs[name]
if currentTab == nil then
-- backwards compatible idx lookup
currentTab = allTabs[tabOrder[name]]
end
assert(currentTab ~= nil, "tab name '" .. name .. "' was not registered")
currentTab.window.setVisible(true)
end
local function switchTab()
assert(#allTabs > 0, "tabs need to be registered in order to switch tabs")
local idx = 0
if currentTab ~= nil then
currentTab.window.setVisible(false)
idx = tabOrder[currentTab.name]
end
idx = idx + 1
if idx > #allTabs then
idx = 1
end
currentTab = allTabs[tabOrder[idx]]
currentTab.window.setVisible(true)
end
local function getCurrentTab()
return currentTab
end
local function getAllTabs()
return allTabs
end
local function updateSize()
local tw, th = parent.getSize()
for name, tab in pairs(allTabs) do
tab.window.reposition(1, 1, tw, th)
end
end
local function onTouch(touch_x, touch_y)
if currentTab ~= nil then
currentTab.onTouch(currentTab, touch_x, touch_y)
end
end
return {
setTerm=setTerm,
addTab=addTab,
showTab=showTab,
switchTab=switchTab,
updateSize=updateSize,
onTouch=onTouch,
currentTab=getCurrentTab,
allTabs=getAllTabs,
}