/**
* @file editor.js
* @author Ken Grimes
* @license AGPL-3.0
* @copyright 2018 - Ken Grimes
* @summmary live edit front-end for fediblog
*/
'use strict'
const apiURL = document.location.origin + '/api/'
const baseURL = document.location.origin
const articleButtons = []
const addButton = (anchor, name, fn) => {
const button = document.createElement('button')
const buttonText = document.createTextNode(name)
button.appendChild(buttonText)
button.onclick = () => fn(button)
if (anchor.firstChild)
anchor.insertBefore(button,anchor.firstChild)
else
anchor.appendChild(button)
return button
}
const logout = () => {
document.cookie = 'live-edit=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;'
window.location.reload(true)
}
const doDelete = (btn) => {
const element = btn.parentElement
const fileName = 'content/' + element.id
if (window.confirm(`Do you really want to delete ${element.id}?`))
fetch(apiURL + fileName, {credentials: 'same-origin', method: 'DELETE'}).then((resp) => {
if (resp.ok)
window.location.href = window.location.href + ".."
else if (resp.status === 401)
logout()
else
console.log(resp)
})
}
const doCancel = (btn) => {
const element = btn.parentElement
element.innerHTML = element.oldHTML
}
const doCommit = (btn) => {
const element = btn.parentElement
const fileName = 'content/' + element.id
const textArea = element.getElementsByTagName('textarea').item(0)
fetch(apiURL + fileName, {credentials: 'same-origin', method: 'POST', body: textArea.value}).then((resp) => {
if (resp.ok)
window.location.reload(true)
else if (resp.status === 401)
logout()
else
console.log(resp)
})
}
const doCommitPost = (btn) => {
const element = btn.parentElement
const nameBox = element.getElementsByTagName('input').item(0)
if (nameBox.value === '') {
window.alert('Filename is required')
return
}
const secMatch = window.location.href.match(new RegExp(baseURL + '(.*/)'))
const section = secMatch ? secMatch[1] : ''
const fileName = 'content/' + section + nameBox.value + '.md'
const textArea = element.getElementsByTagName('textarea').item(0)
fetch(apiURL + fileName, {credentials: 'same-origin', method: 'POST', body: textArea.value}).then((resp) => {
if (resp.ok)
window.location.reload(true)
else if (resp.status === 401)
logout()
else
console.log(resp)
})
}
const doPost = (btn) => {
const element = btn.parentElement
element.oldHTML = element.innerHTML
element.innerHTML =
'' +
'
' +
'Filename: ' +
''
}
const doEdit = (btn) => {
const element = btn.parentElement
const fileName = 'content/' + element.id
fetch(apiURL + fileName, {credentials: 'same-origin'}).then((resp) => {
if (resp.status === 401)
logout()
else if (resp.ok)
resp.text().then((txt) => {
element.oldHTML = element.innerHTML
element.innerHTML =
'' +
'' +
'
' +
''
})
else
console.log(resp)
})
}
const editTools = () => {
const article = document.body.getElementsByTagName('article').item(0)
articleButtons.push(addButton(article, 'new page', doPost))
articleButtons.push(addButton(article, 'edit', doEdit))
}