wiki-mad-libs/web/script.js

104 lines
2.9 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}" class="token-input" name="token-${token.id}">
</p>
`
}
})
document.getElementById('inputs').innerHTML = inputs
const urlParams = new URL(window.location.toLocaleString()).searchParams
if(urlParams.has('stored')) {
try {
let storedInputs = JSON.parse(atob(urlParams.get('stored')))
if(storedInputs.h !== article.hash) {
showError("Unable to use shared link because it's for an old article, and well, time makes fools of us all.")
}
else {
document.querySelectorAll('.token-input').forEach(function(tokenInput) {
let index = tokenInput.id.split('-')[1]
tokenInput.value = storedInputs.i[index]
});
}
}
catch(err) {
showError("Unable to parse shared link.")
}
}
}
function showError(errorMessage) {
errorDiv = document.getElementById('error')
errorDiv.innerHTML = errorMessage;
errorDiv.style.display = 'block'
}
function makeSharableLink(article) {
let userInputs = {}
document.querySelectorAll('.token-input').forEach(function(tokenInput) {
let index = tokenInput.id.split('-')[1]
userInputs[index] = tokenInput.value
});
let storedInputs = {h: article.hash, i: userInputs}
let url = new URL(window.location.toLocaleString())
url.searchParams.set('stored', btoa(JSON.stringify(storedInputs)))
return(url.toLocaleString())
}
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('original-article-link').href = article.url
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('sharable-link').href = makeSharableLink(article)
document.getElementById('article').classList.add('visible')
}
createInputs(article)
document.addEventListener('click', function (event) {
if (event.target.matches('#show-article')) {
event.preventDefault()
showArticle(article)
}
}, false);