dcearth/ui/textinput.lua

65 lines
1.8 KiB
Lua

local love = assert( love )
local utf8 = require("utf8")
local modal = require( "ui.modal" )
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
-- 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).
text = string.sub(text, 1, byteoffset - 1)
end
end
if code == "escape" then
return t:stop()
end
end
return t