async function RenderMarkdownList(mountPoint) {
const response = await fetch(`/api/v1/markdowns`)
const markdownsIds = await response.json()
const markdowns = await Promise.all(
markdownsIds.markdowns.map(async it => {
return await (await fetch(`/api/v1/markdowns/${it}`)).json()
})
)
console.log(markdowns)
mountPoint.innerHTML = `
Create new
`
const container = mountPoint.querySelector('.objects_list_container')
const createButton = mountPoint.querySelector('.objects_list_create_new')
for (const markdown of markdowns) {
makeMarkdownLink(container, markdown, createButton)
}
createButton.addEventListener('click', async (e) => {
const newBoard = await createNewMarkdown()
makeMarkdownLink(container, newBoard, createButton, true)
})
}
function makeMarkdownLink(mountPoint, markdown, before, focus) {
const div = document.createElement('div')
div.innerHTML = `
Edit
`
const button = div.querySelector('.objects_list_item__save_button')
const text = div.querySelector('.objects_list_item__text')
const link = div.querySelector('.objects_list_item__link')
text.textContent = markdown.name || ''
let editing = false
const saveOnEnter = (event) => {
if (event.key === "Enter") {
event.preventDefault();
button.click();
}
}
const startEdit = () => {
text.focus()
text.addEventListener("keypress", saveOnEnter)
button.innerHTML = 'Save'
text.contentEditable = "true"
editing = true
}
button.addEventListener('click', async (e) => {
if (editing) {
button.innerHTML = 'Edit'
text.contentEditable = "false"
editing = false
text.removeEventListener("keypress", saveOnEnter)
markdown.name = text.textContent
text.textContent = text.textContent
const response = await fetch(`/api/v1/markdowns/${markdown.id}`,
{
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: "PUT",
body: JSON.stringify(markdown)
})
const result = await response.text();
console.log(result)
} else {
startEdit()
}
})
link.addEventListener('click', (e) => {
if (editing) return
console.log("link")
window.location.href = `/markdowns/${markdown.id}`
})
mountPoint.insertBefore(div, before)
if (focus)
startEdit()
}
async function createNewMarkdown() {
const response = await fetch(`/api/v1/markdowns`,
{
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: "PUT"
})
const result = await response.json();
return result
}