migrated to react

This commit is contained in:
2026-03-27 22:15:50 +01:00
parent 11ac1e008f
commit 176f821598
24 changed files with 2281 additions and 888 deletions
+5 -285
View File
@@ -1,291 +1,11 @@
---
import AdminLayout from '../../layouts/AdminLayout.astro';
import AssetManager from '../../components/AssetManager.astro';
import Editor from '../../components/react/admin/Editor';
const editSlug = Astro.url.searchParams.get('edit') || undefined;
---
<AdminLayout title="Write Post">
<p slot="header-subtitle" id="post-status" class="mt-2 text-sm md:text-base" style="color: var(--text) !important;">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" y1="14" 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">Post Title (URL identifier)</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>
<button
id="open-library-btn"
class="text-sm bg-surface0 hover:bg-surface1 text-lavender px-4 py-2 rounded border border-surface1 transition-colors inline-flex 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>
Asset Library
</button>
</div>
<textarea
id="content"
required
rows="25"
placeholder="# Hello World&#10;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-5xl 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 'Insert' to add an asset to your post.</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">
<AssetManager mode="select" />
</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 saveBtn = document.getElementById('save-btn');
const delBtn = document.getElementById('delete-btn');
const viewPostBtn = document.getElementById('view-post-btn') as HTMLAnchorElement;
const openLibraryBtn = document.getElementById('open-library-btn');
const assetsModal = document.getElementById('assets-modal');
const closeModal = document.getElementById('close-modal');
const autocomplete = document.getElementById('autocomplete');
const autocompleteList = document.getElementById('autocomplete-list');
let originalSlug = "";
// @ts-ignore
const editor = CodeMirror.fromTextArea(contentInput, {
mode: 'markdown',
theme: 'narlblog',
lineWrapping: true,
keyMap: window.innerWidth > 768 ? 'vim' : 'default',
extraKeys: {"Enter": "newlineAndIndentContinueMarkdownList"}
});
openLibraryBtn?.addEventListener('click', () => {
assetsModal?.classList.remove('hidden');
});
closeModal?.addEventListener('click', () => {
assetsModal?.classList.add('hidden');
});
// Listen for asset selection from the component
document.addEventListener('asset-selected', (ev: any) => {
const asset = ev.detail;
insertMarkdown(asset.name, asset.url);
assetsModal?.classList.add('hidden');
});
function insertMarkdown(name: string, url: string) {
const isImage = /\.(jpg|jpeg|png|webp|gif|svg)$/i.test(name);
const markdown = isImage ? `![${name}](${url})` : `[${name}](${url})`;
const doc = editor.getDoc();
const cursor = doc.getCursor();
doc.replaceRange(markdown, cursor);
editor.focus();
}
// Autocomplete Logic
editor.on('inputRead', async (cm: any, change: any) => {
if (change.text && change.text.length === 1 && (change.text[0] === '/' || change.text[0] === '!')) {
const res = await fetch('/api/uploads', {
headers: { 'Authorization': `Bearer ${token}` }
});
if (res.ok) {
const allAssets = await res.json();
showAutocomplete(allAssets);
}
} else if (change.text && change.text[0] === ' ') {
hideAutocomplete();
}
});
function showAutocomplete(assets: any[]) {
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 = '';
assets.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();
}
});
saveBtn?.addEventListener('click', async () => {
const payload = {
slug: slugInput.value,
old_slug: originalSlug || null,
summary: summaryInput.value || null,
content: editor.getValue()
};
if (!payload.slug || !payload.content) {
showAlert('Title 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');
originalSlug = payload.slug;
if (viewPostBtn) {
viewPostBtn.href = `/posts/${payload.slug}`;
viewPostBtn.classList.remove('hidden');
viewPostBtn.classList.add('inline-flex');
}
} else {
const err = await res.json();
showAlert(`Error: ${err.error}`, 'error');
}
} catch (err) {
showAlert('Failed to connect to server.', 'error');
}
});
delBtn?.addEventListener('click', async () => {
const slugToDelete = originalSlug || slugInput.value;
if (confirm(`Delete post "${slugToDelete}" permanently?`)) {
try {
const res = await fetch(`/api/posts/${encodeURIComponent(slugToDelete)}`, {
method: 'DELETE',
headers: { 'Authorization': `Bearer ${token}` }
});
if (res.ok) window.location.href = '/admin';
else showAlert('Error deleting post.', 'error');
} catch (e) {
showAlert('Connection error.', 'error');
}
}
});
const urlParams = new URLSearchParams(window.location.search);
const editSlug = urlParams.get('edit');
if (editSlug) {
slugInput.value = editSlug;
originalSlug = editSlug;
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>
<p slot="header-subtitle" class="mt-2 text-sm md:text-base" style="color: var(--text) !important;">Create/Edit post.</p>
<Editor client:load editSlug={editSlug} />
</AdminLayout>