Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add TextWrap function to sh_formatting #59

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions lua/pixelui/core/sh_formatting.lua
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@

local floor, format = math.floor, string.format
function PIXEL.FormatTime(time)
if not time then return end

Check warning on line 70 in lua/pixelui/core/sh_formatting.lua

View workflow job for this annotation

GitHub Actions / lint / lint

"Syntax inconsistency"

Inconsistent use of '!' and 'not'

local s = time % 60
time = floor(time / 60)
Expand All @@ -91,3 +91,42 @@

return format("%im %is", m, s)
end

function PIXEL.TextWrap(str, font, maxWidth)
if (!text) then

Check warning on line 96 in lua/pixelui/core/sh_formatting.lua

View workflow job for this annotation

GitHub Actions / lint / lint

"Syntax inconsistency"

Inconsistent use of '!' and 'not'

Check warning on line 96 in lua/pixelui/core/sh_formatting.lua

View workflow job for this annotation

GitHub Actions / lint / lint

"Trailing whitespace"

Trailing whitespace
return ""

Check warning on line 97 in lua/pixelui/core/sh_formatting.lua

View workflow job for this annotation

GitHub Actions / lint / lint

"Trailing whitespace"

Trailing whitespace
end

local totalWidth = 0

surface.SetFont(font)

local spaceWidth = surface.GetTextSize(' ')
str = str:gsub("(%s?[%S]+)", function(word)
local char = string.sub(word, 1, 1)
if char == "\n" or char == "\t" then
totalWidth = 0
end

local wordlen = surface.GetTextSize(word)
totalWidth = totalWidth + wordlen

if wordlen >= maxWidth then
local splitWord, splitPoint = charWrap(word, maxWidth - (totalWidth - wordlen), maxWidth)
totalWidth = splitPoint
return splitWord
elseif totalWidth < maxWidth then
return word
end

if char == ' ' then
totalWidth = wordlen - spaceWidth
return '\n' .. string.sub(word, 2)
end

totalWidth = wordlen
return '\n' .. word
end)

return str
end
Loading