refactor: rewrite text wrapping

This commit is contained in:
2025-05-08 00:57:44 -03:00
parent a00403549a
commit e29b4e9190
+43 -45
View File
@@ -23,42 +23,28 @@ modem.open(HOST_CHANNEL)
--[[
helper functions
]]
function wrapText(text, width, prefixWidth)
function wrapText(text, maxWidth)
local lines = {}
local isFirstLine = true
for originalLine in text:gmatch("[^\n]+") do
local currentLine = ""
local currentLength = 0
if isFirstLine then
isFirstLine = false
currentLength = prefixWidth
for word in text:gmatch("%S+") do
if #currentLine + #word + 1 <= maxWidth then
currentLine = currentLine .. (currentLine == "" and "" or " ") .. word
else
if currentLine == "" then
while #word > maxWidth do
table.insert(lines, word:sub(1, maxWidth))
word = word:sub(maxWidth + 1)
end
for word in originalLine:gmatch("%S+") do
if currentLength + #word > width and currentLength > 0 then
currentLine = word
else
table.insert(lines, currentLine)
currentLine = word
currentLength = #word
else
if currentLength > 0 then
currentLine = currentLine .. " " .. word
currentLength = currentLength + 1 + #word
else
currentLine = word
currentLength = #word
end
end
end
if currentLength > 0 then
if currentLine ~= "" then
table.insert(lines, currentLine)
end
end
return lines
end
@@ -263,38 +249,50 @@ function drawLogs(x0, y0, x1, y1)
term.setTextColor(format["FG"])
local prefix = ("[%s] "):format(entry.type)
term.write(prefix)
local prefixLength = #prefix
local maxMessageWidth = w - prefixLength
if maxMessageWidth <= 0 then maxMessageWidth = 1 end
local lines = wrapText(entry.message, w, prefix:len())
local wrappedMessage = wrapText(entry.message, maxMessageWidth)
if not format["AffectContent"] then
term.setBackgroundColor(prevColourBg)
term.setTextColor(prevColourFg)
local messageBG, messageFG
if format.AffectContent then
messageBG = format.BG
messageFG = format.FG
else
messageBG = prevColourBg
messageFG = prevColourFg
end
local isFirstLine = false
for _, line in pairs(lines) do
for lineIdx, line in ipairs(wrappedMessage) do
if drawnLines > h then break end
term.setCursorPos(1, y1 - drawnLines)
local currentY = y1 - drawnLines
term.setCursorPos(1, currentY)
if isFirstLine then
term.setCursorPos(prefix:len() + 1, y1 - drawnLines)
isFirstLine = false
end
if lineIdx == 1 then
term.setBackgroundColor(format.BG)
term.setTextColor(format.FG)
term.write(prefix)
term.setBackgroundColor(messageBG)
term.setTextColor(messageFG)
term.write(line)
else
term.setBackgroundColor(messageBG)
term.setTextColor(messageFG)
term.write((" "):rep(prefixLength))
term.write(line)
end
term.setBackgroundColor(messageBG)
term.setCursorPos(1 + prefixLength + #line, currentY)
term.clearLine()
drawnLines = drawnLines + 1
end
if format["AffectContent"] then
term.setBackgroundColor(prevColourBg)
term.setTextColor(prevColourFg)
end
drawnLines = drawnLines + 1
end
term.setBackgroundColor(prevColourBg)