cc/tabview.lua

105 lines
2.5 KiB
Lua
Raw Normal View History

local winhlp = require "winhlp"
local frame = term.current()
2024-06-01 14:46:21 +00:00
local tabCount = 0
2024-06-01 14:20:00 +00:00
local allTabs = {}
local tabOrder = {}
local currentTab = nil
local function setTerm(termlike)
frame = termlike
2024-06-01 14:20:00 +00:00
end
local function addTab(tab, orderIdx)
2024-06-01 14:20:00 +00:00
assert(tab.name, "tab needs a unique name")
local isCurrentTab = currentTab == nil
if isCurrentTab then
currentTab = tab
end
local tw, th = frame.getSize()
tab.window = window.create(frame, 1, 1, tw, th, isCurrentTab)
tab.setTerm(tab.window)
2024-06-01 14:20:00 +00:00
tab.scrollPos = 1
tab.pageDown = function()
2024-06-01 14:20:00 +00:00
local tw, th = tab.window.getSize()
tab.scrollPos = tab.scrollPos + th
end
tab.pageUp = function()
2024-06-01 14:20:00 +00:00
local tw, th = tab.window.getSize()
tab.scrollPos = math.max(1, tab.scrollPos - th)
2024-06-01 14:20:00 +00:00
end
allTabs[tab.name] = tab
tabOrder[orderIdx] = tab.name
2024-06-01 14:46:21 +00:00
tabCount = tabCount + 1
2024-06-01 14:20:00 +00:00
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()
2024-06-01 14:46:21 +00:00
assert(tabCount > 0, "tabs need to be registered in order to switch tabs")
2024-06-01 14:20:00 +00:00
local idx = 0
if currentTab ~= nil then
currentTab.window.setVisible(false)
2024-06-01 14:49:01 +00:00
for i, name in pairs(tabOrder) do
if name == currentTab.name then
idx = i
break
end
end
2024-06-01 14:20:00 +00:00
end
idx = idx + 1
2024-06-01 14:46:21 +00:00
if idx > tabCount then
2024-06-01 14:20:00 +00:00
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 = frame.getSize()
2024-06-01 14:20:00 +00:00
for name, tab in pairs(allTabs) do
tab.window.reposition(1, 1, tw, th)
end
end
local function onTouch(touchX, touchY)
if currentTab ~= nil and
winhlp.contains(currentTab.window, touchX, touchY) and
currentTab.onTouch(currentTab, winhlp.translate(currentTab.window, touchX, touchY)) then
return true
2024-06-01 14:20:00 +00:00
end
return false
2024-06-01 14:20:00 +00:00
end
return {
setTerm = setTerm,
addTab = addTab,
showTab = showTab,
switchTab = switchTab,
updateSize = updateSize,
onTouch = onTouch,
currentTab = getCurrentTab,
allTabs = getAllTabs,
}