wiki-mad-libs/web/script.js

60 lines
1.6 KiB
JavaScript

function createInputs(article) {
inputs = ''
article.tokens.forEach(function(token) {
if(token.adlib_tag) {
inputs += `
<p>
<label for="token_${token.id}">${token.adlib_tag}</label>
<input type="text" id="token_${token.id}" name="token_${token.id}">
</p>
`
}
})
document.getElementById('inputs').innerHTML = inputs
}
function showArticle(article) {
const noSpaceBeforeTags = new Set(['.', ',', ')', ';', ':', '!', '?', "''", 'POS'])
const noSpaceBeforeTokens = new Set(["n't", ']'])
const noSpaceAfterTags = new Set(['(', '``'])
const noSpaceAfterTokens = new Set(['['])
document.getElementById('title').innerHTML = article.title
document.getElementById('link').innerHTML = `[ <a href='${article.url}'>Original Article</a> ]`
let output = ''
let spaceBefore = false
article.tokens.forEach(function(token) {
if(spaceBefore && !noSpaceBeforeTags.has(token.tag) && !noSpaceBeforeTokens.has(token.token)) {
output += ' '
}
spaceBefore = true
let adlibInput = document.getElementById(`token_${token.id}`);
if(adlibInput && adlibInput.value) {
output += `<strong>${adlibInput.value}</strong>`
}
else {
output += `${token.token}`
}
if(noSpaceAfterTags.has(token.tag) || noSpaceAfterTokens.has(token.token)) {
spaceBefore = false
}
})
document.getElementById('summary').innerHTML = output
document.getElementById('article').classList.add('visible')
}
createInputs(article)
document.addEventListener('click', function (event) {
if (event.target.matches('#show-article')) {
event.preventDefault()
showArticle(article)
}
}, false);