392 lines
20 KiB
Plaintext
392 lines
20 KiB
Plaintext
---
|
|
import AdminLayout from '../../layouts/AdminLayout.astro';
|
|
---
|
|
|
|
<AdminLayout title="Write Post">
|
|
<p slot="header-subtitle" id="post-status" class="text-subtext1 mt-2 text-sm md:text-base">Create/Edit post.</p>
|
|
|
|
<div slot="header-actions" class="flex gap-4 w-full">
|
|
<button id="delete-btn" class="hidden text-red hover:bg-red/10 px-6 py-3 rounded-lg transition-colors font-bold border border-red/20 w-full md:w-auto">
|
|
Delete
|
|
</button>
|
|
<button
|
|
id="save-btn"
|
|
class="bg-mauve text-crust font-bold py-3 px-8 rounded-lg hover:bg-pink transition-all transform hover:scale-105 w-full md:w-auto whitespace-nowrap"
|
|
>
|
|
Save Post
|
|
</button>
|
|
<a
|
|
id="view-post-btn"
|
|
href="#"
|
|
target="_blank"
|
|
class="hidden bg-blue text-crust font-bold py-3 px-8 rounded-lg hover:bg-sky transition-all transform hover:scale-105 w-full md:w-auto whitespace-nowrap items-center justify-center gap-2"
|
|
>
|
|
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" x2="14" y2="10" x2="21" y2="3"/></svg>
|
|
View Post
|
|
</a>
|
|
</div>
|
|
|
|
<div id="alert" class="hidden p-4 rounded-lg mb-6"></div>
|
|
|
|
<div class="space-y-6">
|
|
<div>
|
|
<label for="slug" class="block text-sm font-medium text-subtext1 mb-2">Slug (URL endpoint)</label>
|
|
<input
|
|
type="text"
|
|
id="slug"
|
|
required
|
|
placeholder="my-awesome-post"
|
|
class="w-full bg-crust border border-surface1 rounded-lg px-4 py-3 text-text focus:outline-none focus:border-mauve transition-colors font-mono"
|
|
/>
|
|
</div>
|
|
|
|
<div>
|
|
<label for="summary" class="block text-sm font-medium text-subtext1 mb-2">Custom Summary (Optional)</label>
|
|
<textarea
|
|
id="summary"
|
|
rows="2"
|
|
placeholder="A brief description of this post for the frontpage..."
|
|
class="w-full bg-crust border border-surface1 rounded-lg px-4 py-3 text-text focus:outline-none focus:border-mauve transition-colors resize-none"
|
|
></textarea>
|
|
</div>
|
|
|
|
<div class="relative">
|
|
<div class="flex flex-col md:flex-row justify-between items-start md:items-end mb-2 gap-2">
|
|
<label for="content" class="block text-sm font-medium text-subtext1 italic">Tip: Type '/' to browse your assets</label>
|
|
|
|
<div class="flex gap-2 w-full md:w-auto">
|
|
<button
|
|
id="browse-btn"
|
|
class="flex-1 md:flex-none text-sm bg-surface0 hover:bg-surface1 text-lavender px-4 py-2 rounded border border-surface1 transition-colors inline-flex justify-center items-center gap-2"
|
|
>
|
|
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="18" height="18" x="3" y="3" rx="2" ry="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"/></svg>
|
|
Library
|
|
</button>
|
|
|
|
<input type="file" id="file-upload" class="hidden" />
|
|
<label
|
|
for="file-upload"
|
|
class="flex-1 md:flex-none cursor-pointer text-sm bg-surface0 hover:bg-surface1 text-blue px-4 py-2 rounded border border-surface1 transition-colors inline-flex justify-center items-center gap-2"
|
|
>
|
|
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" x2="12" y1="3" y2="15"/></svg>
|
|
Upload
|
|
</label>
|
|
</div>
|
|
</div>
|
|
|
|
<textarea
|
|
id="content"
|
|
required
|
|
rows="25"
|
|
placeholder="# Hello World Write your markdown here..."
|
|
class="w-full bg-crust border border-surface1 rounded-lg px-4 py-4 text-text focus:outline-none focus:border-mauve transition-colors font-mono resize-y leading-relaxed"
|
|
></textarea>
|
|
|
|
<!-- Autocomplete Dropdown -->
|
|
<div id="autocomplete" class="hidden absolute z-50 bg-mantle border border-surface1 rounded-lg shadow-2xl max-h-64 overflow-y-auto w-80">
|
|
<div class="p-2 text-[10px] text-subtext0 uppercase border-b border-white/5 bg-crust/50">Assets Library</div>
|
|
<ul id="autocomplete-list" class="py-1">
|
|
<!-- Items injected here -->
|
|
</ul>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Assets Modal -->
|
|
<div id="assets-modal" class="hidden fixed inset-0 z-[100] bg-crust/80 backdrop-blur-sm flex items-center justify-center p-4 md:p-6">
|
|
<div class="glass w-full max-w-4xl max-h-[90vh] flex flex-col overflow-hidden">
|
|
<header class="p-4 md:p-6 border-b border-white/5 flex justify-between items-center bg-surface0/20">
|
|
<div>
|
|
<h2 class="text-xl md:text-2xl font-bold text-mauve">Asset Library</h2>
|
|
<p class="text-xs text-subtext0">Click an asset to insert its markdown link.</p>
|
|
</div>
|
|
<button id="close-modal" class="p-2 text-subtext0 hover:text-red transition-colors">
|
|
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>
|
|
</button>
|
|
</header>
|
|
<div class="p-4 md:p-6 overflow-y-auto flex-1 bg-base/50">
|
|
<div id="assets-grid" class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-5 gap-4">
|
|
<!-- Assets injected here -->
|
|
</div>
|
|
<div id="assets-empty" class="hidden text-center py-20 text-subtext0">
|
|
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" class="mx-auto mb-4 opacity-20"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" x2="12" y1="3" y2="15"/></svg>
|
|
No assets uploaded yet.
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<script>
|
|
import { showAlert } from '../../components/ui/Alert';
|
|
|
|
document.addEventListener('admin-auth-ready', (e: any) => {
|
|
const token = e.detail.token;
|
|
|
|
const slugInput = document.getElementById('slug') as HTMLInputElement;
|
|
const summaryInput = document.getElementById('summary') as HTMLTextAreaElement;
|
|
const contentInput = document.getElementById('content') as HTMLTextAreaElement;
|
|
const fileInput = document.getElementById('file-upload') as HTMLInputElement;
|
|
const saveBtn = document.getElementById('save-btn');
|
|
const delBtn = document.getElementById('delete-btn');
|
|
const viewPostBtn = document.getElementById('view-post-btn') as HTMLAnchorElement;
|
|
const browseBtn = document.getElementById('browse-btn');
|
|
const assetsModal = document.getElementById('assets-modal');
|
|
const closeModal = document.getElementById('close-modal');
|
|
const assetsGrid = document.getElementById('assets-grid');
|
|
const assetsEmpty = document.getElementById('assets-empty');
|
|
const autocomplete = document.getElementById('autocomplete');
|
|
const autocompleteList = document.getElementById('autocomplete-list');
|
|
|
|
// @ts-ignore
|
|
const editor = CodeMirror.fromTextArea(contentInput, {
|
|
mode: 'markdown',
|
|
theme: 'narlblog',
|
|
lineWrapping: true,
|
|
keyMap: window.innerWidth > 768 ? 'vim' : 'default',
|
|
extraKeys: {"Enter": "newlineAndIndentContinueMarkdownList"}
|
|
});
|
|
|
|
let allAssets: {name: string, url: string}[] = [];
|
|
|
|
async function fetchAssets() {
|
|
try {
|
|
const res = await fetch('/api/uploads', {
|
|
headers: { 'Authorization': `Bearer ${token}` }
|
|
});
|
|
if (res.ok) {
|
|
allAssets = await res.json();
|
|
}
|
|
} catch (err) {
|
|
console.error("Failed to fetch assets", err);
|
|
}
|
|
}
|
|
|
|
browseBtn?.addEventListener('click', async () => {
|
|
await fetchAssets();
|
|
renderAssets();
|
|
assetsModal?.classList.remove('hidden');
|
|
});
|
|
|
|
closeModal?.addEventListener('click', () => {
|
|
assetsModal?.classList.add('hidden');
|
|
});
|
|
|
|
function renderAssets() {
|
|
if (!assetsGrid || !assetsEmpty) return;
|
|
assetsGrid.innerHTML = '';
|
|
|
|
if (allAssets.length === 0) {
|
|
assetsEmpty.classList.remove('hidden');
|
|
return;
|
|
}
|
|
assetsEmpty.classList.add('hidden');
|
|
|
|
allAssets.forEach(asset => {
|
|
const div = document.createElement('div');
|
|
div.className = "group relative aspect-square bg-crust rounded-xl overflow-hidden border border-white/5 cursor-pointer hover:border-mauve transition-all hover:scale-105 shadow-lg";
|
|
|
|
const isImage = /\.(jpg|jpeg|png|webp|gif|svg)$/i.test(asset.name);
|
|
|
|
if (isImage) {
|
|
const img = document.createElement('img');
|
|
img.src = asset.url;
|
|
img.className = "w-full h-full object-cover opacity-70 group-hover:opacity-100 transition-opacity";
|
|
div.appendChild(img);
|
|
} else {
|
|
const icon = document.createElement('div');
|
|
icon.className = "w-full h-full flex flex-col items-center justify-center text-subtext0 bg-surface0/30";
|
|
icon.innerHTML = `
|
|
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="mb-2"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>
|
|
<span class="text-[8px] font-mono px-2 truncate w-full text-center">${asset.name.split('.').pop()?.toUpperCase() || 'FILE'}</span>
|
|
`;
|
|
div.appendChild(icon);
|
|
}
|
|
|
|
const label = document.createElement('div');
|
|
label.className = "absolute bottom-0 left-0 right-0 p-2 bg-crust/95 text-[9px] truncate text-center opacity-0 group-hover:opacity-100 transition-opacity border-t border-white/5";
|
|
label.textContent = asset.name;
|
|
div.appendChild(label);
|
|
|
|
div.addEventListener('click', () => {
|
|
insertMarkdown(asset.name, asset.url);
|
|
assetsModal?.classList.add('hidden');
|
|
});
|
|
|
|
assetsGrid.appendChild(div);
|
|
});
|
|
}
|
|
|
|
function insertMarkdown(name: string, url: string) {
|
|
const isImage = /\.(jpg|jpeg|png|webp|gif|svg)$/i.test(name);
|
|
const markdown = isImage ? `` : `[${name}](${url})`;
|
|
|
|
const doc = editor.getDoc();
|
|
const cursor = doc.getCursor();
|
|
doc.replaceRange(markdown, cursor);
|
|
editor.focus();
|
|
}
|
|
|
|
editor.on('inputRead', (cm: any, change: any) => {
|
|
if (change.text && change.text.length === 1 && (change.text[0] === '/' || change.text[0] === '!')) {
|
|
showAutocomplete();
|
|
} else if (change.text && change.text[0] === ' ') {
|
|
hideAutocomplete();
|
|
}
|
|
});
|
|
|
|
async function showAutocomplete() {
|
|
if (allAssets.length === 0) await fetchAssets();
|
|
if (allAssets.length === 0) return;
|
|
|
|
if (!autocomplete || !autocompleteList) return;
|
|
|
|
const cursor = editor.cursorCoords(true, 'local');
|
|
|
|
autocomplete.classList.remove('hidden');
|
|
autocomplete.style.top = `${cursor.bottom + 10}px`;
|
|
autocomplete.style.left = `${cursor.left}px`;
|
|
|
|
autocompleteList.innerHTML = '';
|
|
allAssets.slice(0, 8).forEach(asset => {
|
|
const li = document.createElement('li');
|
|
li.className = "px-4 py-2 hover:bg-mauve/20 cursor-pointer text-sm truncate text-subtext1 hover:text-mauve flex items-center gap-3 transition-colors";
|
|
const isImage = /\.(jpg|jpeg|png|webp|gif|svg)$/i.test(asset.name);
|
|
li.innerHTML = `
|
|
<div class="w-6 h-6 flex-shrink-0 bg-surface0 rounded flex items-center justify-center overflow-hidden">
|
|
${isImage ? `<img src="${asset.url}" class="w-full h-full object-cover">` : `<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/></svg>`}
|
|
</div>
|
|
<span class="truncate">${asset.name}</span>
|
|
`;
|
|
li.addEventListener('click', () => {
|
|
const doc = editor.getDoc();
|
|
const cursor = doc.getCursor();
|
|
const line = doc.getLine(cursor.line);
|
|
const triggerIndex = Math.max(line.lastIndexOf('/'), line.lastIndexOf('!'));
|
|
|
|
if (triggerIndex !== -1) {
|
|
doc.replaceRange('', {line: cursor.line, ch: triggerIndex}, cursor);
|
|
}
|
|
|
|
insertMarkdown(asset.name, asset.url);
|
|
hideAutocomplete();
|
|
});
|
|
autocompleteList.appendChild(li);
|
|
});
|
|
}
|
|
|
|
function hideAutocomplete() {
|
|
autocomplete?.classList.add('hidden');
|
|
}
|
|
|
|
window.addEventListener('click', (ev) => {
|
|
if (!autocomplete?.contains(ev.target as Node)) {
|
|
hideAutocomplete();
|
|
}
|
|
});
|
|
|
|
fileInput?.addEventListener('change', async (ev) => {
|
|
const file = (ev.target as HTMLInputElement).files?.[0];
|
|
if (!file) return;
|
|
|
|
const formData = new FormData();
|
|
formData.append('file', file);
|
|
|
|
try {
|
|
const res = await fetch('/api/upload', {
|
|
method: 'POST',
|
|
headers: { 'Authorization': `Bearer ${token}` },
|
|
body: formData
|
|
});
|
|
|
|
if (res.ok) {
|
|
const data = await res.json();
|
|
insertMarkdown(file.name, data.url);
|
|
showAlert('File uploaded and linked!', 'success');
|
|
} else {
|
|
const err = await res.json();
|
|
showAlert(`Upload failed: ${err.error}`, 'error');
|
|
}
|
|
} catch (err) {
|
|
showAlert('Network error during upload.', 'error');
|
|
}
|
|
fileInput.value = '';
|
|
});
|
|
|
|
saveBtn?.addEventListener('click', async () => {
|
|
const payload = {
|
|
slug: slugInput.value,
|
|
summary: summaryInput.value || null,
|
|
content: editor.getValue()
|
|
};
|
|
if (!payload.slug || !payload.content) {
|
|
showAlert('Slug and content are required.', 'error');
|
|
return;
|
|
}
|
|
try {
|
|
const res = await fetch('/api/posts', {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'Authorization': `Bearer ${token}`
|
|
},
|
|
body: JSON.stringify(payload)
|
|
});
|
|
if (res.ok) {
|
|
showAlert('Post saved!', 'success');
|
|
if (viewPostBtn) {
|
|
viewPostBtn.href = `/posts/${payload.slug}`;
|
|
viewPostBtn.classList.remove('hidden');
|
|
viewPostBtn.classList.add('inline-flex');
|
|
}
|
|
} else {
|
|
showAlert('Error saving post.', 'error');
|
|
}
|
|
} catch (err) {
|
|
showAlert('Failed to connect to server.', 'error');
|
|
}
|
|
});
|
|
|
|
delBtn?.addEventListener('click', async () => {
|
|
if (confirm(`Delete post "${slugInput.value}" permanently?`)) {
|
|
try {
|
|
const res = await fetch(`/api/posts/${encodeURIComponent(slugInput.value)}`, {
|
|
method: 'DELETE',
|
|
headers: { 'Authorization': `Bearer ${token}` }
|
|
});
|
|
if (res.ok) window.location.href = '/admin';
|
|
else showAlert('Error deleting post.', 'error');
|
|
} catch (err) {
|
|
showAlert('Connection error.', 'error');
|
|
}
|
|
}
|
|
});
|
|
|
|
const urlParams = new URLSearchParams(window.location.search);
|
|
const editSlug = urlParams.get('edit');
|
|
if (editSlug) {
|
|
slugInput.value = editSlug;
|
|
slugInput.disabled = true; // Protect slug on edit
|
|
delBtn?.classList.remove('hidden');
|
|
|
|
if (viewPostBtn) {
|
|
viewPostBtn.href = `/posts/${editSlug}`;
|
|
viewPostBtn.classList.remove('hidden');
|
|
viewPostBtn.classList.add('inline-flex');
|
|
}
|
|
|
|
fetch(`/api/posts/${encodeURIComponent(editSlug)}`)
|
|
.then(res => res.json())
|
|
.then(data => {
|
|
if (data.summary) {
|
|
summaryInput.value = data.summary;
|
|
}
|
|
if (data.content) {
|
|
editor.setValue(data.content);
|
|
}
|
|
})
|
|
.catch(() => showAlert('Failed to load post.', 'error'));
|
|
}
|
|
});
|
|
</script>
|
|
</AdminLayout>
|