import client from './api.js'
import { html } from './dom_utils.js'
const createEntityForm =
document.querySelector('#new-entity-form')
const updateEntityForm = document.querySelector('#entity-form')
const updateEntityBtn =
document.querySelector('#update-entity-btn')
const submitBtn = document.querySelector('#new-entity-btn')
const deleteBtn =
document.querySelector('#delete-entity-btn')
const referenceFields =
document.querySelectorAll('.reference-picker')
referenceFields.forEach(field => {
const entityList = field.querySelector('ul.entities')
const selectedElem = field.querySelector('.selected')
const refModel = field.dataset.ref
if (!refModel) {
throw new DOMException('Reference field is missing data-ref attribute.')
}
selectedElem?.addEventListener('click', async () => {
if (!entityList?.classList.contains('opened')) {
const entities = await client.findAll(refModel)
for (const entity of entities) {
const text =
entity['title'] || entity['name'] || entity[Object.keys(entity)[0]]
const entityListItem = html('li', {
classList: ['entity-list-item'],
text,
})
entityListItem.addEventListener('click', () => {
updateSelected(text, entity._id.$oid)
})
entityList?.append(entityListItem)
}
} else {
entityList.innerHTML = ''
}
entityList?.classList.toggle('opened')
})
function updateSelected(text: string, id: string) {
field.setAttribute('data-entity-id', id)
const value = selectedElem?.querySelector('.value')!
value.textContent = text
entityList?.classList.remove('opened')
entityList!.innerHTML = ''
}
})
submitBtn?.addEventListener('click', submit)
async function submit() {
const formData = new FormData(createEntityForm!)
const refs = [...referenceFields].reduce((all, field) => {
const ref = field.getAttribute('data-ref')!
all[ref] = {
$id: field.getAttribute('data-entity-id')!,
$ref: ref,
}
return all
}, {} as Record)
// TODO image fields
const collection = CONTEXT.model!.name
const data = { ...refs, ...Object.fromEntries(formData.entries()) }
await client.create(collection, data)
}
deleteBtn?.addEventListener('click', async () => {
const entityId = deleteBtn.getAttribute('data-entity-id')!
const { deleted } = await client.delete(CONTEXT.model!.name, entityId)
if (deleted) history.back()
})
updateEntityBtn?.addEventListener('click', async () => {
const entityId = updateEntityBtn.getAttribute('data-entity-id')!
const formData = new FormData(updateEntityForm!)
await client.update(
CONTEXT.model!.name,
entityId,
Object.fromEntries(formData.entries())
)
})