added asset manegement
This commit is contained in:
@@ -1,8 +1,9 @@
|
|||||||
use axum::{
|
use axum::{
|
||||||
Json,
|
Json,
|
||||||
extract::{Multipart, State},
|
extract::{Multipart, State, Path, Query},
|
||||||
http::HeaderMap,
|
http::{HeaderMap, StatusCode},
|
||||||
};
|
};
|
||||||
|
use serde::Deserialize;
|
||||||
use std::{fs, sync::Arc};
|
use std::{fs, sync::Arc};
|
||||||
use tracing::{error, info, warn};
|
use tracing::{error, info, warn};
|
||||||
|
|
||||||
@@ -13,6 +14,37 @@ use crate::{
|
|||||||
models::{FileInfo, UploadResponse},
|
models::{FileInfo, UploadResponse},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct UploadQuery {
|
||||||
|
pub replace: Option<bool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn delete_upload(
|
||||||
|
State(state): State<Arc<AppState>>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
Path(filename): Path<String>,
|
||||||
|
) -> Result<StatusCode, AppError> {
|
||||||
|
check_auth(&headers, &state.admin_token)?;
|
||||||
|
|
||||||
|
let file_path = state.data_dir.join("uploads").join(&filename);
|
||||||
|
|
||||||
|
// Security check to prevent directory traversal
|
||||||
|
if file_path.parent() != Some(&state.data_dir.join("uploads")) {
|
||||||
|
return Err(AppError::BadRequest("Invalid filename".to_string()));
|
||||||
|
}
|
||||||
|
|
||||||
|
if file_path.exists() {
|
||||||
|
fs::remove_file(file_path).map_err(|e| {
|
||||||
|
error!("Delete error for file {}: {}", filename, e);
|
||||||
|
AppError::Internal("Delete error".to_string(), Some(e.to_string()))
|
||||||
|
})?;
|
||||||
|
info!("Deleted file: {}", filename);
|
||||||
|
Ok(StatusCode::NO_CONTENT)
|
||||||
|
} else {
|
||||||
|
Err(AppError::NotFound("File not found".to_string()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn list_uploads(
|
pub async fn list_uploads(
|
||||||
State(state): State<Arc<AppState>>,
|
State(state): State<Arc<AppState>>,
|
||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
@@ -42,6 +74,7 @@ pub async fn list_uploads(
|
|||||||
pub async fn upload_file(
|
pub async fn upload_file(
|
||||||
State(state): State<Arc<AppState>>,
|
State(state): State<Arc<AppState>>,
|
||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
|
Query(query): Query<UploadQuery>,
|
||||||
mut multipart: Multipart,
|
mut multipart: Multipart,
|
||||||
) -> Result<Json<UploadResponse>, AppError> {
|
) -> Result<Json<UploadResponse>, AppError> {
|
||||||
check_auth(&headers, &state.admin_token)?;
|
check_auth(&headers, &state.admin_token)?;
|
||||||
@@ -71,7 +104,7 @@ pub async fn upload_file(
|
|||||||
let uploads_dir = state.data_dir.join("uploads");
|
let uploads_dir = state.data_dir.join("uploads");
|
||||||
let file_path = uploads_dir.join(&final_name);
|
let file_path = uploads_dir.join(&final_name);
|
||||||
|
|
||||||
let final_path = if file_path.exists() {
|
let final_path = if file_path.exists() && !query.replace.unwrap_or(false) {
|
||||||
let timestamp = chrono::Utc::now().timestamp();
|
let timestamp = chrono::Utc::now().timestamp();
|
||||||
uploads_dir.join(format!("{}_{}", timestamp, final_name))
|
uploads_dir.join(format!("{}_{}", timestamp, final_name))
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -67,6 +67,7 @@ async fn main() {
|
|||||||
get(handlers::posts::get_post).delete(handlers::posts::delete_post),
|
get(handlers::posts::get_post).delete(handlers::posts::delete_post),
|
||||||
)
|
)
|
||||||
.route("/api/uploads", get(handlers::upload::list_uploads))
|
.route("/api/uploads", get(handlers::upload::list_uploads))
|
||||||
|
.route("/api/uploads/{filename}", delete(handlers::upload::delete_upload))
|
||||||
.route("/api/upload", post(handlers::upload::upload_file))
|
.route("/api/upload", post(handlers::upload::upload_file))
|
||||||
.nest_service("/uploads", ServeDir::new(uploads_dir))
|
.nest_service("/uploads", ServeDir::new(uploads_dir))
|
||||||
.layer(DefaultBodyLimit::max(50 * 1024 * 1024))
|
.layer(DefaultBodyLimit::max(50 * 1024 * 1024))
|
||||||
|
|||||||
178
frontend/src/components/AssetManager.astro
Normal file
178
frontend/src/components/AssetManager.astro
Normal file
@@ -0,0 +1,178 @@
|
|||||||
|
---
|
||||||
|
interface Props {
|
||||||
|
mode?: 'select' | 'manage';
|
||||||
|
}
|
||||||
|
|
||||||
|
const { mode = 'manage' } = Astro.props;
|
||||||
|
---
|
||||||
|
|
||||||
|
<div class="space-y-8">
|
||||||
|
<div id="asset-alert" class="hidden p-4 rounded-lg mb-6 text-sm"></div>
|
||||||
|
|
||||||
|
<!-- Upload Zone -->
|
||||||
|
<div class="glass p-6 border-dashed border-2 border-surface1 hover:border-mauve transition-colors group relative">
|
||||||
|
<input type="file" id="zone-file-upload" class="absolute inset-0 w-full h-full opacity-0 cursor-pointer" multiple />
|
||||||
|
<div class="text-center py-4">
|
||||||
|
<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 text-subtext0 group-hover:text-mauve transition-colors"><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>
|
||||||
|
<p class="text-lg font-bold text-lavender">Click or drag to upload assets</p>
|
||||||
|
<p class="text-xs text-subtext0 mt-1">Any file type up to 50MB</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Assets Grid -->
|
||||||
|
<div id="manager-assets-grid" class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-5 gap-4">
|
||||||
|
<!-- Assets injected here -->
|
||||||
|
</div>
|
||||||
|
<div id="manager-assets-empty" class="hidden text-center py-20 text-subtext0">
|
||||||
|
No assets uploaded yet.
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script is:inline define:vars={{ mode }}>
|
||||||
|
const token = localStorage.getItem('admin_token');
|
||||||
|
const grid = document.getElementById('manager-assets-grid');
|
||||||
|
const empty = document.getElementById('manager-assets-empty');
|
||||||
|
const fileInput = document.getElementById('zone-file-upload');
|
||||||
|
const alertEl = document.getElementById('asset-alert');
|
||||||
|
|
||||||
|
let allAssets = [];
|
||||||
|
|
||||||
|
async function fetchAssets() {
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/uploads', {
|
||||||
|
headers: { 'Authorization': `Bearer ${token}` }
|
||||||
|
});
|
||||||
|
if (res.ok) {
|
||||||
|
allAssets = await res.json();
|
||||||
|
renderAssets();
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error("Failed to fetch assets", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function showLocalAlert(msg, type) {
|
||||||
|
if (!alertEl) return;
|
||||||
|
alertEl.textContent = msg;
|
||||||
|
alertEl.className = `p-4 rounded-lg mb-6 text-sm ${type === 'success' ? 'bg-green/20 text-green border border-green/30' : 'bg-red/20 text-red border border-red/30'}`;
|
||||||
|
alertEl.classList.remove('hidden');
|
||||||
|
setTimeout(() => alertEl.classList.add('hidden'), 4000);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function uploadFiles(files) {
|
||||||
|
let successCount = 0;
|
||||||
|
for (const file of files) {
|
||||||
|
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) successCount++;
|
||||||
|
} catch (e) {}
|
||||||
|
}
|
||||||
|
if (successCount > 0) {
|
||||||
|
showLocalAlert(`Successfully uploaded ${successCount} file(s).`, 'success');
|
||||||
|
fetchAssets();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deleteAsset(filename) {
|
||||||
|
if (!confirm(`Delete "${filename}" permanently?`)) return;
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/api/uploads/${encodeURIComponent(filename)}`, {
|
||||||
|
method: 'DELETE',
|
||||||
|
headers: { 'Authorization': `Bearer ${token}` }
|
||||||
|
});
|
||||||
|
if (res.ok) {
|
||||||
|
showLocalAlert('File deleted.', 'success');
|
||||||
|
fetchAssets();
|
||||||
|
} else {
|
||||||
|
showLocalAlert('Failed to delete file.', 'error');
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
showLocalAlert('Connection error.', 'error');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderAssets() {
|
||||||
|
if (!grid || !empty) return;
|
||||||
|
grid.innerHTML = '';
|
||||||
|
|
||||||
|
if (allAssets.length === 0) {
|
||||||
|
empty.classList.remove('hidden');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
empty.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 transition-all hover:scale-105 shadow-lg flex flex-col";
|
||||||
|
|
||||||
|
const isImage = /\.(jpg|jpeg|png|webp|gif|svg)$/i.test(asset.name);
|
||||||
|
|
||||||
|
// Preview Container
|
||||||
|
const preview = document.createElement('div');
|
||||||
|
preview.className = "flex-1 overflow-hidden bg-surface0/20 relative cursor-pointer";
|
||||||
|
|
||||||
|
if (isImage) {
|
||||||
|
const img = document.createElement('img');
|
||||||
|
img.src = asset.url;
|
||||||
|
img.className = "w-full h-full object-cover opacity-80 group-hover:opacity-100 transition-opacity";
|
||||||
|
preview.appendChild(img);
|
||||||
|
} else {
|
||||||
|
preview.className += " flex flex-col items-center justify-center text-subtext0";
|
||||||
|
preview.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()}</span>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Action Overlays
|
||||||
|
const actions = document.createElement('div');
|
||||||
|
actions.className = "absolute inset-0 bg-crust/60 backdrop-blur-sm opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-2";
|
||||||
|
|
||||||
|
if (mode === 'select') {
|
||||||
|
const selectBtn = document.createElement('button');
|
||||||
|
selectBtn.className = "bg-mauve text-crust px-3 py-1 rounded-md text-xs font-bold";
|
||||||
|
selectBtn.textContent = "Insert";
|
||||||
|
selectBtn.onclick = () => {
|
||||||
|
document.dispatchEvent(new CustomEvent('asset-selected', { detail: asset }));
|
||||||
|
};
|
||||||
|
actions.appendChild(selectBtn);
|
||||||
|
}
|
||||||
|
|
||||||
|
const deleteBtn = document.createElement('button');
|
||||||
|
deleteBtn.className = "bg-red/80 hover:bg-red text-white p-1.5 rounded-md transition-colors";
|
||||||
|
deleteBtn.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/></svg>';
|
||||||
|
deleteBtn.onclick = (e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
deleteAsset(asset.name);
|
||||||
|
};
|
||||||
|
actions.appendChild(deleteBtn);
|
||||||
|
|
||||||
|
preview.appendChild(actions);
|
||||||
|
|
||||||
|
// Label
|
||||||
|
const label = document.createElement('div');
|
||||||
|
label.className = "p-2 bg-crust text-[10px] truncate border-t border-white/5 text-subtext1";
|
||||||
|
label.textContent = asset.name;
|
||||||
|
|
||||||
|
div.appendChild(preview);
|
||||||
|
div.appendChild(label);
|
||||||
|
grid.appendChild(div);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fileInput?.addEventListener('change', (e) => {
|
||||||
|
if (e.target.files.length > 0) uploadFiles(e.target.files);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Initialize
|
||||||
|
fetchAssets();
|
||||||
|
|
||||||
|
// Re-fetch on global upload events if needed
|
||||||
|
document.addEventListener('assets-updated', fetchAssets);
|
||||||
|
</script>
|
||||||
10
frontend/src/pages/admin/assets.astro
Normal file
10
frontend/src/pages/admin/assets.astro
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
---
|
||||||
|
import AdminLayout from '../../layouts/AdminLayout.astro';
|
||||||
|
import AssetManager from '../../components/AssetManager.astro';
|
||||||
|
---
|
||||||
|
|
||||||
|
<AdminLayout title="Asset Library">
|
||||||
|
<p slot="header-subtitle" class="mt-2 text-sm md:text-base text-subtext1">Manage your uploaded images and files.</p>
|
||||||
|
|
||||||
|
<AssetManager mode="manage" />
|
||||||
|
</AdminLayout>
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
---
|
---
|
||||||
import AdminLayout from '../../layouts/AdminLayout.astro';
|
import AdminLayout from '../../layouts/AdminLayout.astro';
|
||||||
|
import AssetManager from '../../components/AssetManager.astro';
|
||||||
---
|
---
|
||||||
|
|
||||||
<AdminLayout title="Write Post">
|
<AdminLayout title="Write Post">
|
||||||
@@ -54,24 +55,13 @@ import AdminLayout from '../../layouts/AdminLayout.astro';
|
|||||||
<div class="flex flex-col md:flex-row justify-between items-start md:items-end mb-2 gap-2">
|
<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>
|
<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
|
<button
|
||||||
id="browse-btn"
|
id="open-library-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"
|
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>
|
<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
|
Asset Library
|
||||||
</button>
|
</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>
|
</div>
|
||||||
|
|
||||||
<textarea
|
<textarea
|
||||||
@@ -94,24 +84,18 @@ import AdminLayout from '../../layouts/AdminLayout.astro';
|
|||||||
|
|
||||||
<!-- Assets Modal -->
|
<!-- 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 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">
|
<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">
|
<header class="p-4 md:p-6 border-b border-white/5 flex justify-between items-center bg-surface0/20">
|
||||||
<div>
|
<div>
|
||||||
<h2 class="text-xl md:text-2xl font-bold text-mauve">Asset Library</h2>
|
<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>
|
<p class="text-xs text-subtext0">Click 'Insert' to add an asset to your post.</p>
|
||||||
</div>
|
</div>
|
||||||
<button id="close-modal" class="p-2 text-subtext0 hover:text-red transition-colors">
|
<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>
|
<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>
|
</button>
|
||||||
</header>
|
</header>
|
||||||
<div class="p-4 md:p-6 overflow-y-auto flex-1 bg-base/50">
|
<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">
|
<AssetManager mode="select" />
|
||||||
<!-- 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>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -125,15 +109,12 @@ import AdminLayout from '../../layouts/AdminLayout.astro';
|
|||||||
const slugInput = document.getElementById('slug') as HTMLInputElement;
|
const slugInput = document.getElementById('slug') as HTMLInputElement;
|
||||||
const summaryInput = document.getElementById('summary') as HTMLTextAreaElement;
|
const summaryInput = document.getElementById('summary') as HTMLTextAreaElement;
|
||||||
const contentInput = document.getElementById('content') as HTMLTextAreaElement;
|
const contentInput = document.getElementById('content') as HTMLTextAreaElement;
|
||||||
const fileInput = document.getElementById('file-upload') as HTMLInputElement;
|
|
||||||
const saveBtn = document.getElementById('save-btn');
|
const saveBtn = document.getElementById('save-btn');
|
||||||
const delBtn = document.getElementById('delete-btn');
|
const delBtn = document.getElementById('delete-btn');
|
||||||
const viewPostBtn = document.getElementById('view-post-btn') as HTMLAnchorElement;
|
const viewPostBtn = document.getElementById('view-post-btn') as HTMLAnchorElement;
|
||||||
const browseBtn = document.getElementById('browse-btn');
|
const openLibraryBtn = document.getElementById('open-library-btn');
|
||||||
const assetsModal = document.getElementById('assets-modal');
|
const assetsModal = document.getElementById('assets-modal');
|
||||||
const closeModal = document.getElementById('close-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 autocomplete = document.getElementById('autocomplete');
|
||||||
const autocompleteList = document.getElementById('autocomplete-list');
|
const autocompleteList = document.getElementById('autocomplete-list');
|
||||||
|
|
||||||
@@ -148,24 +129,7 @@ import AdminLayout from '../../layouts/AdminLayout.astro';
|
|||||||
extraKeys: {"Enter": "newlineAndIndentContinueMarkdownList"}
|
extraKeys: {"Enter": "newlineAndIndentContinueMarkdownList"}
|
||||||
});
|
});
|
||||||
|
|
||||||
let allAssets: {name: string, url: string}[] = [];
|
openLibraryBtn?.addEventListener('click', () => {
|
||||||
|
|
||||||
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');
|
assetsModal?.classList.remove('hidden');
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -173,51 +137,13 @@ import AdminLayout from '../../layouts/AdminLayout.astro';
|
|||||||
assetsModal?.classList.add('hidden');
|
assetsModal?.classList.add('hidden');
|
||||||
});
|
});
|
||||||
|
|
||||||
function renderAssets() {
|
// Listen for asset selection from the component
|
||||||
if (!assetsGrid || !assetsEmpty) return;
|
document.addEventListener('asset-selected', (ev: any) => {
|
||||||
assetsGrid.innerHTML = '';
|
const asset = ev.detail;
|
||||||
|
|
||||||
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);
|
insertMarkdown(asset.name, asset.url);
|
||||||
assetsModal?.classList.add('hidden');
|
assetsModal?.classList.add('hidden');
|
||||||
});
|
});
|
||||||
|
|
||||||
assetsGrid.appendChild(div);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function insertMarkdown(name: string, url: string) {
|
function insertMarkdown(name: string, url: string) {
|
||||||
const isImage = /\.(jpg|jpeg|png|webp|gif|svg)$/i.test(name);
|
const isImage = /\.(jpg|jpeg|png|webp|gif|svg)$/i.test(name);
|
||||||
const markdown = isImage ? `` : `[${name}](${url})`;
|
const markdown = isImage ? `` : `[${name}](${url})`;
|
||||||
@@ -228,28 +154,30 @@ import AdminLayout from '../../layouts/AdminLayout.astro';
|
|||||||
editor.focus();
|
editor.focus();
|
||||||
}
|
}
|
||||||
|
|
||||||
editor.on('inputRead', (cm: any, change: any) => {
|
// Autocomplete Logic
|
||||||
|
editor.on('inputRead', async (cm: any, change: any) => {
|
||||||
if (change.text && change.text.length === 1 && (change.text[0] === '/' || change.text[0] === '!')) {
|
if (change.text && change.text.length === 1 && (change.text[0] === '/' || change.text[0] === '!')) {
|
||||||
showAutocomplete();
|
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] === ' ') {
|
} else if (change.text && change.text[0] === ' ') {
|
||||||
hideAutocomplete();
|
hideAutocomplete();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
async function showAutocomplete() {
|
function showAutocomplete(assets: any[]) {
|
||||||
if (allAssets.length === 0) await fetchAssets();
|
|
||||||
if (allAssets.length === 0) return;
|
|
||||||
|
|
||||||
if (!autocomplete || !autocompleteList) return;
|
if (!autocomplete || !autocompleteList) return;
|
||||||
|
|
||||||
const cursor = editor.cursorCoords(true, 'local');
|
const cursor = editor.cursorCoords(true, 'local');
|
||||||
|
|
||||||
autocomplete.classList.remove('hidden');
|
autocomplete.classList.remove('hidden');
|
||||||
autocomplete.style.top = `${cursor.bottom + 10}px`;
|
autocomplete.style.top = `${cursor.bottom + 10}px`;
|
||||||
autocomplete.style.left = `${cursor.left}px`;
|
autocomplete.style.left = `${cursor.left}px`;
|
||||||
|
|
||||||
autocompleteList.innerHTML = '';
|
autocompleteList.innerHTML = '';
|
||||||
allAssets.slice(0, 8).forEach(asset => {
|
assets.slice(0, 8).forEach(asset => {
|
||||||
const li = document.createElement('li');
|
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";
|
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);
|
const isImage = /\.(jpg|jpeg|png|webp|gif|svg)$/i.test(asset.name);
|
||||||
@@ -264,11 +192,9 @@ import AdminLayout from '../../layouts/AdminLayout.astro';
|
|||||||
const cursor = doc.getCursor();
|
const cursor = doc.getCursor();
|
||||||
const line = doc.getLine(cursor.line);
|
const line = doc.getLine(cursor.line);
|
||||||
const triggerIndex = Math.max(line.lastIndexOf('/'), line.lastIndexOf('!'));
|
const triggerIndex = Math.max(line.lastIndexOf('/'), line.lastIndexOf('!'));
|
||||||
|
|
||||||
if (triggerIndex !== -1) {
|
if (triggerIndex !== -1) {
|
||||||
doc.replaceRange('', {line: cursor.line, ch: triggerIndex}, cursor);
|
doc.replaceRange('', {line: cursor.line, ch: triggerIndex}, cursor);
|
||||||
}
|
}
|
||||||
|
|
||||||
insertMarkdown(asset.name, asset.url);
|
insertMarkdown(asset.name, asset.url);
|
||||||
hideAutocomplete();
|
hideAutocomplete();
|
||||||
});
|
});
|
||||||
@@ -286,34 +212,6 @@ import AdminLayout from '../../layouts/AdminLayout.astro';
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
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 () => {
|
saveBtn?.addEventListener('click', async () => {
|
||||||
const payload = {
|
const payload = {
|
||||||
slug: slugInput.value,
|
slug: slugInput.value,
|
||||||
@@ -336,7 +234,7 @@ import AdminLayout from '../../layouts/AdminLayout.astro';
|
|||||||
});
|
});
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
showAlert('Post saved!', 'success');
|
showAlert('Post saved!', 'success');
|
||||||
originalSlug = payload.slug; // Update for next save
|
originalSlug = payload.slug;
|
||||||
if (viewPostBtn) {
|
if (viewPostBtn) {
|
||||||
viewPostBtn.href = `/posts/${payload.slug}`;
|
viewPostBtn.href = `/posts/${payload.slug}`;
|
||||||
viewPostBtn.classList.remove('hidden');
|
viewPostBtn.classList.remove('hidden');
|
||||||
@@ -383,12 +281,8 @@ import AdminLayout from '../../layouts/AdminLayout.astro';
|
|||||||
fetch(`/api/posts/${encodeURIComponent(editSlug)}`)
|
fetch(`/api/posts/${encodeURIComponent(editSlug)}`)
|
||||||
.then(res => res.json())
|
.then(res => res.json())
|
||||||
.then(data => {
|
.then(data => {
|
||||||
if (data.summary) {
|
if (data.summary) summaryInput.value = data.summary;
|
||||||
summaryInput.value = data.summary;
|
if (data.content) editor.setValue(data.content);
|
||||||
}
|
|
||||||
if (data.content) {
|
|
||||||
editor.setValue(data.content);
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
.catch(() => showAlert('Failed to load post.', 'error'));
|
.catch(() => showAlert('Failed to load post.', 'error'));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,27 +7,39 @@ import AdminLayout from '../../layouts/AdminLayout.astro';
|
|||||||
Logout
|
Logout
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<div class="grid md:grid-cols-2 gap-8 mb-12">
|
<div class="grid md:grid-cols-3 gap-8 mb-12">
|
||||||
<a href="/admin/editor" class="group">
|
<a href="/admin/editor" class="group">
|
||||||
<div class="bg-surface0/50 p-8 rounded-xl border border-white/5 transition-all hover:bg-surface0 hover:scale-[1.02] h-full flex items-center gap-6">
|
<div class="bg-surface0/50 p-8 rounded-xl border border-white/5 transition-all hover:bg-surface0 hover:scale-[1.02] h-full flex flex-col items-center text-center gap-4">
|
||||||
<div class="bg-mauve/20 p-4 rounded-lg text-mauve">
|
<div class="bg-mauve/20 p-4 rounded-full text-mauve">
|
||||||
<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"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 1 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
|
<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"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 1 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<h2 class="text-2xl font-bold text-lavender group-hover:text-mauve transition-colors">Write a Post</h2>
|
<h2 class="text-xl font-bold text-lavender group-hover:text-mauve transition-colors">Write Post</h2>
|
||||||
<p class="text-subtext0">Create or edit markdown posts and upload any file.</p>
|
<p class="text-xs text-subtext0 mt-1">Create or edit markdown posts.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</a>
|
||||||
|
|
||||||
|
<a href="/admin/assets" class="group">
|
||||||
|
<div class="bg-surface0/50 p-8 rounded-xl border border-white/5 transition-all hover:bg-surface0 hover:scale-[1.02] h-full flex flex-col items-center text-center gap-4">
|
||||||
|
<div class="bg-teal/20 p-4 rounded-full text-teal">
|
||||||
|
<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"><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>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h2 class="text-xl font-bold text-teal group-hover:text-green transition-colors">Asset Library</h2>
|
||||||
|
<p class="text-xs text-subtext0 mt-1">Manage images and uploads.</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</a>
|
</a>
|
||||||
|
|
||||||
<a href="/admin/settings" class="group">
|
<a href="/admin/settings" class="group">
|
||||||
<div class="bg-surface0/50 p-8 rounded-xl border border-white/5 transition-all hover:bg-surface0 hover:scale-[1.02] h-full flex items-center gap-6">
|
<div class="bg-surface0/50 p-8 rounded-xl border border-white/5 transition-all hover:bg-surface0 hover:scale-[1.02] h-full flex flex-col items-center text-center gap-4">
|
||||||
<div class="bg-blue/20 p-4 rounded-lg text-blue">
|
<div class="bg-blue/20 p-4 rounded-full text-blue">
|
||||||
<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"><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/></svg>
|
<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"><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/></svg>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<h2 class="text-2xl font-bold text-blue mb-2 group-hover:text-sky transition-colors">Site Settings</h2>
|
<h2 class="text-xl font-bold text-blue group-hover:text-sky transition-colors">Settings</h2>
|
||||||
<p class="text-subtext0">Update title, favicon, and global theme.</p>
|
<p class="text-xs text-subtext0 mt-1">Site title and themes.</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</a>
|
</a>
|
||||||
|
|||||||
Reference in New Issue
Block a user