refactor
This commit is contained in:
12
backend/src/auth.rs
Normal file
12
backend/src/auth.rs
Normal file
@@ -0,0 +1,12 @@
|
||||
use axum::http::HeaderMap;
|
||||
use tracing::warn;
|
||||
use crate::error::AppError;
|
||||
|
||||
pub fn check_auth(headers: &HeaderMap, admin_token: &str) -> Result<(), AppError> {
|
||||
let auth_header = headers.get("Authorization").and_then(|h| h.to_str().ok());
|
||||
if auth_header != Some(&format!("Bearer {}", admin_token)) {
|
||||
warn!("Unauthorized access attempt detected");
|
||||
return Err(AppError::Unauthorized);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
41
backend/src/error.rs
Normal file
41
backend/src/error.rs
Normal file
@@ -0,0 +1,41 @@
|
||||
use axum::{
|
||||
http::StatusCode,
|
||||
response::{IntoResponse, Response},
|
||||
Json,
|
||||
};
|
||||
|
||||
use crate::models::ErrorResponse;
|
||||
|
||||
pub enum AppError {
|
||||
Unauthorized,
|
||||
NotFound(String),
|
||||
BadRequest(String),
|
||||
Internal(String, Option<String>),
|
||||
}
|
||||
|
||||
impl IntoResponse for AppError {
|
||||
fn into_response(self) -> Response {
|
||||
let (status, error_message, details) = match self {
|
||||
AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "Unauthorized".to_string(), None),
|
||||
AppError::NotFound(msg) => (StatusCode::NOT_FOUND, msg, None),
|
||||
AppError::BadRequest(msg) => (StatusCode::BAD_REQUEST, msg, None),
|
||||
AppError::Internal(msg, details) => (StatusCode::INTERNAL_SERVER_ERROR, msg, details),
|
||||
};
|
||||
|
||||
let body = Json(ErrorResponse {
|
||||
error: error_message,
|
||||
details,
|
||||
});
|
||||
|
||||
(status, body).into_response()
|
||||
}
|
||||
}
|
||||
|
||||
impl<E> From<E> for AppError
|
||||
where
|
||||
E: std::error::Error + Send + Sync + 'static,
|
||||
{
|
||||
fn from(err: E) -> Self {
|
||||
AppError::Internal("Internal Server Error".to_string(), Some(err.to_string()))
|
||||
}
|
||||
}
|
||||
46
backend/src/handlers/config.rs
Normal file
46
backend/src/handlers/config.rs
Normal file
@@ -0,0 +1,46 @@
|
||||
use axum::{
|
||||
extract::State,
|
||||
http::HeaderMap,
|
||||
response::IntoResponse,
|
||||
Json,
|
||||
};
|
||||
use std::{fs, sync::Arc};
|
||||
use tracing::error;
|
||||
|
||||
use crate::{
|
||||
auth::check_auth,
|
||||
error::AppError,
|
||||
models::SiteConfig,
|
||||
AppState,
|
||||
};
|
||||
|
||||
pub async fn get_config(State(state): State<Arc<AppState>>) -> impl IntoResponse {
|
||||
let config_path = state.data_dir.join("config.json");
|
||||
let config = fs::read_to_string(&config_path)
|
||||
.ok()
|
||||
.and_then(|c| serde_json::from_str::<SiteConfig>(&c).ok())
|
||||
.unwrap_or_default();
|
||||
|
||||
Json(config)
|
||||
}
|
||||
|
||||
pub async fn update_config(
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
Json(payload): Json<SiteConfig>,
|
||||
) -> Result<Json<SiteConfig>, AppError> {
|
||||
check_auth(&headers, &state.admin_token)?;
|
||||
|
||||
let config_path = state.data_dir.join("config.json");
|
||||
let config_str = serde_json::to_string_pretty(&payload).map_err(|e| {
|
||||
error!("Serialization error: {}", e);
|
||||
AppError::Internal("Serialization error".to_string(), Some(e.to_string()))
|
||||
})?;
|
||||
|
||||
fs::write(&config_path, config_str).map_err(|e| {
|
||||
error!("Write error for config: {}", e);
|
||||
AppError::Internal("Write error".to_string(), Some(e.to_string()))
|
||||
})?;
|
||||
|
||||
Ok(Json(payload))
|
||||
}
|
||||
3
backend/src/handlers/mod.rs
Normal file
3
backend/src/handlers/mod.rs
Normal file
@@ -0,0 +1,3 @@
|
||||
pub mod config;
|
||||
pub mod posts;
|
||||
pub mod upload;
|
||||
105
backend/src/handlers/posts.rs
Normal file
105
backend/src/handlers/posts.rs
Normal file
@@ -0,0 +1,105 @@
|
||||
use axum::{
|
||||
extract::{Path, State},
|
||||
http::{HeaderMap, StatusCode},
|
||||
response::IntoResponse,
|
||||
Json,
|
||||
};
|
||||
use std::{fs, sync::Arc};
|
||||
use tracing::{error, info, warn};
|
||||
|
||||
use crate::{
|
||||
auth::check_auth,
|
||||
error::AppError,
|
||||
models::{CreatePostRequest, PostDetail, PostInfo},
|
||||
AppState,
|
||||
};
|
||||
|
||||
pub async fn create_post(
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
Json(payload): Json<CreatePostRequest>,
|
||||
) -> Result<Json<PostDetail>, AppError> {
|
||||
check_auth(&headers, &state.admin_token)?;
|
||||
|
||||
if payload.slug.contains('/') || payload.slug.contains('\\') || payload.slug.contains("..") {
|
||||
return Err(AppError::BadRequest("Invalid slug".to_string()));
|
||||
}
|
||||
|
||||
let file_path = state.data_dir.join("posts").join(format!("{}.md", payload.slug));
|
||||
|
||||
fs::write(&file_path, &payload.content).map_err(|e| {
|
||||
error!("Write error for post {}: {}", payload.slug, e);
|
||||
AppError::Internal("Write error".to_string(), Some(e.to_string()))
|
||||
})?;
|
||||
|
||||
info!("Post created/updated: {}", payload.slug);
|
||||
Ok(Json(PostDetail {
|
||||
slug: payload.slug,
|
||||
content: payload.content,
|
||||
}))
|
||||
}
|
||||
|
||||
pub async fn delete_post(
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
Path(slug): Path<String>,
|
||||
) -> Result<StatusCode, AppError> {
|
||||
check_auth(&headers, &state.admin_token)?;
|
||||
|
||||
let file_path = state.data_dir.join("posts").join(format!("{}.md", slug));
|
||||
info!("Attempting to delete post at: {:?}", file_path);
|
||||
|
||||
if !file_path.exists() {
|
||||
warn!("Post not found for deletion: {}", slug);
|
||||
return Err(AppError::NotFound("Post not found".to_string()));
|
||||
}
|
||||
|
||||
fs::remove_file(file_path).map_err(|e| {
|
||||
error!("Delete error for post {}: {}", slug, e);
|
||||
AppError::Internal("Delete error".to_string(), Some(e.to_string()))
|
||||
})?;
|
||||
|
||||
info!("Post deleted: {}", slug);
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
pub async fn list_posts(State(state): State<Arc<AppState>>) -> impl IntoResponse {
|
||||
let posts_dir = state.data_dir.join("posts");
|
||||
let mut posts = Vec::new();
|
||||
|
||||
if let Ok(entries) = fs::read_dir(posts_dir) {
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.extension().and_then(|e| e.to_str()) == Some("md") {
|
||||
if let Some(slug) = path.file_stem().and_then(|s| s.to_str()) {
|
||||
let mut excerpt = String::new();
|
||||
if let Ok(content) = fs::read_to_string(&path) {
|
||||
let clean_content = content.replace("#", "").replace("\n", " ");
|
||||
excerpt = clean_content.chars().take(200).collect::<String>();
|
||||
if clean_content.len() > 200 {
|
||||
excerpt.push_str("...");
|
||||
}
|
||||
}
|
||||
posts.push(PostInfo {
|
||||
slug: slug.to_string(),
|
||||
excerpt: excerpt.trim().to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Json(posts)
|
||||
}
|
||||
|
||||
pub async fn get_post(
|
||||
State(state): State<Arc<AppState>>,
|
||||
Path(slug): Path<String>,
|
||||
) -> Result<Json<PostDetail>, AppError> {
|
||||
let file_path = state.data_dir.join("posts").join(format!("{}.md", slug));
|
||||
|
||||
match fs::read_to_string(&file_path) {
|
||||
Ok(content) => Ok(Json(PostDetail { slug, content })),
|
||||
Err(_) => Err(AppError::NotFound("Post not found".to_string())),
|
||||
}
|
||||
}
|
||||
105
backend/src/handlers/upload.rs
Normal file
105
backend/src/handlers/upload.rs
Normal file
@@ -0,0 +1,105 @@
|
||||
use axum::{
|
||||
extract::{Multipart, State},
|
||||
http::HeaderMap,
|
||||
response::IntoResponse,
|
||||
Json,
|
||||
};
|
||||
use std::{fs, sync::Arc};
|
||||
use tracing::{error, info, warn};
|
||||
|
||||
use crate::{
|
||||
auth::check_auth,
|
||||
error::AppError,
|
||||
models::{FileInfo, UploadResponse},
|
||||
AppState,
|
||||
};
|
||||
|
||||
pub async fn list_uploads(
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Json<Vec<FileInfo>>, AppError> {
|
||||
check_auth(&headers, &state.admin_token)?;
|
||||
|
||||
let uploads_dir = state.data_dir.join("uploads");
|
||||
let mut files = Vec::new();
|
||||
|
||||
if let Ok(entries) = fs::read_dir(uploads_dir) {
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_file() {
|
||||
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
|
||||
files.push(FileInfo {
|
||||
name: name.to_string(),
|
||||
url: format!("/uploads/{}", name),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Json(files))
|
||||
}
|
||||
|
||||
pub async fn upload_file(
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
mut multipart: Multipart,
|
||||
) -> Result<Json<UploadResponse>, AppError> {
|
||||
check_auth(&headers, &state.admin_token)?;
|
||||
|
||||
info!("Upload requested");
|
||||
|
||||
while let Ok(Some(field)) = multipart.next_field().await {
|
||||
let file_name = match field.file_name() {
|
||||
Some(name) => name.to_string(),
|
||||
None => continue,
|
||||
};
|
||||
|
||||
info!("Processing upload for: {}", file_name);
|
||||
let slugified_name = slug::slugify(&file_name);
|
||||
|
||||
let extension = std::path::Path::new(&file_name)
|
||||
.extension()
|
||||
.and_then(|e| e.to_str())
|
||||
.unwrap_or("");
|
||||
|
||||
let final_name = if !extension.is_empty() {
|
||||
format!("{}.{}", slugified_name, extension)
|
||||
} else {
|
||||
slugified_name
|
||||
};
|
||||
|
||||
let uploads_dir = state.data_dir.join("uploads");
|
||||
let file_path = uploads_dir.join(&final_name);
|
||||
|
||||
let final_path = if file_path.exists() {
|
||||
let timestamp = chrono::Utc::now().timestamp();
|
||||
uploads_dir.join(format!("{}_{}", timestamp, final_name))
|
||||
} else {
|
||||
file_path
|
||||
};
|
||||
|
||||
let final_name_str = final_path.file_name().unwrap().to_str().unwrap().to_string();
|
||||
|
||||
let data = match field.bytes().await {
|
||||
Ok(bytes) => bytes,
|
||||
Err(e) => {
|
||||
error!("Failed to read multipart bytes: {}", e);
|
||||
return Err(AppError::BadRequest(format!("Read error: {}", e)));
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(e) = fs::write(&final_path, &data) {
|
||||
error!("Failed to write file to {:?}: {}", final_path, e);
|
||||
return Err(AppError::Internal("Write error".to_string(), Some(e.to_string())));
|
||||
}
|
||||
|
||||
info!("File uploaded successfully to {:?}", final_path);
|
||||
return Ok(Json(UploadResponse {
|
||||
url: format!("/uploads/{}", final_name_str),
|
||||
}));
|
||||
}
|
||||
|
||||
warn!("Upload failed: no file found in multipart stream");
|
||||
Err(AppError::BadRequest("No file found".to_string()))
|
||||
}
|
||||
@@ -1,84 +1,24 @@
|
||||
pub mod auth;
|
||||
pub mod error;
|
||||
pub mod handlers;
|
||||
pub mod models;
|
||||
|
||||
use axum::{
|
||||
Router,
|
||||
extract::{DefaultBodyLimit, Multipart, Path, State},
|
||||
http::{HeaderMap, StatusCode},
|
||||
response::{IntoResponse, Json},
|
||||
extract::DefaultBodyLimit,
|
||||
routing::{delete, get, post},
|
||||
Router,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{env, fs, path::PathBuf, sync::Arc};
|
||||
use tower_http::{
|
||||
cors::{Any, CorsLayer},
|
||||
services::ServeDir,
|
||||
};
|
||||
use tracing::{error, info, warn};
|
||||
use tracing::{error, info};
|
||||
|
||||
#[derive(Clone)]
|
||||
struct AppState {
|
||||
admin_token: String,
|
||||
data_dir: PathBuf,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone)]
|
||||
struct SiteConfig {
|
||||
title: String,
|
||||
subtitle: String,
|
||||
welcome_title: String,
|
||||
welcome_subtitle: String,
|
||||
footer: String,
|
||||
favicon: String,
|
||||
theme: String,
|
||||
custom_css: String,
|
||||
}
|
||||
|
||||
impl Default for SiteConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
title: "Narlblog".to_string(),
|
||||
subtitle: "A clean, modern blog".to_string(),
|
||||
welcome_title: "Welcome to my blog".to_string(),
|
||||
welcome_subtitle: "Thoughts on software, design, and building things with Rust and Astro.".to_string(),
|
||||
footer: "Built with Rust & Astro".to_string(),
|
||||
favicon: "/favicon.svg".to_string(),
|
||||
theme: "mocha".to_string(),
|
||||
custom_css: "".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct PostInfo {
|
||||
slug: String,
|
||||
excerpt: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct PostDetail {
|
||||
slug: String,
|
||||
content: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct CreatePostRequest {
|
||||
slug: String,
|
||||
content: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct ErrorResponse {
|
||||
error: String,
|
||||
details: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct UploadResponse {
|
||||
url: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct FileInfo {
|
||||
name: String,
|
||||
url: String,
|
||||
pub struct AppState {
|
||||
pub admin_token: String,
|
||||
pub data_dir: PathBuf,
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
@@ -114,11 +54,11 @@ async fn main() {
|
||||
.allow_headers(Any);
|
||||
|
||||
let app = Router::new()
|
||||
.route("/api/config", get(get_config).post(update_config))
|
||||
.route("/api/posts", get(list_posts).post(create_post))
|
||||
.route("/api/posts/{slug}", get(get_post).delete(delete_post))
|
||||
.route("/api/uploads", get(list_uploads))
|
||||
.route("/api/upload", post(upload_file))
|
||||
.route("/api/config", get(handlers::config::get_config).post(handlers::config::update_config))
|
||||
.route("/api/posts", get(handlers::posts::list_posts).post(handlers::posts::create_post))
|
||||
.route("/api/posts/{slug}", get(handlers::posts::get_post).delete(handlers::posts::delete_post))
|
||||
.route("/api/uploads", get(handlers::upload::list_uploads))
|
||||
.route("/api/upload", post(handlers::upload::upload_file))
|
||||
.nest_service("/uploads", ServeDir::new(uploads_dir))
|
||||
.layer(DefaultBodyLimit::max(50 * 1024 * 1024))
|
||||
.layer(cors)
|
||||
@@ -129,302 +69,3 @@ async fn main() {
|
||||
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
|
||||
axum::serve(listener, app).await.unwrap();
|
||||
}
|
||||
|
||||
fn check_auth(
|
||||
headers: &HeaderMap,
|
||||
admin_token: &str,
|
||||
) -> Result<(), (StatusCode, Json<ErrorResponse>)> {
|
||||
let auth_header = headers.get("Authorization").and_then(|h| h.to_str().ok());
|
||||
if auth_header != Some(&format!("Bearer {}", admin_token)) {
|
||||
warn!("Unauthorized access attempt detected");
|
||||
return Err((
|
||||
StatusCode::UNAUTHORIZED,
|
||||
Json(ErrorResponse {
|
||||
error: "Unauthorized".to_string(),
|
||||
details: None,
|
||||
}),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn get_config(State(state): State<Arc<AppState>>) -> impl IntoResponse {
|
||||
let config_path = state.data_dir.join("config.json");
|
||||
let config = fs::read_to_string(&config_path)
|
||||
.ok()
|
||||
.and_then(|c| serde_json::from_str::<SiteConfig>(&c).ok())
|
||||
.unwrap_or_default();
|
||||
|
||||
Json(config)
|
||||
}
|
||||
|
||||
async fn update_config(
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
Json(payload): Json<SiteConfig>,
|
||||
) -> Result<Json<SiteConfig>, (StatusCode, Json<ErrorResponse>)> {
|
||||
check_auth(&headers, &state.admin_token)?;
|
||||
|
||||
let config_path = state.data_dir.join("config.json");
|
||||
let config_str = serde_json::to_string_pretty(&payload).map_err(|e| {
|
||||
error!("Serialization error: {}", e);
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(ErrorResponse {
|
||||
error: "Serialization error".to_string(),
|
||||
details: Some(e.to_string()),
|
||||
}),
|
||||
)
|
||||
})?;
|
||||
|
||||
fs::write(&config_path, config_str).map_err(|e| {
|
||||
error!("Write error for config: {}", e);
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(ErrorResponse {
|
||||
error: "Write error".to_string(),
|
||||
details: Some(e.to_string()),
|
||||
}),
|
||||
)
|
||||
})?;
|
||||
|
||||
Ok(Json(payload))
|
||||
}
|
||||
|
||||
async fn create_post(
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
Json(payload): Json<CreatePostRequest>,
|
||||
) -> Result<Json<PostDetail>, (StatusCode, Json<ErrorResponse>)> {
|
||||
check_auth(&headers, &state.admin_token)?;
|
||||
|
||||
if payload.slug.contains('/') || payload.slug.contains('\\') || payload.slug.contains("..") {
|
||||
return Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(ErrorResponse {
|
||||
error: "Invalid slug".to_string(),
|
||||
details: None,
|
||||
}),
|
||||
));
|
||||
}
|
||||
|
||||
let file_path = state
|
||||
.data_dir
|
||||
.join("posts")
|
||||
.join(format!("{}.md", payload.slug));
|
||||
|
||||
fs::write(&file_path, &payload.content).map_err(|e| {
|
||||
error!("Write error for post {}: {}", payload.slug, e);
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(ErrorResponse {
|
||||
error: "Write error".to_string(),
|
||||
details: Some(e.to_string()),
|
||||
}),
|
||||
)
|
||||
})?;
|
||||
|
||||
info!("Post created/updated: {}", payload.slug);
|
||||
Ok(Json(PostDetail {
|
||||
slug: payload.slug,
|
||||
content: payload.content,
|
||||
}))
|
||||
}
|
||||
|
||||
async fn delete_post(
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
Path(slug): Path<String>,
|
||||
) -> Result<StatusCode, (StatusCode, Json<ErrorResponse>)> {
|
||||
check_auth(&headers, &state.admin_token)?;
|
||||
|
||||
let file_path = state.data_dir.join("posts").join(format!("{}.md", slug));
|
||||
info!("Attempting to delete post at: {:?}", file_path);
|
||||
|
||||
if !file_path.exists() {
|
||||
warn!("Post not found for deletion: {}", slug);
|
||||
return Err((
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(ErrorResponse {
|
||||
error: "Post not found".to_string(),
|
||||
details: None,
|
||||
}),
|
||||
));
|
||||
}
|
||||
|
||||
fs::remove_file(file_path).map_err(|e| {
|
||||
error!("Delete error for post {}: {}", slug, e);
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(ErrorResponse {
|
||||
error: "Delete error".to_string(),
|
||||
details: Some(e.to_string()),
|
||||
}),
|
||||
)
|
||||
})?;
|
||||
|
||||
info!("Post deleted: {}", slug);
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
async fn list_uploads(
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Json<Vec<FileInfo>>, (StatusCode, Json<ErrorResponse>)> {
|
||||
check_auth(&headers, &state.admin_token)?;
|
||||
|
||||
let uploads_dir = state.data_dir.join("uploads");
|
||||
let mut files = Vec::new();
|
||||
|
||||
if let Ok(entries) = fs::read_dir(uploads_dir) {
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_file() {
|
||||
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
|
||||
files.push(FileInfo {
|
||||
name: name.to_string(),
|
||||
url: format!("/uploads/{}", name),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Json(files))
|
||||
}
|
||||
|
||||
async fn list_posts(State(state): State<Arc<AppState>>) -> impl IntoResponse {
|
||||
let posts_dir = state.data_dir.join("posts");
|
||||
let mut posts = Vec::new();
|
||||
|
||||
if let Ok(entries) = fs::read_dir(posts_dir) {
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.extension().and_then(|e| e.to_str()) == Some("md") {
|
||||
if let Some(slug) = path.file_stem().and_then(|s| s.to_str()) {
|
||||
let mut excerpt = String::new();
|
||||
if let Ok(content) = fs::read_to_string(&path) {
|
||||
// Strip basic markdown hashes and get first ~200 chars
|
||||
let clean_content = content.replace("#", "").replace("\n", " ");
|
||||
excerpt = clean_content.chars().take(200).collect::<String>();
|
||||
if clean_content.len() > 200 {
|
||||
excerpt.push_str("...");
|
||||
}
|
||||
}
|
||||
posts.push(PostInfo {
|
||||
slug: slug.to_string(),
|
||||
excerpt: excerpt.trim().to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Json(posts)
|
||||
}
|
||||
|
||||
async fn get_post(
|
||||
State(state): State<Arc<AppState>>,
|
||||
Path(slug): Path<String>,
|
||||
) -> Result<Json<PostDetail>, (StatusCode, Json<ErrorResponse>)> {
|
||||
let file_path = state.data_dir.join("posts").join(format!("{}.md", slug));
|
||||
|
||||
match fs::read_to_string(&file_path) {
|
||||
Ok(content) => Ok(Json(PostDetail { slug, content })),
|
||||
Err(_) => Err((
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(ErrorResponse {
|
||||
error: "Post not found".to_string(),
|
||||
details: None,
|
||||
}),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
async fn upload_file(
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
mut multipart: Multipart,
|
||||
) -> Result<Json<UploadResponse>, (StatusCode, Json<ErrorResponse>)> {
|
||||
check_auth(&headers, &state.admin_token)?;
|
||||
|
||||
info!("Upload requested");
|
||||
|
||||
while let Ok(Some(field)) = multipart.next_field().await {
|
||||
let file_name = match field.file_name() {
|
||||
Some(name) => name.to_string(),
|
||||
None => continue,
|
||||
};
|
||||
|
||||
info!("Processing upload for: {}", file_name);
|
||||
let slugified_name = slug::slugify(&file_name);
|
||||
|
||||
// Handle extension correctly after slugifying
|
||||
let extension = std::path::Path::new(&file_name)
|
||||
.extension()
|
||||
.and_then(|e| e.to_str())
|
||||
.unwrap_or("");
|
||||
|
||||
let final_name = if !extension.is_empty() {
|
||||
format!("{}.{}", slugified_name, extension)
|
||||
} else {
|
||||
slugified_name
|
||||
};
|
||||
|
||||
let uploads_dir = state.data_dir.join("uploads");
|
||||
let file_path = uploads_dir.join(&final_name);
|
||||
|
||||
let final_path = if file_path.exists() {
|
||||
let timestamp = chrono::Utc::now().timestamp();
|
||||
uploads_dir.join(format!("{}_{}", timestamp, final_name))
|
||||
} else {
|
||||
file_path
|
||||
};
|
||||
|
||||
let final_name_str = final_path
|
||||
.file_name()
|
||||
.unwrap()
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_string();
|
||||
|
||||
let data = match field.bytes().await {
|
||||
Ok(bytes) => bytes,
|
||||
Err(e) => {
|
||||
error!("Failed to read multipart bytes: {}", e);
|
||||
return Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(ErrorResponse {
|
||||
error: "Read error".to_string(),
|
||||
details: Some(e.to_string()),
|
||||
}),
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(e) = fs::write(&final_path, &data) {
|
||||
error!("Failed to write file to {:?}: {}", final_path, e);
|
||||
return Err((
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(ErrorResponse {
|
||||
error: "Write error".to_string(),
|
||||
details: Some(e.to_string()),
|
||||
}),
|
||||
));
|
||||
}
|
||||
|
||||
info!("File uploaded successfully to {:?}", final_path);
|
||||
return Ok(Json(UploadResponse {
|
||||
url: format!("/uploads/{}", final_name_str),
|
||||
}));
|
||||
}
|
||||
|
||||
warn!("Upload failed: no file found in multipart stream");
|
||||
Err((
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(ErrorResponse {
|
||||
error: "No file found".to_string(),
|
||||
details: None,
|
||||
}),
|
||||
))
|
||||
}
|
||||
|
||||
64
backend/src/models.rs
Normal file
64
backend/src/models.rs
Normal file
@@ -0,0 +1,64 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone)]
|
||||
pub struct SiteConfig {
|
||||
pub title: String,
|
||||
pub subtitle: String,
|
||||
pub welcome_title: String,
|
||||
pub welcome_subtitle: String,
|
||||
pub footer: String,
|
||||
pub favicon: String,
|
||||
pub theme: String,
|
||||
pub custom_css: String,
|
||||
}
|
||||
|
||||
impl Default for SiteConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
title: "Narlblog".to_string(),
|
||||
subtitle: "A clean, modern blog".to_string(),
|
||||
welcome_title: "Welcome to my blog".to_string(),
|
||||
welcome_subtitle: "Thoughts on software, design, and building things with Rust and Astro.".to_string(),
|
||||
footer: "Built with Rust & Astro".to_string(),
|
||||
favicon: "/favicon.svg".to_string(),
|
||||
theme: "mocha".to_string(),
|
||||
custom_css: "".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct PostInfo {
|
||||
pub slug: String,
|
||||
pub excerpt: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct PostDetail {
|
||||
pub slug: String,
|
||||
pub content: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct CreatePostRequest {
|
||||
pub slug: String,
|
||||
pub content: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct ErrorResponse {
|
||||
pub error: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub details: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct UploadResponse {
|
||||
pub url: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct FileInfo {
|
||||
pub name: String,
|
||||
pub url: String,
|
||||
}
|
||||
25
frontend/src/components/PostCard.astro
Normal file
25
frontend/src/components/PostCard.astro
Normal file
@@ -0,0 +1,25 @@
|
||||
---
|
||||
interface Props {
|
||||
slug: string;
|
||||
excerpt?: string;
|
||||
formatSlug: (slug: string) => string;
|
||||
}
|
||||
|
||||
const { slug, excerpt, formatSlug } = Astro.props;
|
||||
---
|
||||
|
||||
<a href={`/posts/${slug}`} class="group block">
|
||||
<article class="glass p-5 md:p-8 transition-all hover:scale-[1.01] hover:bg-surface0/80 active:scale-[0.99] flex flex-col md:flex-row justify-between md:items-center gap-4 md:gap-6">
|
||||
<div class="flex-1">
|
||||
<h2 class="text-xl md:text-3xl font-bold text-lavender group-hover:text-mauve transition-colors mb-2 md:mb-3">
|
||||
{formatSlug(slug)}
|
||||
</h2>
|
||||
<p class="text-text text-sm md:text-base leading-relaxed line-clamp-3">
|
||||
{excerpt || `Read more about ${formatSlug(slug)}...`}
|
||||
</p>
|
||||
</div>
|
||||
<div class="text-mauve opacity-0 group-hover:opacity-100 transition-opacity self-end md:self-auto shrink-0 hidden md:block">
|
||||
<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" class="md:w-8 md:h-8"><path d="M5 12h14"/><path d="m12 5 7 7-7 7"/></svg>
|
||||
</div>
|
||||
</article>
|
||||
</a>
|
||||
18
frontend/src/components/ui/Alert.ts
Normal file
18
frontend/src/components/ui/Alert.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
export function showAlert(msg: string, type: 'success' | 'error', elementId: string = 'alert') {
|
||||
const alertEl = document.getElementById(elementId);
|
||||
if (alertEl) {
|
||||
alertEl.textContent = msg;
|
||||
alertEl.className = `p-4 rounded-lg mb-6 text-sm md:text-base ${
|
||||
type === 'success'
|
||||
? 'bg-green/20 text-green border border-green/30'
|
||||
: 'bg-red/20 text-red border border-red/30'
|
||||
}`;
|
||||
alertEl.classList.remove('hidden');
|
||||
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' });
|
||||
|
||||
setTimeout(() => {
|
||||
alertEl.classList.add('hidden');
|
||||
}, 5000);
|
||||
}
|
||||
}
|
||||
45
frontend/src/layouts/AdminLayout.astro
Normal file
45
frontend/src/layouts/AdminLayout.astro
Normal file
@@ -0,0 +1,45 @@
|
||||
---
|
||||
import Layout from './Layout.astro';
|
||||
|
||||
interface Props {
|
||||
title: string;
|
||||
}
|
||||
|
||||
const { title } = Astro.props;
|
||||
---
|
||||
|
||||
<Layout title={title}>
|
||||
<div class="glass p-6 md:p-12 mb-12" id="admin-content" style="display: none;">
|
||||
<header class="mb-8 md:mb-12 border-b border-white/5 pb-8 md:pb-12 flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
|
||||
<div>
|
||||
<a href="/admin" class="text-blue hover:text-sky transition-colors mb-4 md:mb-8 inline-flex items-center gap-2 group text-sm md:text-base">
|
||||
<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" class="md:w-5 md:h-5 transition-transform group-hover:-translate-x-1"><path d="m15 18-6-6 6-6"/></svg>
|
||||
Dashboard
|
||||
</a>
|
||||
<h1 class="text-3xl md:text-4xl font-extrabold text-mauve">
|
||||
{title}
|
||||
</h1>
|
||||
<slot name="header-subtitle" />
|
||||
</div>
|
||||
|
||||
<div class="flex gap-4 w-full md:w-auto">
|
||||
<slot name="header-actions" />
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<slot />
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const token = localStorage.getItem('admin_token');
|
||||
if (!token) {
|
||||
window.location.href = '/admin/login';
|
||||
} else {
|
||||
const content = document.getElementById('admin-content');
|
||||
if (content) content.style.display = 'block';
|
||||
|
||||
// Dispatch custom event for child components to know token is ready
|
||||
document.dispatchEvent(new CustomEvent('admin-auth-ready', { detail: { token } }));
|
||||
}
|
||||
</script>
|
||||
</Layout>
|
||||
@@ -1,110 +1,95 @@
|
||||
---
|
||||
import Layout from '../../layouts/Layout.astro';
|
||||
import AdminLayout from '../../layouts/AdminLayout.astro';
|
||||
---
|
||||
|
||||
<Layout title="Post Editor">
|
||||
<AdminLayout title="Write Post">
|
||||
<!-- CodeMirror Assets -->
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/codemirror.min.css">
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/theme/catppuccin.min.css">
|
||||
<script is:inline src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/codemirror.min.js"></script>
|
||||
<script is:inline src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/mode/markdown/markdown.min.js"></script>
|
||||
<script is:inline src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/keymap/vim.min.js"></script>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/codemirror.min.css" slot="header-subtitle">
|
||||
<script is:inline src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/codemirror.min.js" slot="header-subtitle"></script>
|
||||
<script is:inline src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/mode/markdown/markdown.min.js" slot="header-subtitle"></script>
|
||||
<script is:inline src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/keymap/vim.min.js" slot="header-subtitle"></script>
|
||||
|
||||
<div class="glass p-12 mb-12" id="editor-content" style="display: none;">
|
||||
<header class="mb-12 border-b border-white/5 pb-12 flex justify-between items-center">
|
||||
<div>
|
||||
<a href="/admin" class="text-blue hover:text-sky transition-colors mb-8 inline-flex items-center gap-2 group">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="transition-transform group-hover:-translate-x-1"><path d="m15 18-6-6 6-6"/></svg>
|
||||
Back to Dashboard
|
||||
</a>
|
||||
<h1 class="text-4xl font-extrabold text-mauve mt-4">
|
||||
Write Post
|
||||
</h1>
|
||||
</div>
|
||||
|
||||
<div class="flex gap-4">
|
||||
<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">
|
||||
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"
|
||||
>
|
||||
Save Post
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
<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>
|
||||
</div>
|
||||
|
||||
<div id="alert" class="hidden p-4 rounded-lg mb-6"></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 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 class="relative">
|
||||
<div class="flex justify-between items-end mb-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">
|
||||
<button
|
||||
id="browse-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>
|
||||
Library
|
||||
</button>
|
||||
<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="cursor-pointer text-sm bg-surface0 hover:bg-surface1 text-blue 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"><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 File
|
||||
</label>
|
||||
</div>
|
||||
<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>
|
||||
<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>
|
||||
<!-- 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-6">
|
||||
<div class="glass w-full max-w-4xl max-h-[80vh] flex flex-col overflow-hidden">
|
||||
<header class="p-6 border-b border-white/5 flex justify-between items-center bg-surface0/20">
|
||||
<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-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>
|
||||
</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-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">
|
||||
<!-- Assets injected here -->
|
||||
</div>
|
||||
@@ -117,293 +102,251 @@ import Layout from '../../layouts/Layout.astro';
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const token = localStorage.getItem('admin_token');
|
||||
if (!token) {
|
||||
window.location.href = '/admin/login';
|
||||
} else {
|
||||
document.getElementById('editor-content')!.style.display = 'block';
|
||||
}
|
||||
import { showAlert } from '../../components/ui/Alert';
|
||||
|
||||
const slugInput = document.getElementById('slug') as HTMLInputElement;
|
||||
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 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');
|
||||
|
||||
// Initialize CodeMirror
|
||||
// @ts-ignore
|
||||
const editor = CodeMirror.fromTextArea(contentInput, {
|
||||
mode: 'markdown',
|
||||
theme: 'default',
|
||||
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 (e) {
|
||||
console.error("Failed to fetch assets", e);
|
||||
}
|
||||
}
|
||||
|
||||
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 = '';
|
||||
document.addEventListener('admin-auth-ready', (e: any) => {
|
||||
const token = e.detail.token;
|
||||
|
||||
if (allAssets.length === 0) {
|
||||
assetsEmpty.classList.remove('hidden');
|
||||
return;
|
||||
}
|
||||
assetsEmpty.classList.add('hidden');
|
||||
const slugInput = document.getElementById('slug') as HTMLInputElement;
|
||||
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 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');
|
||||
|
||||
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);
|
||||
// @ts-ignore
|
||||
const editor = CodeMirror.fromTextArea(contentInput, {
|
||||
mode: 'markdown',
|
||||
theme: 'narlblog',
|
||||
lineWrapping: true,
|
||||
keyMap: window.innerWidth > 768 ? 'vim' : 'default',
|
||||
extraKeys: {"Enter": "newlineAndIndentContinueMarkdownList"}
|
||||
});
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
let allAssets: {name: string, url: string}[] = [];
|
||||
|
||||
// Autocomplete on '/' or '!' inside CodeMirror
|
||||
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');
|
||||
}
|
||||
|
||||
// Close autocomplete on click outside
|
||||
window.addEventListener('click', (e) => {
|
||||
if (!autocomplete?.contains(e.target as Node)) {
|
||||
hideAutocomplete();
|
||||
}
|
||||
});
|
||||
|
||||
fileInput?.addEventListener('change', async (e) => {
|
||||
const file = (e.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 (e) {
|
||||
showAlert('Network error during upload.', 'error');
|
||||
}
|
||||
fileInput.value = '';
|
||||
});
|
||||
|
||||
saveBtn?.addEventListener('click', async () => {
|
||||
const payload = { slug: slugInput.value, 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');
|
||||
else showAlert('Error saving post.', 'error');
|
||||
} catch (e) {
|
||||
showAlert('Failed to connect to server.', 'error');
|
||||
}
|
||||
});
|
||||
|
||||
delBtn?.addEventListener('click', async () => {
|
||||
if (confirm(`Delete post "${slugInput.value}" permanently?`)) {
|
||||
async function fetchAssets() {
|
||||
try {
|
||||
const res = await fetch(`/api/posts/${encodeURIComponent(slugInput.value)}`, {
|
||||
method: 'DELETE',
|
||||
const res = await fetch('/api/uploads', {
|
||||
headers: { 'Authorization': `Bearer ${token}` }
|
||||
});
|
||||
if (res.ok) window.location.href = '/admin';
|
||||
else showAlert('Error deleting post.', 'error');
|
||||
if (res.ok) {
|
||||
allAssets = await res.json();
|
||||
}
|
||||
} catch (e) {
|
||||
showAlert('Connection error.', 'error');
|
||||
console.error("Failed to fetch assets", e);
|
||||
}
|
||||
}
|
||||
|
||||
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', (e) => {
|
||||
if (!autocomplete?.contains(e.target as Node)) {
|
||||
hideAutocomplete();
|
||||
}
|
||||
});
|
||||
|
||||
fileInput?.addEventListener('change', async (e) => {
|
||||
const file = (e.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 (e) {
|
||||
showAlert('Network error during upload.', 'error');
|
||||
}
|
||||
fileInput.value = '';
|
||||
});
|
||||
|
||||
saveBtn?.addEventListener('click', async () => {
|
||||
const payload = { slug: slugInput.value, 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');
|
||||
else showAlert('Error saving post.', 'error');
|
||||
} catch (e) {
|
||||
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 (e) {
|
||||
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');
|
||||
fetch(`/api/posts/${encodeURIComponent(editSlug)}`)
|
||||
.then(res => res.json())
|
||||
.then(data => {
|
||||
if (data.content) {
|
||||
editor.setValue(data.content);
|
||||
}
|
||||
})
|
||||
.catch(() => showAlert('Failed to load post.', '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');
|
||||
fetch(`/api/posts/${encodeURIComponent(editSlug)}`)
|
||||
.then(res => res.json())
|
||||
.then(data => {
|
||||
if (data.content) {
|
||||
editor.setValue(data.content);
|
||||
}
|
||||
})
|
||||
.catch(() => showAlert('Failed to load post.', 'error'));
|
||||
}
|
||||
|
||||
function showAlert(msg: string, type: 'success' | 'error') {
|
||||
const alertEl = document.getElementById('alert');
|
||||
if (alertEl) {
|
||||
alertEl.textContent = msg;
|
||||
alertEl.className = `p-4 rounded-lg mb-6 ${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);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
</Layout>
|
||||
ect slug on edit
|
||||
delBtn?.classList.remove('hidden');
|
||||
fetch(`/api/posts/${encodeURIComponent(editSlug)}`)
|
||||
.then(res => res.json())
|
||||
.then(data => {
|
||||
if (data.content) {
|
||||
editor.setValue(data.content);
|
||||
}
|
||||
})
|
||||
.catch(() => showAlert('Failed to load post.', 'error'));
|
||||
}
|
||||
|
||||
function showAlert(msg: string, type: 'success' | 'error') {
|
||||
const alertEl = document.getElementById('alert');
|
||||
if (alertEl) {
|
||||
alertEl.textContent = msg;
|
||||
alertEl.className = `p-4 rounded-lg mb-6 ${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);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
</Layout>
|
||||
setTimeout(() => { alertEl.classList.add('hidden'); }, 4000);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
</Layout>
|
||||
</AdminLayout>
|
||||
|
||||
@@ -1,135 +1,125 @@
|
||||
---
|
||||
import Layout from '../../layouts/Layout.astro';
|
||||
import AdminLayout from '../../layouts/AdminLayout.astro';
|
||||
---
|
||||
|
||||
<Layout title="Admin Dashboard">
|
||||
<div class="glass p-12 mb-12" id="admin-content" style="display: none;">
|
||||
<header class="mb-12 border-b border-white/5 pb-12 flex justify-between items-center">
|
||||
<h1 class="text-4xl font-extrabold text-mauve">
|
||||
Admin Dashboard
|
||||
</h1>
|
||||
<button id="logout-btn" class="text-red hover:text-maroon transition-colors font-medium">
|
||||
Logout
|
||||
</button>
|
||||
</header>
|
||||
<AdminLayout title="Admin Dashboard">
|
||||
<button slot="header-actions" id="logout-btn" class="text-red hover:text-maroon transition-colors font-medium">
|
||||
Logout
|
||||
</button>
|
||||
|
||||
<div class="grid md:grid-cols-2 gap-8 mb-12">
|
||||
<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-mauve/20 p-4 rounded-lg 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>
|
||||
</div>
|
||||
<div>
|
||||
<h2 class="text-2xl font-bold text-lavender group-hover:text-mauve transition-colors">Write a Post</h2>
|
||||
<p class="text-subtext0">Create or edit markdown posts and upload any file.</p>
|
||||
</div>
|
||||
<div class="grid md:grid-cols-2 gap-8 mb-12">
|
||||
<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-mauve/20 p-4 rounded-lg 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>
|
||||
</div>
|
||||
</a>
|
||||
|
||||
<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-blue/20 p-4 rounded-lg 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>
|
||||
</div>
|
||||
<div>
|
||||
<h2 class="text-2xl font-bold text-blue mb-2 group-hover:text-sky transition-colors">Site Settings</h2>
|
||||
<p class="text-subtext0">Update title, favicon, and global theme.</p>
|
||||
</div>
|
||||
</div>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<section>
|
||||
<h2 class="text-2xl font-bold text-mauve mb-6 flex items-center gap-3">
|
||||
<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="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/></svg>
|
||||
Manage Posts
|
||||
</h2>
|
||||
<div id="posts-list" class="space-y-4">
|
||||
<!-- Posts will be loaded here -->
|
||||
<div class="animate-pulse flex space-x-4 p-8 glass">
|
||||
<div class="flex-1 space-y-4 py-1">
|
||||
<div class="h-4 bg-surface1 rounded w-3/4"></div>
|
||||
<div class="h-4 bg-surface1 rounded w-1/2"></div>
|
||||
</div>
|
||||
<div>
|
||||
<h2 class="text-2xl font-bold text-lavender group-hover:text-mauve transition-colors">Write a Post</h2>
|
||||
<p class="text-subtext0">Create or edit markdown posts and upload any file.</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</a>
|
||||
|
||||
<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-blue/20 p-4 rounded-lg 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>
|
||||
</div>
|
||||
<div>
|
||||
<h2 class="text-2xl font-bold text-blue mb-2 group-hover:text-sky transition-colors">Site Settings</h2>
|
||||
<p class="text-subtext0">Update title, favicon, and global theme.</p>
|
||||
</div>
|
||||
</div>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<section>
|
||||
<h2 class="text-2xl font-bold text-mauve mb-6 flex items-center gap-3">
|
||||
<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="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/></svg>
|
||||
Manage Posts
|
||||
</h2>
|
||||
<div id="posts-list" class="space-y-4">
|
||||
<!-- Posts will be loaded here -->
|
||||
<div class="animate-pulse flex space-x-4 p-8 glass">
|
||||
<div class="flex-1 space-y-4 py-1">
|
||||
<div class="h-4 bg-surface1 rounded w-3/4"></div>
|
||||
<div class="h-4 bg-surface1 rounded w-1/2"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<script>
|
||||
const token = localStorage.getItem('admin_token');
|
||||
if (!token) {
|
||||
window.location.href = '/admin/login';
|
||||
} else {
|
||||
const content = document.getElementById('admin-content');
|
||||
if (content) content.style.display = 'block';
|
||||
import { showAlert } from '../../components/ui/Alert';
|
||||
|
||||
document.addEventListener('admin-auth-ready', (e: any) => {
|
||||
const token = e.detail.token;
|
||||
loadPosts();
|
||||
}
|
||||
|
||||
async function loadPosts() {
|
||||
const postsList = document.getElementById('posts-list');
|
||||
if (!postsList) return;
|
||||
async function loadPosts() {
|
||||
const postsList = document.getElementById('posts-list');
|
||||
if (!postsList) return;
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/posts');
|
||||
if (res.ok) {
|
||||
const posts = await res.json();
|
||||
if (posts.length === 0) {
|
||||
postsList.innerHTML = '<div class="glass p-8 text-center text-subtext0">No posts yet.</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
postsList.innerHTML = '';
|
||||
posts.forEach((post: {slug: string}) => {
|
||||
const div = document.createElement('div');
|
||||
div.className = "glass p-6 flex justify-between items-center group hover:bg-surface0/50 transition-colors";
|
||||
div.innerHTML = `
|
||||
<div>
|
||||
<h3 class="font-bold text-lavender text-lg">${post.slug}</h3>
|
||||
<p class="text-xs text-subtext0">/posts/${post.slug}</p>
|
||||
</div>
|
||||
<div class="flex gap-3">
|
||||
<a href="/admin/editor?edit=${post.slug}" class="p-2 text-blue hover:bg-blue/10 rounded transition-colors" title="Edit">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"/><path d="m15 5 4 4"/></svg>
|
||||
</a>
|
||||
<button class="p-2 text-red hover:bg-red/10 rounded transition-colors delete-btn" data-slug="${post.slug}" title="Delete">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" 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"/><line x1="10" x2="10" y1="11" y2="17"/><line x1="14" x2="14" y1="11" y2="17"/></svg>
|
||||
</button>
|
||||
</div>
|
||||
`;
|
||||
postsList.appendChild(div);
|
||||
});
|
||||
|
||||
// Handle delete
|
||||
document.querySelectorAll('.delete-btn').forEach(btn => {
|
||||
btn.addEventListener('click', async (e) => {
|
||||
const slug = (e.currentTarget as HTMLElement).dataset.slug;
|
||||
if (confirm(`Are you sure you want to delete "${slug}"?`)) {
|
||||
try {
|
||||
const delRes = await fetch(`/api/posts/${encodeURIComponent(slug)}`, {
|
||||
method: 'DELETE',
|
||||
headers: { 'Authorization': `Bearer ${token}` }
|
||||
});
|
||||
if (delRes.ok) {
|
||||
loadPosts();
|
||||
} else {
|
||||
alert('Failed to delete post.');
|
||||
}
|
||||
} catch (err) {
|
||||
alert('Error connecting to server.');
|
||||
}
|
||||
}
|
||||
try {
|
||||
const res = await fetch('/api/posts');
|
||||
if (res.ok) {
|
||||
const posts = await res.json();
|
||||
if (posts.length === 0) {
|
||||
postsList.innerHTML = '<div class="glass p-8 text-center text-subtext0">No posts yet.</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
postsList.innerHTML = '';
|
||||
posts.forEach((post: {slug: string}) => {
|
||||
const div = document.createElement('div');
|
||||
div.className = "glass p-6 flex justify-between items-center group hover:bg-surface0/50 transition-colors";
|
||||
div.innerHTML = `
|
||||
<div>
|
||||
<h3 class="font-bold text-lavender text-lg">${post.slug}</h3>
|
||||
<p class="text-xs text-subtext0">/posts/${post.slug}</p>
|
||||
</div>
|
||||
<div class="flex gap-3">
|
||||
<a href="/admin/editor?edit=${post.slug}" class="p-2 text-blue hover:bg-blue/10 rounded transition-colors" title="Edit">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"/><path d="m15 5 4 4"/></svg>
|
||||
</a>
|
||||
<button class="p-2 text-red hover:bg-red/10 rounded transition-colors delete-btn" data-slug="${post.slug}" title="Delete">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" 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"/><line x1="10" x2="10" y1="11" y2="17"/><line x1="14" x2="14" y1="11" y2="17"/></svg>
|
||||
</button>
|
||||
</div>
|
||||
`;
|
||||
postsList.appendChild(div);
|
||||
});
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
postsList.innerHTML = '<div class="glass p-8 text-center text-red">Failed to load posts.</div>';
|
||||
}
|
||||
}
|
||||
|
||||
document.getElementById('logout-btn')?.addEventListener('click', () => {
|
||||
localStorage.removeItem('admin_token');
|
||||
window.location.href = '/';
|
||||
document.querySelectorAll('.delete-btn').forEach(btn => {
|
||||
btn.addEventListener('click', async (ev) => {
|
||||
const slug = (ev.currentTarget as HTMLElement).dataset.slug;
|
||||
if (confirm(`Are you sure you want to delete "${slug}"?`)) {
|
||||
try {
|
||||
const delRes = await fetch(`/api/posts/${encodeURIComponent(slug as string)}`, {
|
||||
method: 'DELETE',
|
||||
headers: { 'Authorization': `Bearer ${token}` }
|
||||
});
|
||||
if (delRes.ok) {
|
||||
loadPosts();
|
||||
} else {
|
||||
showAlert('Failed to delete post.', 'error');
|
||||
}
|
||||
} catch (err) {
|
||||
showAlert('Error connecting to server.', 'error');
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
postsList.innerHTML = '<div class="glass p-8 text-center text-red">Failed to load posts.</div>';
|
||||
}
|
||||
}
|
||||
|
||||
document.getElementById('logout-btn')?.addEventListener('click', () => {
|
||||
localStorage.removeItem('admin_token');
|
||||
window.location.href = '/';
|
||||
});
|
||||
});
|
||||
</script>
|
||||
</Layout>
|
||||
</AdminLayout>
|
||||
|
||||
@@ -1,150 +1,131 @@
|
||||
---
|
||||
import Layout from '../../layouts/Layout.astro';
|
||||
import AdminLayout from '../../layouts/AdminLayout.astro';
|
||||
---
|
||||
|
||||
<Layout title="Site Settings">
|
||||
<div class="glass p-12 mb-12" id="settings-content" style="display: none;">
|
||||
<header class="mb-12 border-b border-white/5 pb-12">
|
||||
<a href="/admin" class="text-blue hover:text-sky transition-colors mb-8 inline-flex items-center gap-2 group">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="transition-transform group-hover:-translate-x-1"><path d="m15 18-6-6 6-6"/></svg>
|
||||
Back to Dashboard
|
||||
</a>
|
||||
<h1 class="text-4xl font-extrabold text-mauve mt-4">
|
||||
Site Settings
|
||||
</h1>
|
||||
<p class="text-subtext1 mt-2">Configure how your blog looks and feels globally.</p>
|
||||
</header>
|
||||
<AdminLayout title="Site Settings">
|
||||
<p slot="header-subtitle" class="text-subtext1 mt-2 text-sm md:text-base">Configure how your blog looks and feels globally.</p>
|
||||
|
||||
<form id="settings-form" class="space-y-8">
|
||||
<div id="alert" class="hidden p-4 rounded-lg mb-6"></div>
|
||||
<form id="settings-form" class="space-y-8">
|
||||
<div id="alert" class="hidden p-4 rounded-lg mb-6"></div>
|
||||
|
||||
<section class="space-y-6">
|
||||
<h2 class="text-xl font-bold text-lavender border-l-4 border-lavender pl-4">General Identity</h2>
|
||||
<div class="grid md:grid-cols-2 gap-6">
|
||||
<div>
|
||||
<label for="title" class="block text-sm font-medium text-subtext1 mb-2">Blog Title (Nav)</label>
|
||||
<input type="text" id="title" required class="w-full bg-crust border border-surface1 rounded-lg px-4 py-3 text-text focus:outline-none focus:border-mauve transition-colors" />
|
||||
</div>
|
||||
<div>
|
||||
<label for="subtitle" class="block text-sm font-medium text-subtext1 mb-2">Nav Subtitle</label>
|
||||
<input type="text" id="subtitle" required class="w-full bg-crust border border-surface1 rounded-lg px-4 py-3 text-text focus:outline-none focus:border-mauve transition-colors" />
|
||||
</div>
|
||||
<div>
|
||||
<label for="welcome_title" class="block text-sm font-medium text-subtext1 mb-2">Welcome Title (Frontpage)</label>
|
||||
<input type="text" id="welcome_title" required class="w-full bg-crust border border-surface1 rounded-lg px-4 py-3 text-text focus:outline-none focus:border-mauve transition-colors" />
|
||||
</div>
|
||||
<div>
|
||||
<label for="welcome_subtitle" class="block text-sm font-medium text-subtext1 mb-2">Welcome Subtitle</label>
|
||||
<input type="text" id="welcome_subtitle" required class="w-full bg-crust border border-surface1 rounded-lg px-4 py-3 text-text focus:outline-none focus:border-mauve transition-colors" />
|
||||
</div>
|
||||
<section class="space-y-6">
|
||||
<h2 class="text-xl font-bold text-lavender border-l-4 border-lavender pl-4">General Identity</h2>
|
||||
<div class="grid md:grid-cols-2 gap-6">
|
||||
<div>
|
||||
<label for="title" class="block text-sm font-medium text-subtext1 mb-2">Blog Title (Nav)</label>
|
||||
<input type="text" id="title" required class="w-full bg-crust border border-surface1 rounded-lg px-4 py-3 text-text focus:outline-none focus:border-mauve transition-colors" />
|
||||
</div>
|
||||
<div>
|
||||
<label for="favicon" class="block text-sm font-medium text-subtext1 mb-2">Favicon URL</label>
|
||||
<input type="text" id="favicon" required class="w-full bg-crust border border-surface1 rounded-lg px-4 py-3 text-text focus:outline-none focus:border-mauve transition-colors" />
|
||||
<p class="text-[10px] text-subtext0 mt-1">URL to the icon shown in browser tabs.</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="space-y-6">
|
||||
<h2 class="text-xl font-bold text-blue border-l-4 border-blue pl-4">Appearance</h2>
|
||||
<div>
|
||||
<label for="theme" class="block text-sm font-medium text-subtext1 mb-2">Color Theme (Catppuccin)</label>
|
||||
<select id="theme" class="w-full bg-crust border border-surface1 rounded-lg px-4 py-3 text-text focus:outline-none focus:border-mauve transition-colors">
|
||||
<option value="mocha">Mocha (Dark, High Contrast)</option>
|
||||
<option value="macchiato">Macchiato (Dark, Medium Contrast)</option>
|
||||
<option value="frappe">Frappe (Dark, Low Contrast)</option>
|
||||
<option value="latte">Latte (Light Mode)</option>
|
||||
</select>
|
||||
<p class="text-[10px] text-subtext0 mt-1">Select a predefined Catppuccin color palette.</p>
|
||||
<label for="subtitle" class="block text-sm font-medium text-subtext1 mb-2">Nav Subtitle</label>
|
||||
<input type="text" id="subtitle" required class="w-full bg-crust border border-surface1 rounded-lg px-4 py-3 text-text focus:outline-none focus:border-mauve transition-colors" />
|
||||
</div>
|
||||
<div>
|
||||
<label for="custom_css" class="block text-sm font-medium text-subtext1 mb-2">Custom CSS</label>
|
||||
<textarea id="custom_css" rows="4" 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 text-xs" placeholder="body { ... }"></textarea>
|
||||
<p class="text-[10px] text-subtext0 mt-1">Inject custom CSS styles globally.</p>
|
||||
<label for="welcome_title" class="block text-sm font-medium text-subtext1 mb-2">Welcome Title (Frontpage)</label>
|
||||
<input type="text" id="welcome_title" required class="w-full bg-crust border border-surface1 rounded-lg px-4 py-3 text-text focus:outline-none focus:border-mauve transition-colors" />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="space-y-6">
|
||||
<h2 class="text-xl font-bold text-teal border-l-4 border-teal pl-4">Footer</h2>
|
||||
<div>
|
||||
<label for="footer" class="block text-sm font-medium text-subtext1 mb-2">Footer Text</label>
|
||||
<input type="text" id="footer" required class="w-full bg-crust border border-surface1 rounded-lg px-4 py-3 text-text focus:outline-none focus:border-mauve transition-colors" />
|
||||
<label for="welcome_subtitle" class="block text-sm font-medium text-subtext1 mb-2">Welcome Subtitle</label>
|
||||
<input type="text" id="welcome_subtitle" required class="w-full bg-crust border border-surface1 rounded-lg px-4 py-3 text-text focus:outline-none focus:border-mauve transition-colors" />
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
<div>
|
||||
<label for="favicon" class="block text-sm font-medium text-subtext1 mb-2">Favicon URL</label>
|
||||
<input type="text" id="favicon" required class="w-full bg-crust border border-surface1 rounded-lg px-4 py-3 text-text focus:outline-none focus:border-mauve transition-colors" />
|
||||
<p class="text-[10px] text-subtext0 mt-1">URL to the icon shown in browser tabs.</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<button type="submit" class="w-full md:w-auto bg-mauve text-crust font-bold py-4 px-12 rounded-lg hover:bg-pink transition-all transform hover:scale-[1.02] active:scale-[0.98]">
|
||||
Save Site Configuration
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
<section class="space-y-6">
|
||||
<h2 class="text-xl font-bold text-blue border-l-4 border-blue pl-4">Appearance</h2>
|
||||
<div>
|
||||
<label for="theme" class="block text-sm font-medium text-subtext1 mb-2">Color Theme (Catppuccin)</label>
|
||||
<select id="theme" class="w-full bg-crust border border-surface1 rounded-lg px-4 py-3 text-text focus:outline-none focus:border-mauve transition-colors">
|
||||
<option value="mocha">Mocha (Dark, High Contrast)</option>
|
||||
<option value="macchiato">Macchiato (Dark, Medium Contrast)</option>
|
||||
<option value="frappe">Frappe (Dark, Low Contrast)</option>
|
||||
<option value="latte">Latte (Light Mode)</option>
|
||||
</select>
|
||||
<p class="text-[10px] text-subtext0 mt-1">Select a predefined Catppuccin color palette.</p>
|
||||
</div>
|
||||
<div>
|
||||
<label for="custom_css" class="block text-sm font-medium text-subtext1 mb-2">Custom CSS</label>
|
||||
<textarea id="custom_css" rows="4" 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 text-xs" placeholder="body { ... }"></textarea>
|
||||
<p class="text-[10px] text-subtext0 mt-1">Inject custom CSS styles globally.</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="space-y-6">
|
||||
<h2 class="text-xl font-bold text-teal border-l-4 border-teal pl-4">Footer</h2>
|
||||
<div>
|
||||
<label for="footer" class="block text-sm font-medium text-subtext1 mb-2">Footer Text</label>
|
||||
<input type="text" id="footer" required class="w-full bg-crust border border-surface1 rounded-lg px-4 py-3 text-text focus:outline-none focus:border-mauve transition-colors" />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<button type="submit" class="w-full md:w-auto bg-mauve text-crust font-bold py-4 px-12 rounded-lg hover:bg-pink transition-all transform hover:scale-[1.02] active:scale-[0.98]">
|
||||
Save Site Configuration
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<script>
|
||||
const token = localStorage.getItem('admin_token');
|
||||
if (!token) {
|
||||
window.location.href = '/admin/login';
|
||||
} else {
|
||||
document.getElementById('settings-content')!.style.display = 'block';
|
||||
import { showAlert } from '../../components/ui/Alert';
|
||||
|
||||
document.addEventListener('admin-auth-ready', (e: any) => {
|
||||
const token = e.detail.token;
|
||||
loadSettings();
|
||||
}
|
||||
|
||||
async function loadSettings() {
|
||||
try {
|
||||
const res = await fetch('/api/config');
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
(document.getElementById('title') as HTMLInputElement).value = data.title || '';
|
||||
(document.getElementById('subtitle') as HTMLInputElement).value = data.subtitle || '';
|
||||
(document.getElementById('footer') as HTMLInputElement).value = data.footer || '';
|
||||
(document.getElementById('favicon') as HTMLInputElement).value = data.favicon || '';
|
||||
(document.getElementById('theme') as HTMLSelectElement).value = data.theme || 'mocha';
|
||||
(document.getElementById('custom_css') as HTMLTextAreaElement).value = data.custom_css || '';
|
||||
async function loadSettings() {
|
||||
try {
|
||||
const res = await fetch('/api/config');
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
(document.getElementById('title') as HTMLInputElement).value = data.title || '';
|
||||
(document.getElementById('subtitle') as HTMLInputElement).value = data.subtitle || '';
|
||||
(document.getElementById('welcome_title') as HTMLInputElement).value = data.welcome_title || '';
|
||||
(document.getElementById('welcome_subtitle') as HTMLInputElement).value = data.welcome_subtitle || '';
|
||||
(document.getElementById('footer') as HTMLInputElement).value = data.footer || '';
|
||||
(document.getElementById('favicon') as HTMLInputElement).value = data.favicon || '';
|
||||
(document.getElementById('theme') as HTMLSelectElement).value = data.theme || 'mocha';
|
||||
(document.getElementById('custom_css') as HTMLTextAreaElement).value = data.custom_css || '';
|
||||
}
|
||||
} catch (err) {
|
||||
showAlert('Failed to load settings from server.', 'error');
|
||||
}
|
||||
} catch (e) {
|
||||
showAlert('Failed to load settings from server.', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
document.getElementById('settings-form')?.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
const payload = {
|
||||
title: (document.getElementById('title') as HTMLInputElement).value,
|
||||
subtitle: (document.getElementById('subtitle') as HTMLInputElement).value,
|
||||
footer: (document.getElementById('footer') as HTMLInputElement).value,
|
||||
favicon: (document.getElementById('favicon') as HTMLInputElement).value,
|
||||
theme: (document.getElementById('theme') as HTMLSelectElement).value,
|
||||
custom_css: (document.getElementById('custom_css') as HTMLTextAreaElement).value,
|
||||
};
|
||||
document.getElementById('settings-form')?.addEventListener('submit', async (ev) => {
|
||||
ev.preventDefault();
|
||||
const payload = {
|
||||
title: (document.getElementById('title') as HTMLInputElement).value,
|
||||
subtitle: (document.getElementById('subtitle') as HTMLInputElement).value,
|
||||
welcome_title: (document.getElementById('welcome_title') as HTMLInputElement).value,
|
||||
welcome_subtitle: (document.getElementById('welcome_subtitle') as HTMLInputElement).value,
|
||||
footer: (document.getElementById('footer') as HTMLInputElement).value,
|
||||
favicon: (document.getElementById('favicon') as HTMLInputElement).value,
|
||||
theme: (document.getElementById('theme') as HTMLSelectElement).value,
|
||||
custom_css: (document.getElementById('custom_css') as HTMLTextAreaElement).value,
|
||||
};
|
||||
|
||||
try {
|
||||
// Now using relative path which will be proxied
|
||||
const res = await fetch('/api/config', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
try {
|
||||
const res = await fetch('/api/config', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
showAlert('Settings saved successfully! Refresh to see changes.', 'success');
|
||||
} else {
|
||||
const err = await res.json();
|
||||
showAlert(`Error: ${err.error}`, 'error');
|
||||
if (res.ok) {
|
||||
showAlert('Settings saved successfully! Refresh to see changes.', 'success');
|
||||
} else {
|
||||
const err = await res.json();
|
||||
showAlert(`Error: ${err.error}`, 'error');
|
||||
}
|
||||
} catch (err) {
|
||||
showAlert('Failed to save settings. Please check your connection.', 'error');
|
||||
}
|
||||
} catch (e) {
|
||||
showAlert('Failed to save settings. Please check your connection.', 'error');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
function showAlert(msg: string, type: 'success' | 'error') {
|
||||
const alertEl = document.getElementById('alert');
|
||||
if (alertEl) {
|
||||
alertEl.textContent = msg;
|
||||
alertEl.className = `p-4 rounded-lg mb-6 ${type === 'success' ? 'bg-green/20 text-green border border-green/30' : 'bg-red/20 text-red border border-red/30'}`;
|
||||
alertEl.classList.remove('hidden');
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' });
|
||||
}
|
||||
}
|
||||
</script>
|
||||
</Layout>
|
||||
</AdminLayout>
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
---
|
||||
import Layout from '../layouts/Layout.astro';
|
||||
import PostCard from '../components/PostCard.astro';
|
||||
|
||||
const API_URL = (typeof process !== 'undefined' ? process.env.PUBLIC_API_URL : import.meta.env.PUBLIC_API_URL) || 'http://localhost:3000';
|
||||
console.log('Connecting to backend at:', API_URL);
|
||||
const API_URL = process.env.PUBLIC_API_URL || 'http://localhost:3000';
|
||||
|
||||
interface Post {
|
||||
slug: string;
|
||||
excerpt?: string;
|
||||
}
|
||||
|
||||
let posts: Post[] = [];
|
||||
@@ -62,7 +63,7 @@ function formatSlug(slug: string) {
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
{posts.length === 0 && !error && (
|
||||
<div class="glass p-8 md:p-12 text-center text-subtext1 text-sm md:text-base">
|
||||
<p>No posts found yet. Add some .md files to the data/posts directory!</p>
|
||||
@@ -70,21 +71,11 @@ function formatSlug(slug: string) {
|
||||
)}
|
||||
|
||||
{posts.map((post) => (
|
||||
<a href={`/posts/${post.slug}`} class="group block">
|
||||
<article class="glass p-5 md:p-8 transition-all hover:scale-[1.01] hover:bg-surface0/80 active:scale-[0.99] flex flex-col md:flex-row justify-between md:items-center gap-4 md:gap-6">
|
||||
<div class="flex-1">
|
||||
<h2 class="text-xl md:text-3xl font-bold text-lavender group-hover:text-mauve transition-colors mb-2 md:mb-3">
|
||||
{formatSlug(post.slug)}
|
||||
</h2>
|
||||
<p class="text-text text-sm md:text-base leading-relaxed line-clamp-3">
|
||||
{post.excerpt || `Read more about ${formatSlug(post.slug)}...`}
|
||||
</p>
|
||||
</div>
|
||||
<div class="text-mauve opacity-0 group-hover:opacity-100 transition-opacity self-end md:self-auto shrink-0 hidden md:block">
|
||||
<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" class="md:w-8 md:h-8"><path d="M5 12h14"/><path d="m12 5 7 7-7 7"/></svg>
|
||||
</div>
|
||||
</article>
|
||||
</a>
|
||||
<PostCard
|
||||
slug={post.slug}
|
||||
excerpt={post.excerpt}
|
||||
formatSlug={formatSlug}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user