Files
portfolio/app/editor/page.tsx
denshooter 0349c686fa feat(auth): implement session token creation and verification for enhanced security
feat(api): require session authentication for admin routes and improve error handling

fix(api): streamline project image generation by fetching data directly from the database

fix(api): optimize project import/export functionality with session validation and improved error handling

fix(api): enhance analytics dashboard and email manager with session token for admin requests

fix(components): improve loading states and dynamic imports for better user experience

chore(security): update Content Security Policy to avoid unsafe-eval in production

chore(deps): update package.json scripts for consistent environment handling in linting and testing
2026-01-12 00:27:03 +01:00

1161 lines
42 KiB
TypeScript

"use client";
import React, {
useState,
useEffect,
useRef,
useCallback,
Suspense,
} from "react";
import { useSearchParams } from "next/navigation";
import { motion, AnimatePresence } from "framer-motion";
import ReactMarkdown from "react-markdown";
import {
ArrowLeft,
Save,
Eye,
X,
Bold,
Italic,
Code,
Image,
Link,
List,
ListOrdered,
Quote,
Hash,
Loader2,
ExternalLink,
Github,
Tag,
} from "lucide-react";
import { useToast } from "@/components/Toast";
interface Project {
id: string;
title: string;
description: string;
content?: string;
category: string;
tags?: string[];
featured: boolean;
published: boolean;
github?: string;
live?: string;
image?: string;
createdAt: string;
updatedAt: string;
}
function EditorPageContent() {
const searchParams = useSearchParams();
const projectId = searchParams.get("id");
const contentRef = useRef<HTMLDivElement>(null);
const { showSuccess, showError } = useToast();
const [, setProject] = useState<Project | null>(null);
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [isLoading, setIsLoading] = useState(true);
const [isSaving, setIsSaving] = useState(false);
const [isCreating, setIsCreating] = useState(!projectId);
const [showPreview, setShowPreview] = useState(false);
const [_isTyping, setIsTyping] = useState(false);
const [history, setHistory] = useState<typeof formData[]>([]);
const [historyIndex, setHistoryIndex] = useState(-1);
const [originalFormData, setOriginalFormData] = useState<typeof formData | null>(null);
const shouldUpdateContentRef = useRef(true);
// Form state
const [formData, setFormData] = useState({
title: "",
description: "",
content: "",
category: "web",
tags: [] as string[],
featured: false,
published: false,
github: "",
live: "",
image: "",
});
const loadProject = useCallback(async (id: string) => {
try {
const response = await fetch("/api/projects");
if (response.ok) {
const data = await response.json();
const foundProject = data.projects.find(
(p: Project) => p.id.toString() === id,
);
if (foundProject) {
const initialData = {
title: foundProject.title || "",
description: foundProject.description || "",
content: foundProject.content || "",
category: foundProject.category || "web",
tags: foundProject.tags || [],
featured: foundProject.featured || false,
published: foundProject.published || false,
github: foundProject.github || "",
live: foundProject.live || "",
image: foundProject.image || "",
};
setProject(foundProject);
setFormData(initialData);
setOriginalFormData(initialData);
setHistory([initialData]);
setHistoryIndex(0);
shouldUpdateContentRef.current = true;
// Initialize contentEditable after state update
setTimeout(() => {
if (contentRef.current && initialData.content) {
contentRef.current.textContent = initialData.content;
}
}, 0);
}
} else {
if (process.env.NODE_ENV === "development") {
console.error("Failed to fetch projects:", response.status);
}
}
} catch (error) {
if (process.env.NODE_ENV === "development") {
console.error("Error loading project:", error);
}
}
}, []);
// Check authentication and load project
useEffect(() => {
const init = async () => {
try {
// Check auth
const authStatus = sessionStorage.getItem("admin_authenticated");
const sessionToken = sessionStorage.getItem("admin_session_token");
if (authStatus === "true" && sessionToken) {
setIsAuthenticated(true);
// Load project if editing
if (projectId) {
await loadProject(projectId);
} else {
setIsCreating(true);
// Initialize history for new project
const initialData = {
title: "",
description: "",
content: "",
category: "web",
tags: [],
featured: false,
published: false,
github: "",
live: "",
image: "",
};
setFormData(initialData);
setOriginalFormData(initialData);
setHistory([initialData]);
setHistoryIndex(0);
shouldUpdateContentRef.current = true;
// Initialize contentEditable after state update
setTimeout(() => {
if (contentRef.current) {
contentRef.current.textContent = "";
}
}, 0);
}
} else {
setIsAuthenticated(false);
}
} catch (error) {
if (process.env.NODE_ENV === "development") {
console.error("Error in init:", error);
}
setIsAuthenticated(false);
} finally {
setIsLoading(false);
}
};
init();
}, [projectId, loadProject]);
const handleSave = useCallback(async () => {
try {
setIsSaving(true);
// Validate required fields
if (!formData.title.trim()) {
showError("Validation Error", "Please enter a project title");
setIsSaving(false);
return;
}
if (!formData.description.trim()) {
showError("Validation Error", "Please enter a project description");
setIsSaving(false);
return;
}
const url = projectId ? `/api/projects/${projectId}` : "/api/projects";
const method = projectId ? "PUT" : "POST";
// Prepare data for saving - only include fields that exist in the database schema
const saveData = {
title: formData.title.trim(),
description: formData.description.trim(),
content: formData.content.trim(),
category: formData.category,
tags: formData.tags,
github: formData.github.trim() || null,
live: formData.live.trim() || null,
imageUrl: formData.image.trim() || null,
published: formData.published,
featured: formData.featured,
// Add required fields that might be missing
date: new Date().toISOString().split("T")[0], // Current date in YYYY-MM-DD format
};
const response = await fetch(url, {
method,
headers: {
"Content-Type": "application/json",
"x-admin-request": "true",
"x-session-token": sessionStorage.getItem("admin_session_token") || "",
},
body: JSON.stringify(saveData),
});
if (response.ok) {
const savedProject = await response.json();
// Update local state with the saved project data
setProject(savedProject);
setFormData((prev) => ({
...prev,
title: savedProject.title || "",
description: savedProject.description || "",
content: savedProject.content || "",
category: savedProject.category || "web",
tags: savedProject.tags || [],
featured: savedProject.featured || false,
published: savedProject.published || false,
github: savedProject.github || "",
live: savedProject.live || "",
image: savedProject.imageUrl || "",
}));
// Show success toast (smaller, smoother)
showSuccess("Saved", `"${savedProject.title}" saved`);
// Update project ID if it was a new project
if (!projectId && savedProject.id) {
const newUrl = `/editor?id=${savedProject.id}`;
window.history.replaceState({}, '', newUrl);
}
} else {
const errorData = await response.json();
if (process.env.NODE_ENV === "development") {
console.error("Error saving project:", response.status, errorData);
}
showError("Save Failed", errorData.error || "Failed to save");
}
} catch (error) {
if (process.env.NODE_ENV === "development") {
console.error("Error saving project:", error);
}
showError(
"Save Failed",
error instanceof Error ? error.message : "Failed to save"
);
} finally {
setIsSaving(false);
}
}, [projectId, formData, showSuccess, showError]);
const handleInputChange = (
field: string,
value: string | boolean | string[],
) => {
setFormData((prev) => {
const newData = {
...prev,
[field]: value,
};
// Add to history for undo/redo
setHistory((hist) => {
const newHistory = hist.slice(0, historyIndex + 1);
newHistory.push(newData);
// Keep only last 50 history entries
const trimmedHistory = newHistory.slice(-50);
setHistoryIndex(trimmedHistory.length - 1);
return trimmedHistory;
});
return newData;
});
};
const handleUndo = useCallback(() => {
setHistoryIndex((currentIndex) => {
if (currentIndex > 0) {
const newIndex = currentIndex - 1;
shouldUpdateContentRef.current = true;
setFormData(history[newIndex]);
return newIndex;
}
return currentIndex;
});
}, [history]);
const handleRedo = useCallback(() => {
setHistoryIndex((currentIndex) => {
if (currentIndex < history.length - 1) {
const newIndex = currentIndex + 1;
shouldUpdateContentRef.current = true;
setFormData(history[newIndex]);
return newIndex;
}
return currentIndex;
});
}, [history]);
const handleRevert = useCallback(() => {
if (originalFormData) {
if (confirm("Are you sure you want to revert all changes? This cannot be undone.")) {
shouldUpdateContentRef.current = true;
setFormData(originalFormData);
setHistory([originalFormData]);
setHistoryIndex(0);
}
} else if (projectId) {
// Reload from server
if (confirm("Are you sure you want to revert all changes? This will reload the project from the server.")) {
shouldUpdateContentRef.current = true;
loadProject(projectId);
}
}
}, [originalFormData, projectId, loadProject]);
// Sync contentEditable when formData.content changes externally (undo/redo/revert)
useEffect(() => {
if (contentRef.current && shouldUpdateContentRef.current) {
const currentContent = contentRef.current.textContent || "";
if (currentContent !== formData.content) {
contentRef.current.textContent = formData.content;
}
shouldUpdateContentRef.current = false;
}
}, [formData.content]);
// Initialize contentEditable when formData.content is set and editor is empty
useEffect(() => {
if (contentRef.current) {
const currentText = contentRef.current.textContent || "";
// Initialize if editor is empty and we have content, or if content changed externally
if ((!currentText && formData.content) || (shouldUpdateContentRef.current && currentText !== formData.content)) {
contentRef.current.textContent = formData.content;
shouldUpdateContentRef.current = false;
}
}
}, [formData.content]);
// Keyboard shortcuts
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
// Ctrl+S or Cmd+S - Save
if ((e.ctrlKey || e.metaKey) && e.key === 's') {
e.preventDefault();
if (!isSaving) {
handleSave();
}
}
// Ctrl+Z or Cmd+Z - Undo
if ((e.ctrlKey || e.metaKey) && e.key === 'z' && !e.shiftKey) {
e.preventDefault();
handleUndo();
}
// Ctrl+Shift+Z or Cmd+Shift+Z - Redo
if ((e.ctrlKey || e.metaKey) && e.key === 'z' && e.shiftKey) {
e.preventDefault();
handleRedo();
}
// Ctrl+R or Cmd+R - Revert (but allow browser refresh if not in editor)
if ((e.ctrlKey || e.metaKey) && e.key === 'r') {
const target = e.target as HTMLElement;
if (target.isContentEditable || target.tagName === 'INPUT' || target.tagName === 'TEXTAREA') {
e.preventDefault();
handleRevert();
}
}
};
window.addEventListener('keydown', handleKeyDown);
return () => {
window.removeEventListener('keydown', handleKeyDown);
};
}, [isSaving, handleSave, handleUndo, handleRedo, handleRevert]);
const handleTagsChange = (tagsString: string) => {
const tags = tagsString
.split(",")
.map((tag) => tag.trim())
.filter((tag) => tag);
setFormData((prev) => ({
...prev,
tags,
}));
};
// Markdown components for react-markdown with security
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const markdownComponents: any = {
a: ({ node: _node, ...props }: { node?: unknown; href?: string; children?: React.ReactNode }) => {
// Validate URLs to prevent javascript: and data: protocols
const href = props.href || "";
const isSafe =
href && typeof href === 'string' && !href.startsWith("javascript:") && !href.startsWith("data:");
return (
<a
{...props}
href={isSafe ? href : "#"}
target={isSafe && href.startsWith("http") ? "_blank" : undefined}
rel={
isSafe && href.startsWith("http")
? "noopener noreferrer"
: undefined
}
/>
);
},
img: ({ node: _node, ...props }: { node?: unknown; src?: string; alt?: string }) => {
// Validate image URLs
const src = props.src;
const isSafe =
src && typeof src === 'string' && !src.startsWith("javascript:") && !src.startsWith("data:");
// eslint-disable-next-line @next/next/no-img-element
return isSafe ? <img {...props} src={src} alt={props.alt || ""} /> : null;
},
};
// Rich text editor functions
const insertFormatting = (format: string) => {
const content = contentRef.current;
if (!content) return;
const selection = window.getSelection();
if (!selection || selection.rangeCount === 0) return;
const range = selection.getRangeAt(0);
let newText = "";
switch (format) {
case "bold":
newText = `**${selection.toString() || "bold text"}**`;
break;
case "italic":
newText = `*${selection.toString() || "italic text"}*`;
break;
case "code":
newText = `\`${selection.toString() || "code"}\``;
break;
case "h1":
newText = `# ${selection.toString() || "Heading 1"}`;
break;
case "h2":
newText = `## ${selection.toString() || "Heading 2"}`;
break;
case "h3":
newText = `### ${selection.toString() || "Heading 3"}`;
break;
case "list":
newText = `- ${selection.toString() || "List item"}`;
break;
case "orderedList":
newText = `1. ${selection.toString() || "List item"}`;
break;
case "quote":
newText = `> ${selection.toString() || "Quote"}`;
break;
case "link":
const url = prompt("Enter URL:");
if (url) {
newText = `[${selection.toString() || "link text"}](${url})`;
}
break;
case "image":
const imageUrl = prompt("Enter image URL:");
if (imageUrl) {
newText = `![${selection.toString() || "alt text"}](${imageUrl})`;
}
break;
}
if (newText) {
range.deleteContents();
range.insertNode(document.createTextNode(newText));
// Update form data
setFormData((prev) => ({
...prev,
content: content.textContent || "",
}));
}
};
if (isLoading) {
return (
<div className="min-h-screen animated-bg flex items-center justify-center">
<div className="text-center">
<motion.div
initial={{ opacity: 0, scale: 0.8 }}
animate={{ opacity: 1, scale: 1 }}
className="glass-card p-8 rounded-2xl"
>
<motion.div
animate={{ rotate: 360 }}
transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
className="w-12 h-12 border-3 border-stone-500 border-t-transparent rounded-full mx-auto mb-6"
/>
<h2 className="text-xl font-semibold gradient-text mb-2">
Loading Editor
</h2>
<p className="text-gray-400">Preparing your workspace...</p>
</motion.div>
</div>
</div>
);
}
if (!isAuthenticated) {
return (
<div className="min-h-screen animated-bg flex items-center justify-center">
<motion.div
initial={{ opacity: 0, scale: 0.9 }}
animate={{ opacity: 1, scale: 1 }}
className="text-center text-white max-w-md mx-auto p-8 admin-glass-card rounded-2xl"
>
<div className="mb-6">
<div className="w-16 h-16 bg-red-500/20 rounded-full flex items-center justify-center mx-auto mb-4">
<X className="w-8 h-8 text-red-400" />
</div>
<h1 className="text-2xl font-bold mb-2">Access Denied</h1>
<p className="text-white/70 mb-6">
You need to be logged in to access the editor.
</p>
</div>
<button
onClick={() => (window.location.href = "/manage")}
className="w-full px-6 py-3 bg-stone-600 text-white rounded-xl hover:bg-stone-700 transition-all font-medium"
>
Go to Admin Login
</button>
</motion.div>
</div>
);
}
return (
<div className="min-h-screen animated-bg flex flex-col overflow-hidden">
{/* Header */}
<div className="glass-card border-b border-white/10 sticky top-0 z-50 flex-shrink-0">
<div className="max-w-7xl mx-auto px-4 sm:px-6">
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between h-auto sm:h-16 py-4 sm:py-0 gap-4 sm:gap-0">
<div className="flex flex-col sm:flex-row items-start sm:items-center space-y-2 sm:space-y-0 sm:space-x-4">
<button
onClick={() => (window.location.href = "/manage")}
className="inline-flex items-center space-x-2 text-stone-400 hover:text-stone-300 transition-colors"
>
<ArrowLeft className="w-5 h-5" />
<span className="hidden sm:inline">Back to Dashboard</span>
<span className="sm:hidden">Back</span>
</button>
<div className="hidden sm:block h-6 w-px bg-white/20" />
<h1 className="text-lg sm:text-xl font-semibold gradient-text truncate max-w-xs sm:max-w-none">
{isCreating
? "Create New Project"
: `Edit: ${formData.title || "Untitled"}`}
</h1>
</div>
<div className="flex items-center space-x-2 sm:space-x-3 w-full sm:w-auto">
<button
onClick={() => setShowPreview(!showPreview)}
className={`flex items-center space-x-2 px-4 py-2 rounded-lg font-medium transition-all duration-200 text-sm ${
showPreview
? "bg-stone-600 text-white shadow-lg"
: "bg-gray-800/50 text-stone-300 hover:bg-gray-700/50 hover:text-stone-100"
}`}
>
<Eye className="w-4 h-4" />
<span className="hidden sm:inline">Preview</span>
</button>
<button
onClick={handleSave}
disabled={isSaving}
className="btn-primary flex items-center space-x-2 px-6 py-2 text-sm sm:text-base flex-1 sm:flex-none disabled:opacity-50"
>
{isSaving ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
<Save className="w-4 h-4" />
)}
<span>{isSaving ? "Saving..." : "Save Project"}</span>
</button>
</div>
</div>
</div>
</div>
{/* Editor Content - Scrollable */}
<div className="flex-1 overflow-y-auto">
<div className="max-w-7xl mx-auto px-4 sm:px-6 py-6 sm:py-8">
<div className="flex flex-col lg:flex-row gap-6 lg:gap-8">
{/* Floating particles background */}
<div className="particles">
{[...Array(20)].map((_, i) => (
<div
key={i}
className="particle"
style={{
left: `${Math.random() * 100}%`,
animationDelay: `${Math.random() * 20}s`,
animationDuration: `${20 + Math.random() * 10}s`,
}}
/>
))}
</div>
{/* Sidebar - Left (appears first in DOM for left positioning) */}
<div className="w-full lg:w-80 flex-shrink-0 space-y-6 order-1 lg:order-1">
{/* Project Settings */}
<motion.div
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ delay: 0.4 }}
className="glass-card p-6 rounded-2xl"
>
<h3 className="text-lg font-semibold gradient-text mb-4">
Settings
</h3>
<div className="space-y-4">
<div>
<label className="block text-sm font-medium text-stone-300 mb-2">
Category
</label>
<div className="custom-select">
<select
value={formData.category}
onChange={(e) =>
handleInputChange("category", e.target.value)
}
>
<option value="web">Web Development</option>
<option value="mobile">Mobile Development</option>
<option value="desktop">Desktop Application</option>
<option value="game">Game Development</option>
<option value="ai">AI/ML</option>
<option value="other">Other</option>
</select>
</div>
</div>
<div>
<label className="block text-sm font-medium text-stone-300 mb-2">
Tags
</label>
<input
type="text"
value={formData.tags.join(", ")}
onChange={(e) => handleTagsChange(e.target.value)}
className="w-full px-3 py-2 form-input-enhanced rounded-lg focus:outline-none"
placeholder="React, TypeScript, Next.js"
/>
</div>
</div>
</motion.div>
{/* Links */}
<motion.div
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ delay: 0.5 }}
className="glass-card p-6 rounded-2xl"
>
<h3 className="text-lg font-semibold gradient-text mb-4">
Links
</h3>
<div className="space-y-4">
<div>
<label className="block text-sm font-medium text-stone-300 mb-2">
GitHub URL
</label>
<input
type="url"
value={formData.github}
onChange={(e) =>
handleInputChange("github", e.target.value)
}
className="w-full px-3 py-2 form-input-enhanced rounded-lg focus:outline-none"
placeholder="https://github.com/username/repo"
/>
</div>
<div>
<label className="block text-sm font-medium text-stone-300 mb-2">
Live URL
</label>
<input
type="url"
value={formData.live}
onChange={(e) => handleInputChange("live", e.target.value)}
className="w-full px-3 py-2 form-input-enhanced rounded-lg focus:outline-none"
placeholder="https://example.com"
/>
</div>
</div>
</motion.div>
{/* Publish */}
<motion.div
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
transition={{ delay: 0.6 }}
className="glass-card p-6 rounded-2xl"
>
<h3 className="text-lg font-semibold gradient-text mb-4">
Publish
</h3>
<div className="space-y-4">
<label className="flex items-center space-x-3">
<input
type="checkbox"
checked={formData.featured}
onChange={(e) =>
handleInputChange("featured", e.target.checked)
}
className="w-4 h-4 text-stone-500 bg-gray-900/80 border-gray-600/50 rounded focus:ring-stone-500 focus:ring-2"
/>
<span className="text-stone-200">Featured Project</span>
</label>
<label className="flex items-center space-x-3">
<input
type="checkbox"
checked={formData.published}
onChange={(e) =>
handleInputChange("published", e.target.checked)
}
className="w-4 h-4 text-stone-500 bg-gray-900/80 border-gray-600/50 rounded focus:ring-stone-500 focus:ring-2"
/>
<span className="text-stone-200">Published</span>
</label>
</div>
<div className="mt-6 pt-4 border-t border-white/20">
<h4 className="text-sm font-medium text-stone-300 mb-2">
Preview
</h4>
<div className="text-xs text-stone-400 space-y-1">
<p>Status: {formData.published ? "Published" : "Draft"}</p>
{formData.featured && (
<p className="text-stone-400"> Featured</p>
)}
<p>Category: {formData.category}</p>
<p>Tags: {formData.tags.length} tags</p>
</div>
</div>
</motion.div>
</div>
{/* Main Editor - Right (appears second in DOM for right positioning) */}
<div className="flex-1 space-y-6 order-2 lg:order-2 min-w-0">
{/* Project Title */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
className="glass-card p-6 rounded-2xl"
>
<input
type="text"
value={formData.title}
onChange={(e) => handleInputChange("title", e.target.value)}
className="w-full text-3xl font-bold form-input-enhanced focus:outline-none p-4 rounded-lg"
placeholder="Enter project title..."
/>
</motion.div>
{/* Description - Under Title */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.1 }}
className="glass-card p-6 rounded-2xl"
>
<h3 className="text-lg font-semibold gradient-text mb-4">
Description
</h3>
<textarea
value={formData.description}
onChange={(e) =>
handleInputChange("description", e.target.value)
}
rows={4}
className="w-full px-4 py-3 form-input-enhanced rounded-lg focus:outline-none resize-none"
placeholder="Brief description of your project..."
/>
</motion.div>
{/* Rich Text Toolbar */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.2 }}
className="glass-card p-4 rounded-2xl"
>
<div className="flex flex-wrap items-center gap-1 sm:gap-2">
<div className="flex items-center space-x-1 border-r border-white/20 pr-2 sm:pr-3">
<button
onClick={() => insertFormatting("bold")}
className="p-2 rounded-lg text-stone-300"
title="Bold"
>
<Bold className="w-4 h-4" />
</button>
<button
onClick={() => insertFormatting("italic")}
className="p-2 rounded-lg text-stone-300"
title="Italic"
>
<Italic className="w-4 h-4" />
</button>
<button
onClick={() => insertFormatting("code")}
className="p-2 rounded-lg text-stone-300"
title="Code"
>
<Code className="w-4 h-4" />
</button>
</div>
<div className="flex items-center space-x-1 border-r border-white/20 pr-2 sm:pr-3">
<button
onClick={() => insertFormatting("h1")}
className="p-2 rounded-lg text-stone-300"
title="Heading 1"
>
<Hash className="w-4 h-4" />
</button>
<button
onClick={() => insertFormatting("h2")}
className="p-2 hover:bg-gray-800/50 rounded-lg transition-all duration-200 text-xs sm:text-sm text-stone-300 hover:text-stone-100"
title="Heading 2"
>
H2
</button>
<button
onClick={() => insertFormatting("h3")}
className="p-2 hover:bg-gray-800/50 rounded-lg transition-all duration-200 text-xs sm:text-sm text-stone-300 hover:text-stone-100"
title="Heading 3"
>
H3
</button>
</div>
<div className="flex items-center space-x-1 border-r border-white/20 pr-2 sm:pr-3">
<button
onClick={() => insertFormatting("list")}
className="p-2 rounded-lg text-stone-300"
title="Bullet List"
>
<List className="w-4 h-4" />
</button>
<button
onClick={() => insertFormatting("orderedList")}
className="p-2 rounded-lg text-stone-300"
title="Numbered List"
>
<ListOrdered className="w-4 h-4" />
</button>
<button
onClick={() => insertFormatting("quote")}
className="p-2 rounded-lg text-stone-300"
title="Quote"
>
<Quote className="w-4 h-4" />
</button>
</div>
<div className="flex items-center space-x-1">
<button
onClick={() => insertFormatting("link")}
className="p-2 rounded-lg text-stone-300"
title="Link"
>
<Link className="w-4 h-4" />
</button>
<button
onClick={() => insertFormatting("image")}
className="p-2 rounded-lg text-stone-300"
title="Image"
>
{/* eslint-disable-next-line jsx-a11y/alt-text */}
<Image className="w-4 h-4" />
</button>
</div>
</div>
</motion.div>
{/* Content Editor */}
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.3 }}
className="glass-card p-6 rounded-2xl"
>
<h3 className="text-lg font-semibold gradient-text mb-4">
Content
</h3>
<div className="relative">
<div
ref={contentRef}
contentEditable
className="editor-content-editable w-full min-h-[500px] p-6 form-input-enhanced rounded-lg focus:outline-none leading-relaxed"
style={{ whiteSpace: "pre-wrap" }}
onFocus={(e) => {
// Ensure content is set when focusing if empty
const target = e.target as HTMLDivElement;
const currentText = target.textContent || "";
if (!currentText && formData.content) {
target.textContent = formData.content;
} else if (currentText !== formData.content && shouldUpdateContentRef.current) {
// Sync if content changed externally (undo/redo)
target.textContent = formData.content;
}
shouldUpdateContentRef.current = false;
}}
onMouseDown={(e) => {
// Prevent content from being cleared on click
const target = e.target as HTMLDivElement;
const currentText = target.textContent || "";
if (!currentText && formData.content) {
target.textContent = formData.content;
}
shouldUpdateContentRef.current = false;
}}
onClick={(e) => {
// Ensure content persists on click
const target = e.target as HTMLDivElement;
if (!target.textContent && formData.content) {
target.textContent = formData.content;
}
}}
onInput={(e) => {
const target = e.target as HTMLDivElement;
setIsTyping(true);
shouldUpdateContentRef.current = false;
const newContent = target.textContent || "";
setFormData((prev) => {
const newData = {
...prev,
content: newContent,
};
// Add to history for undo/redo
setHistory((hist) => {
const newHistory = hist.slice(0, historyIndex + 1);
newHistory.push(newData);
// Keep only last 50 history entries
const trimmedHistory = newHistory.slice(-50);
setHistoryIndex(trimmedHistory.length - 1);
return trimmedHistory;
});
return newData;
});
}}
onBlur={() => {
setIsTyping(false);
}}
suppressContentEditableWarning={true}
data-placeholder="Start writing your project content..."
/>
</div>
<p className="text-xs text-stone-400 mt-2">
Supports Markdown formatting. Use the toolbar above or type
directly.
</p>
</motion.div>
</div>
</div>
</div>
</div>
{/* Preview Modal */}
<AnimatePresence>
{showPreview && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4"
onClick={() => setShowPreview(false)}
>
<motion.div
initial={{ scale: 0.9, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
exit={{ scale: 0.9, opacity: 0 }}
className="glass-card rounded-2xl p-8 max-w-4xl w-full max-h-[90vh] overflow-y-auto scrollbar-hide"
onClick={(e) => e.stopPropagation()}
>
<div className="flex items-center justify-between mb-6">
<h2 className="text-2xl font-bold gradient-text">
Project Preview
</h2>
<button
onClick={() => setShowPreview(false)}
className="p-2 rounded-lg"
>
<X className="w-5 h-5 text-white/70" />
</button>
</div>
{/* Preview Content */}
<div className="space-y-6">
{/* Project Header */}
<div className="text-center">
<h1 className="text-4xl font-bold gradient-text mb-4">
{formData.title || "Untitled Project"}
</h1>
<p className="text-xl text-gray-400 mb-6">
{formData.description || "No description provided"}
</p>
{/* Project Meta */}
<div className="flex flex-wrap justify-center gap-4 mb-6">
<div className="flex items-center space-x-2 text-stone-300">
<Tag className="w-4 h-4" />
<span className="capitalize">{formData.category}</span>
</div>
{formData.featured && (
<div className="flex items-center space-x-2 text-stone-400">
<span className="text-sm font-semibold">
Featured
</span>
</div>
)}
</div>
{/* Tags */}
{formData.tags.length > 0 && (
<div className="flex flex-wrap justify-center gap-2 mb-6">
{formData.tags.map((tag, index) => (
<span
key={index}
className="px-3 py-1 bg-gray-800/50 text-stone-300 text-sm rounded-full border border-gray-700"
>
{tag}
</span>
))}
</div>
)}
{/* Links */}
{((formData.github && formData.github.trim()) ||
(formData.live && formData.live.trim())) && (
<div className="flex justify-center space-x-4 mb-8">
{formData.github && formData.github.trim() && (
<a
href={formData.github}
target="_blank"
rel="noopener noreferrer"
className="flex items-center space-x-2 px-4 py-2 bg-gray-800/50 text-stone-300 rounded-lg"
>
<Github className="w-4 h-4" />
<span>GitHub</span>
</a>
)}
{formData.live && formData.live.trim() && (
<a
href={formData.live}
target="_blank"
rel="noopener noreferrer"
className="flex items-center space-x-2 px-4 py-2 bg-stone-600/80 text-white rounded-lg"
>
<ExternalLink className="w-4 h-4" />
<span>Live Demo</span>
</a>
)}
</div>
)}
</div>
{/* Content Preview */}
{formData.content && (
<div className="border-t border-white/10 pt-6">
<h3 className="text-xl font-semibold gradient-text mb-4">
Content
</h3>
<div className="prose prose-invert max-w-none">
<div className="markdown text-stone-300 leading-relaxed">
<ReactMarkdown components={markdownComponents}>
{formData.content}
</ReactMarkdown>
</div>
</div>
</div>
)}
{/* Status */}
<div className="border-t border-white/10 pt-6">
<div className="flex items-center justify-between">
<div className="flex items-center space-x-4">
<span
className={`px-3 py-1 rounded-full text-sm font-medium ${
formData.published
? "bg-green-500/20 text-green-400"
: "bg-yellow-500/20 text-yellow-400"
}`}
>
{formData.published ? "Published" : "Draft"}
</span>
{formData.featured && (
<span className="px-3 py-1 bg-stone-500/20 text-stone-400 rounded-full text-sm font-medium">
Featured
</span>
)}
</div>
<div className="text-sm text-gray-400">
Last updated: {new Date().toLocaleDateString()}
</div>
</div>
</div>
</div>
</motion.div>
</motion.div>
)}
</AnimatePresence>
</div>
);
}
export default function EditorPage() {
return (
<Suspense
fallback={
<div className="min-h-screen bg-gray-900 flex items-center justify-center">
<div className="text-white">Loading editor...</div>
</div>
}
>
<EditorPageContent />
</Suspense>
);
}