function createCloseButton() { const container = document.createElement('div'); container.style.marginBottom = '1em'; container.style.display = 'flex'; container.style.justifyContent = 'flex-end'; const closeButton = document.createElement('a'); closeButton.classList.add('btn'); closeButton.classList.add('btn--close'); closeButton.href = '#'; closeButton.innerText = 'x close'; closeButton.style.marginLeft = 'auto'; closeButton.addEventListener('click', (e) => { e.preventDefault(); container.parentElement.remove(); }); container.append(closeButton); return container; } document.querySelectorAll('[data-delete]').forEach((el) => { el.addEventListener('click', (e) => { if (confirm('Are you sure? This cannot be undone.')) { let slug = e.target.dataset.delete; fetch(`/posts/${slug}`, { method: 'DELETE', }).then((r) => { r.json().then((data) => { if (data.success) { window.location = '/'; } }); }); } }); }); const previewButton = document.querySelector('[data-preview]'); if (previewButton) { previewButton.addEventListener('click', (e) => { e.preventDefault(); const currentPreview = document.querySelector('#preview'); if (currentPreview) { currentPreview.remove(); } const form = document.querySelector('#post-form'); const textarea = form.querySelector('[name=body]'); const previewContainer = document.createElement('div'); const contentContainer = document.createElement('div'); const content = textarea.value.trim(); previewContainer.id = 'preview'; if (content.length === 0) { return; } const closeButton = createCloseButton(); fetch('/preview', { method: 'POST', body: content, }).then((r) => r.json().then((r) => { contentContainer.innerHTML = r.body; previewContainer.append(closeButton); previewContainer.append(contentContainer); form.append(previewContainer); }), ); }); } document.querySelectorAll('[data-editor-helper]').forEach((helperBtn) => { helperBtn.addEventListener('click', (e) => { e.preventDefault(); const textarea = document.querySelector('[name=body]'); const currentValue = textarea.value; const start = textarea.selectionStart; const end = textarea.selectionEnd; const leftChunk = currentValue.substring(0, start); const rightChunk = currentValue.substring(end, textarea.value.length); let insertion = ''; let startOffset = 0; let endOffset = 0; switch (e.target.dataset.editorHelper) { case 'bold': insertion = '****'; startOffset = 2; endOffset = 2; break; case 'italic': insertion = '__'; startOffset = 1; endOffset = 1; break; case 'link': insertion = '[text](url)'; startOffset = 1; endOffset = 5; break; case 'code': insertion = '```js\n```' startOffset = 3; endOffset = 5; } textarea.value = leftChunk + insertion + rightChunk; textarea.focus(); textarea.selectionStart = start + startOffset; textarea.selectionEnd = end + endOffset; }) });