dcearth/ui/textinput.lua

65 lines
1.8 KiB
Lua
Raw Normal View History

2024-04-29 01:21:32 +00:00
local love = assert( love )
local utf8 = require("utf8")
local modal = require( "ui.modal" )
2024-04-29 01:21:32 +00:00
local t = modal.new{ }
function t.setCurrentModal( fields )
t.currentModal = assert( fields )
t.currentIdx = 1
return t:start()
end
function t.draw()
if not t.currentModal then return end
love.graphics.setColor( 0, 0, 0, 0.3 )
love.graphics.rectangle("fill", 0, 0, love.graphics.getDimensions())
-- other fields
for i, field in ipairs( t.currentModal ) do
love.graphics.setColor( 1, 1, 1, 0.2 )
local mode = (i == t.currentIdx) and "fill" or "line"
love.graphics.rectangle( mode, 200, i * 28, 200, 14, 4 )
love.graphics.setColor( 1, 1, 1, 1 )
love.graphics.print( field.name, 8, i * 28 )
love.graphics.print( field.value, 216, i * 28 )
end
end
function t.textinput( char )
if t.currentModal then
local field = t.currentModal.currentFieldIdx
t.currentModal.currentField.value = t.currentModal.currentField.value .. char
end
end
function t.keypressed(key, code, isRepeat)
if code == "down" then
t.currentIdx = t.currentIdx + 1
if t.currentIdx > #(t.currentModal) then
t.currentIdx = 1
end
elseif code == "up" then
t.currentIdx = t.currentIdx - 1
if t.currentIdx < 1 then
t.currentIdx = #(t.currentModal)
end
end
if key == "backspace" then
local text = t.currentModal.currentField
2024-04-29 01:21:32 +00:00
-- get the byte offset to the last UTF-8 character in the string.
local byteoffset = utf8.offset(text, -1)
if byteoffset then
-- remove the last UTF-8 character.
-- string.sub operates on bytes rather than UTF-8 characters, so we couldn't do string.sub(text, 1, -2).
2024-07-20 03:09:53 +00:00
t.currentModal.currentField = text:sub( 1, byteoffset - 1)
2024-04-29 01:21:32 +00:00
end
end
if code == "escape" then
2024-04-29 01:21:32 +00:00
return t:stop()
end
end
return t