const unescape = require('querystring').unescape
const titleCase = require('voca').titleCase
const titleize = require('titleize')
const doNotBreakAfterChars = ["'", "’"]
const toTitleCase = s => titleCase(titleize(s), doNotBreakAfterChars)
const commonHead = title => `
<!DOCTYPE html>
<html lang="en">
<head>
<title>${title ? title + ' — ' : ''}Title Caser</title>
<link href="https://unpkg.com/basscss-basic/index.css" rel="stylesheet">
<style>
body { padding: 0 2em; }
</style>
</head>
<body>
`
const commonHtml = `
<hr>
<p>
<form id="form" method="get" action="${process.env.RUNKIT_ENDPOINT_URL}">
<label for="sentence">Text to convert to title case:</label>
<input type="text" id="sentence" />
<button type="submit">Go!</button>
</form>
</p>
<script type="text/javascript">
const form = document.getElementById('form')
const text = document.getElementById('sentence')
function setFormAction () {
form.setAttribute('action', '${process.env.RUNKIT_ENDPOINT_URL}' + text.value)
}
text.addEventListener('input', setFormAction, false)
</script>
`
const commonFoot = `
</body></html>
`
exports.endpoint = (request, response) => {
let body
const url = new URL(request.url, process.env.RUNKIT_ENDPOINT_URL)
const path = url.pathname
if (path.length > 1) {
const title = toTitleCase(unescape(path.replace('/', '')))
body = commonHead(title) + `
<h1>${title}</h1>
` + commonHtml + commonFoot
} else {
body = commonHead() + `
<h1>Hi! This endpoint can title case sentences for you.</h1>
<p>
For example:<br/>
BACH sInGs lullabies! → Bach Sings Lullabies!
</p>
` + commonHtml + commonFoot
}
response.writeHead(200, {
'Content-Length': body.length,
'Content-Type': 'text/html; charset=utf-8' })
const document = body
response.write(document)
response.end()
}