(function() { var previewBtn = document.getElementById('preview-btn'); var uploadBtn = document.getElementById('upload-btn'); var imgFile = document.getElementById('img-file'); var textarea = document.getElementById('content'); var output = document.getElementById('preview-output'); var uploadStatus = document.getElementById('upload-status'); if (!textarea) return; // --- Preview --- function refreshPreview() { var fd = new FormData(); fd.append('content', textarea.value); fetch('/admin/preview', { method: 'POST', body: fd }) .then(function(r) { return r.text(); }) .then(function(html) { output.innerHTML = html; }) .catch(function() { output.innerHTML = '
Preview failed.
'; }); } if (previewBtn) previewBtn.addEventListener('click', refreshPreview); if (textarea.value.trim()) { refreshPreview(); } // --- Image upload --- if (uploadBtn) uploadBtn.addEventListener('click', function() { imgFile.click(); }); if (imgFile) imgFile.addEventListener('change', function() { if (!this.files.length) return; var file = this.files[0]; var fd = new FormData(); fd.append('image', file); uploadStatus.textContent = 'Uploading\u2026'; uploadBtn.disabled = true; fetch('/admin/upload', { method: 'POST', body: fd }) .then(function(r) { return r.json(); }) .then(function(data) { if (data.error) { uploadStatus.textContent = 'Error: ' + data.error; return; } var pos = textarea.selectionStart; var before = textarea.value.substring(0, pos); var after = textarea.value.substring(textarea.selectionEnd); textarea.value = before + data.markdown + after; textarea.selectionStart = textarea.selectionEnd = pos + data.markdown.length; textarea.focus(); uploadStatus.textContent = 'Inserted: ' + data.url; setTimeout(function() { uploadStatus.textContent = ''; }, 3000); }) .catch(function() { uploadStatus.textContent = 'Upload failed.'; }) .finally(function() { uploadBtn.disabled = false; imgFile.value = ''; }); }); })();