108 lines
2.6 KiB
Lua
108 lines
2.6 KiB
Lua
local utf8 = require("utf8")
|
|
local https=require('https')
|
|
local htmlparser = require("htmlparser")
|
|
|
|
local url='https://neocities.org'
|
|
local textInput = ''
|
|
|
|
function love.load()
|
|
-- Set up a Love2D font for displaying the text
|
|
font = love.graphics.newFont(24)
|
|
love.graphics.setFont(font)
|
|
love.graphics.setColor(1, 1, 1)
|
|
|
|
-- enable key repeat so backspace can be held down to trigger love.keypressed multiple times.
|
|
love.keyboard.setKeyRepeat(true)
|
|
|
|
grabText()
|
|
end
|
|
|
|
function love.draw()
|
|
-- Draw the website's text on the Love2D window
|
|
love.graphics.setColor(1, 1, 1)
|
|
love.graphics.printf(screenText, 0, 40, love.graphics.getWidth(), "left")
|
|
|
|
drawInputBox()
|
|
end
|
|
|
|
function grabText()
|
|
rawHTML = makeRequest(url)
|
|
screenText = parseWebsite(rawHTML)
|
|
end
|
|
|
|
function parseWebsite(html)
|
|
|
|
local root = htmlparser.parse(html,1000) --1000 is the default
|
|
local head = root:select("h1")
|
|
local out
|
|
|
|
if head[1] then
|
|
local headText = stripText(head[1]:getcontent()) or ""--first h1 on page
|
|
out = headText .. "\n"
|
|
else
|
|
out = ""
|
|
end
|
|
|
|
local elements = root:select("p")
|
|
|
|
--local out = headText
|
|
for _,e in ipairs(elements) do
|
|
out = out .. stripText(e:getcontent()) .. "\n"
|
|
end
|
|
|
|
return out
|
|
end
|
|
|
|
function stripText(parsed)
|
|
|
|
stripped = parsed:gsub('%—','') --remove an html entity bothering me
|
|
stripped = stripped:gsub('%b<>', '') --remove tags
|
|
stripped = stripped:match'^%s*(.*)' --remove leading spaces
|
|
|
|
return stripped
|
|
end
|
|
|
|
function makeRequest(url)
|
|
local code, body, headers = https.request(url)
|
|
print('statusCode ', code)
|
|
--for index,value in pairs(headers) do
|
|
-- print("\t",index, value)
|
|
--end
|
|
|
|
return body
|
|
end
|
|
|
|
function love.textinput (text)
|
|
--if textbox.active then
|
|
-- textbox.text = textbox.text .. text
|
|
--end
|
|
textInput = textInput .. text
|
|
end
|
|
|
|
function love.keypressed(key)
|
|
if key == "backspace" then
|
|
-- get the byte offset to the last UTF-8 character in the string.
|
|
local byteoffset = utf8.offset(textInput, -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).
|
|
textInput = string.sub(textInput, 1, byteoffset - 1)
|
|
end
|
|
end
|
|
|
|
if key == 'return' then
|
|
url=textInput --obviously need to add in validation later
|
|
grabText()
|
|
end
|
|
end
|
|
|
|
function drawInputBox()
|
|
--empty input box
|
|
love.graphics.rectangle('fill', 5,0, love.graphics.getWidth(),40)
|
|
|
|
--text input starter
|
|
love.graphics.setColor(0, 0, 0)
|
|
love.graphics.print("$ "..textInput, 10, 10)
|
|
end
|