| 1 |
(function() { |
| 2 |
var itemId = document.getElementById('wizard-item-sections-cfg').dataset.itemId; |
| 3 |
|
| 4 |
document.getElementById('add-section-btn').addEventListener('click', function() { |
| 5 |
var title = document.getElementById('new-section-title').value.trim(); |
| 6 |
var body = document.getElementById('new-section-body').value; |
| 7 |
var status = document.getElementById('section-add-status'); |
| 8 |
if (!title) { status.textContent = 'Title is required'; return; } |
| 9 |
this.disabled = true; |
| 10 |
status.textContent = ''; |
| 11 |
|
| 12 |
fetch('/api/items/' + itemId + '/sections', { |
| 13 |
method: 'POST', |
| 14 |
headers: Object.assign({'Content-Type': 'application/json'}, csrfHeaders()), |
| 15 |
body: JSON.stringify({ title: title, body: body }) |
| 16 |
}) |
| 17 |
.then(function(res) { |
| 18 |
if (!res.ok) return res.json().then(function(d) { throw new Error(d.error || 'Failed'); }); |
| 19 |
return res.json(); |
| 20 |
}) |
| 21 |
.then(function(sec) { |
| 22 |
var row = document.createElement('div'); |
| 23 |
row.className = 'section-row'; |
| 24 |
row.dataset.id = sec.id; |
| 25 |
row.innerHTML = |
| 26 |
'<span class="section-row-title"></span>' + |
| 27 |
'<span class="section-row-length"></span>' + |
| 28 |
'<button type="button" class="btn-secondary section-delete-btn"></button>'; |
| 29 |
row.querySelector('.section-row-title').textContent = sec.title; |
| 30 |
row.querySelector('.section-row-length').textContent = (sec.body || '').length + ' chars'; |
| 31 |
var delBtn = row.querySelector('.section-delete-btn'); |
| 32 |
delBtn.dataset.id = sec.id; |
| 33 |
delBtn.textContent = 'Delete'; |
| 34 |
document.getElementById('sections-list').appendChild(row); |
| 35 |
attachDeleteHandler(delBtn); |
| 36 |
document.getElementById('new-section-title').value = ''; |
| 37 |
document.getElementById('new-section-body').value = ''; |
| 38 |
}) |
| 39 |
.catch(function(err) { status.textContent = err.message; }) |
| 40 |
.finally(function() { document.getElementById('add-section-btn').disabled = false; }); |
| 41 |
}); |
| 42 |
|
| 43 |
function attachDeleteHandler(btn) { |
| 44 |
btn.addEventListener('click', function() { |
| 45 |
var id = this.dataset.id; |
| 46 |
var row = this.closest('.section-row'); |
| 47 |
fetch('/api/sections/' + id, { method: 'DELETE', headers: csrfHeaders() }) |
| 48 |
.then(function(res) { if (res.ok) row.remove(); else showToast('Failed to delete'); }) |
| 49 |
.catch(function() { showToast('Failed to delete'); }); |
| 50 |
}); |
| 51 |
} |
| 52 |
|
| 53 |
document.querySelectorAll('.section-delete-btn').forEach(attachDeleteHandler); |
| 54 |
})(); |
| 55 |
|