cc/listview.lua

110 lines
2.5 KiB
Lua

local backingList = {}
local length = 0
local paginationPos = 1
local frame = term.current()
local drawEntry = nil
local function setTerm(termlike)
frame = termlike
end
local function setDrawEntryFunc(drawLineFunc)
drawEntry = drawLineFunc
end
local function redrawEntry(idx)
local tw, th = frame.getSize()
if idx >= paginationPos and idx-paginationPos <= th then
frame.setCursorPos(1, idx-paginationPos+1)
if drawEntry then
drawEntry(frame, backingList[idx])
else
frame.setBackgroundColor(colors.red)
frame.clearLine()
frame.setBackgroundColor(colors.black)
end
end
end
local function itemAt(idx)
return backingList[idx]
end
local function updateItemAt(idx, item)
backingList[idx] = item
if idx > length then
length = idx
end
redrawEntry(idx)
end
local function getLength()
return length
end
local function clearFrom(idx)
local tw, th = frame.getSize()
for j = length, idx, -1 do
backingList[j] = nil
end
length = idx
for y = idx-paginationPos+1, th, 1 do
frame.setCursorPos(1, y)
frame.clearLine()
end
end
local function redraw()
if drawEntry then
local tw, th = frame.getSize()
local backingIdx = paginationPos
for idx = 1, th, 1 do
frame.setCursorPos(1, idx)
if backingList[backingIdx] == nil then
frame.clearLine()
else
drawEntry(frame, backingList[backingIdx])
end
backingIdx = backingIdx + 1
end
else
frame.setBackgroundColor(colors.red)
frame.clear()
frame.setBackgroundColor(colors.black)
end
end
local function updatePage(scrollPos)
if scrollPos ~= paginationPos then
paginationPos = scrollPos
redraw()
end
end
local function updatePartial(filter)
if drawEntry then
local tw, th = frame.getSize()
local backingIdx = paginationPos
for idx = 1, th, 1 do
frame.setCursorPos(1, idx)
if backingList[backingIdx] ~= nil and filter(backingList[backingIdx]) then
drawEntry(frame, backingList[backingIdx])
end
backingIdx = backingIdx + 1
end
end
end
return {
setTerm=setTerm,
setDrawEntryFunc=setDrawEntryFunc,
itemAt=itemAt,
updateItemAt=updateItemAt,
length=getLength,
clearFrom=clearFrom,
redraw=redraw,
updatePage=updatePage,
updatePartial=updatePartial,
}