feat: implement WYSIWYG markdown editor
Add complete markdown editor with Go backend and React/TypeScript frontend. Backend: - Cobra CLI with configurable host, port, data-dir, static-dir flags - REST API for CRUD operations on markdown files (GET, POST, PUT, DELETE) - File storage with flat .md structure - Comprehensive Logrus logging for all operations - Static asset serving for frontend Frontend: - React 18 + TypeScript + Tailwind CSS - Live markdown editor with GFM preview (react-markdown) - File management UI (list, create, open, save, delete) - Theme system (Light/Dark/System) with localStorage persistence - Responsive design (320px - 1920px+) Testing: - 6 backend tests covering CRUD round-trip, validation, error handling - 19 frontend tests covering API, theme system, and UI components - All tests passing with single 'make test' command Build: - Frontend compiles to optimized assets in dist/ - Backend can serve frontend via --static-dir flag
This commit is contained in:
178
frontend/src/App.tsx
Normal file
178
frontend/src/App.tsx
Normal file
@@ -0,0 +1,178 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { FileList } from './components/FileList';
|
||||
import { Editor } from './components/Editor';
|
||||
import { Header } from './components/Header';
|
||||
import { NewFileDialog } from './components/NewFileDialog';
|
||||
import { api } from './services/api';
|
||||
import type { MarkdownFile } from './types';
|
||||
|
||||
function App() {
|
||||
const [files, setFiles] = useState<MarkdownFile[]>([]);
|
||||
const [selectedFile, setSelectedFile] = useState<MarkdownFile | null>(null);
|
||||
const [content, setContent] = useState('');
|
||||
const [originalContent, setOriginalContent] = useState('');
|
||||
const [showNewDialog, setShowNewDialog] = useState(false);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const loadFiles = useCallback(async () => {
|
||||
try {
|
||||
setError(null);
|
||||
const fetchedFiles = await api.list();
|
||||
setFiles(fetchedFiles);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to load files');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
loadFiles();
|
||||
}, [loadFiles]);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedFile) {
|
||||
setContent(selectedFile.content);
|
||||
setOriginalContent(selectedFile.content);
|
||||
} else {
|
||||
setContent('');
|
||||
setOriginalContent('');
|
||||
}
|
||||
}, [selectedFile]);
|
||||
|
||||
const handleSelectFile = async (name: string) => {
|
||||
try {
|
||||
setError(null);
|
||||
const file = await api.get(name);
|
||||
setSelectedFile(file);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to open file');
|
||||
}
|
||||
};
|
||||
|
||||
const handleCreateFile = async (name: string) => {
|
||||
try {
|
||||
setError(null);
|
||||
const file = await api.create(name, '# ' + name.replace('.md', '') + '\n\nStart writing here...');
|
||||
setFiles([...files, file]);
|
||||
setSelectedFile(file);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to create file');
|
||||
}
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!selectedFile || isSaving) return;
|
||||
|
||||
try {
|
||||
setIsSaving(true);
|
||||
setError(null);
|
||||
const updated = await api.update(selectedFile.name, content);
|
||||
setSelectedFile(updated);
|
||||
setOriginalContent(content);
|
||||
setFiles(files.map((f) => (f.name === updated.name ? updated : f)));
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to save file');
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteFile = async (name: string) => {
|
||||
if (!confirm(`Delete ${name}?`)) return;
|
||||
|
||||
try {
|
||||
setError(null);
|
||||
await api.delete(name);
|
||||
setFiles(files.filter((f) => f.name !== name));
|
||||
if (selectedFile?.name === name) {
|
||||
setSelectedFile(null);
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to delete file');
|
||||
}
|
||||
};
|
||||
|
||||
const hasUnsavedChanges = content !== originalContent;
|
||||
const canSave = selectedFile !== null && hasUnsavedChanges;
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-white dark:bg-gray-950 text-gray-900 dark:text-gray-100">
|
||||
<Header
|
||||
fileName={selectedFile?.name || ''}
|
||||
hasUnsavedChanges={hasUnsavedChanges}
|
||||
onNewFile={() => setShowNewDialog(true)}
|
||||
onSave={handleSave}
|
||||
canSave={canSave}
|
||||
/>
|
||||
|
||||
<div className="container mx-auto max-w-7xl">
|
||||
{loading && (
|
||||
<div className="p-8 text-center text-gray-500 dark:text-gray-400">
|
||||
Loading...
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!loading && error && (
|
||||
<div className="mx-4 mt-4 p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg">
|
||||
<p className="text-sm text-red-800 dark:text-red-200">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!loading && (
|
||||
<div className="grid grid-cols-1 lg:grid-cols-4 gap-4">
|
||||
<div className="lg:col-span-1">
|
||||
<FileList
|
||||
files={files}
|
||||
selectedFile={selectedFile?.name || null}
|
||||
onSelectFile={handleSelectFile}
|
||||
onDeleteFile={handleDeleteFile}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="lg:col-span-3">
|
||||
{selectedFile ? (
|
||||
<Editor
|
||||
content={content}
|
||||
onChange={setContent}
|
||||
placeholder="Write your markdown here..."
|
||||
/>
|
||||
) : (
|
||||
<div className="flex items-center justify-center h-[calc(100vh-160px)] min-h-[300px] bg-gray-50 dark:bg-gray-800 rounded-lg">
|
||||
<div className="text-center">
|
||||
<p className="text-gray-500 dark:text-gray-400 mb-2">
|
||||
No file selected
|
||||
</p>
|
||||
<button
|
||||
onClick={() => setShowNewDialog(true)}
|
||||
className="text-blue-600 dark:text-blue-400 hover:underline text-sm"
|
||||
>
|
||||
Create a new file to get started
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<NewFileDialog
|
||||
isOpen={showNewDialog}
|
||||
onClose={() => setShowNewDialog(false)}
|
||||
onCreate={handleCreateFile}
|
||||
existingNames={files.map((f) => f.name)}
|
||||
/>
|
||||
|
||||
{hasUnsavedChanges && (
|
||||
<div className="fixed bottom-4 right-4 px-4 py-2 bg-orange-100 dark:bg-orange-900/30 text-orange-800 dark:text-orange-200 rounded-lg text-sm">
|
||||
Unsaved changes
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
32
frontend/src/components/Editor.tsx
Normal file
32
frontend/src/components/Editor.tsx
Normal file
@@ -0,0 +1,32 @@
|
||||
import ReactMarkdown from 'react-markdown';
|
||||
import remarkGfm from 'remark-gfm';
|
||||
|
||||
interface EditorProps {
|
||||
content: string;
|
||||
onChange: (content: string) => void;
|
||||
placeholder?: string;
|
||||
}
|
||||
|
||||
export function Editor({ content, onChange, placeholder = '# Start writing\n\nYour markdown here...' }: EditorProps) {
|
||||
return (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 h-[calc(100vh-160px)] min-h-[300px]">
|
||||
<div className="border-r border-gray-200 dark:border-gray-700">
|
||||
<textarea
|
||||
value={content}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
placeholder={placeholder}
|
||||
className="w-full h-full p-4 resize-none outline-none bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100 font-mono text-sm leading-relaxed"
|
||||
spellCheck={false}
|
||||
/>
|
||||
</div>
|
||||
<div className="p-4 overflow-auto bg-gray-50 dark:bg-gray-800">
|
||||
<ReactMarkdown
|
||||
remarkPlugins={[remarkGfm]}
|
||||
className="prose dark:prose-invert max-w-none"
|
||||
>
|
||||
{content || placeholder}
|
||||
</ReactMarkdown>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
58
frontend/src/components/FileList.tsx
Normal file
58
frontend/src/components/FileList.tsx
Normal file
@@ -0,0 +1,58 @@
|
||||
import { File, Trash2, FileText } from 'lucide-react';
|
||||
import type { MarkdownFile } from '../types';
|
||||
|
||||
interface FileListProps {
|
||||
files: MarkdownFile[];
|
||||
selectedFile: string | null;
|
||||
onSelectFile: (name: string) => void;
|
||||
onDeleteFile: (name: string) => void;
|
||||
}
|
||||
|
||||
export function FileList({ files, selectedFile, onSelectFile, onDeleteFile }: FileListProps) {
|
||||
return (
|
||||
<div className="border-b border-gray-200 dark:border-gray-700">
|
||||
<div className="px-6 py-3 bg-gray-50 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700">
|
||||
<h2 className="text-sm font-semibold text-gray-700 dark:text-gray-300 flex items-center gap-2">
|
||||
<File className="w-4 h-4" />
|
||||
Files ({files.length})
|
||||
</h2>
|
||||
</div>
|
||||
{files.length === 0 ? (
|
||||
<div className="p-4 text-center text-gray-500 dark:text-gray-400 text-sm">
|
||||
No markdown files yet. Create one to get started.
|
||||
</div>
|
||||
) : (
|
||||
<ul className="divide-y divide-gray-200 dark:divide-gray-700 max-h-[200px] overflow-y-auto">
|
||||
{files.map((file) => (
|
||||
<li
|
||||
key={file.name}
|
||||
className={`flex items-center justify-between px-6 py-3 hover:bg-gray-50 dark:hover:bg-gray-800 cursor-pointer transition-colors ${
|
||||
selectedFile === file.name ? 'bg-blue-50 dark:bg-blue-900/20' : ''
|
||||
}`}
|
||||
>
|
||||
<button
|
||||
onClick={() => onSelectFile(file.name)}
|
||||
className="flex items-center gap-2 flex-1 text-left"
|
||||
>
|
||||
<FileText className="w-4 h-4 text-gray-400" />
|
||||
<span className="text-sm text-gray-900 dark:text-gray-100 truncate">
|
||||
{file.name}
|
||||
</span>
|
||||
</button>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onDeleteFile(file.name);
|
||||
}}
|
||||
className="p-1 text-gray-400 hover:text-red-500 transition-colors"
|
||||
aria-label={`Delete ${file.name}`}
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
71
frontend/src/components/Header.tsx
Normal file
71
frontend/src/components/Header.tsx
Normal file
@@ -0,0 +1,71 @@
|
||||
import { Sun, Moon, Monitor, Plus, Save } from 'lucide-react';
|
||||
import { useTheme } from '../hooks/useTheme';
|
||||
import type { Theme } from '../types';
|
||||
|
||||
interface HeaderProps {
|
||||
fileName: string;
|
||||
hasUnsavedChanges: boolean;
|
||||
onNewFile: () => void;
|
||||
onSave: () => void;
|
||||
canSave: boolean;
|
||||
}
|
||||
|
||||
export function Header({ fileName, hasUnsavedChanges, onNewFile, onSave, canSave }: HeaderProps) {
|
||||
const { theme, setTheme } = useTheme();
|
||||
|
||||
const themes: { value: Theme; icon: any; label: string }[] = [
|
||||
{ value: 'light', icon: Sun, label: 'Light' },
|
||||
{ value: 'dark', icon: Moon, label: 'Dark' },
|
||||
{ value: 'system', icon: Monitor, label: 'System' },
|
||||
];
|
||||
|
||||
return (
|
||||
<header className="bg-white dark:bg-gray-900 border-b border-gray-200 dark:border-gray-700 px-4 py-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
onClick={onNewFile}
|
||||
className="flex items-center gap-2 px-3 py-1.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm font-medium transition-colors"
|
||||
>
|
||||
<Plus className="w-4 h-4" />
|
||||
New
|
||||
</button>
|
||||
<button
|
||||
onClick={onSave}
|
||||
disabled={!canSave}
|
||||
className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg text-sm font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
<Save className="w-4 h-4" />
|
||||
Save
|
||||
</button>
|
||||
{hasUnsavedChanges && (
|
||||
<span className="text-xs text-orange-600 dark:text-orange-400 font-medium">
|
||||
Unsaved
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<h1 className="text-sm font-semibold text-gray-900 dark:text-gray-100">
|
||||
{fileName || 'Untitled'}
|
||||
</h1>
|
||||
|
||||
<div className="flex items-center gap-1">
|
||||
{themes.map(({ value, icon: Icon, label }) => (
|
||||
<button
|
||||
key={value}
|
||||
onClick={() => setTheme(value)}
|
||||
className={`p-2 rounded-lg transition-colors ${
|
||||
theme === value
|
||||
? 'bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400'
|
||||
: 'text-gray-500 hover:bg-gray-100 dark:hover:bg-gray-800'
|
||||
}`}
|
||||
title={`Switch to ${label} theme`}
|
||||
>
|
||||
<Icon className="w-5 h-5" />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
121
frontend/src/components/NewFileDialog.tsx
Normal file
121
frontend/src/components/NewFileDialog.tsx
Normal file
@@ -0,0 +1,121 @@
|
||||
import { useState, useRef, useEffect } from 'react';
|
||||
import { X } from 'lucide-react';
|
||||
|
||||
interface NewFileDialogProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onCreate: (name: string) => void;
|
||||
existingNames: string[];
|
||||
}
|
||||
|
||||
export function NewFileDialog({ isOpen, onClose, onCreate, existingNames }: NewFileDialogProps) {
|
||||
const [fileName, setFileName] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
setFileName('');
|
||||
setError('');
|
||||
inputRef.current?.focus();
|
||||
}
|
||||
}, [isOpen]);
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
const trimmedName = fileName.trim();
|
||||
|
||||
if (!trimmedName) {
|
||||
setError('File name is required');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!trimmedName.endsWith('.md')) {
|
||||
setError('File name must end with .md');
|
||||
return;
|
||||
}
|
||||
|
||||
if (existingNames.includes(trimmedName)) {
|
||||
setError('A file with this name already exists');
|
||||
return;
|
||||
}
|
||||
|
||||
if (trimmedName.includes('/') || trimmedName.includes('..')) {
|
||||
setError('Invalid file name');
|
||||
return;
|
||||
}
|
||||
|
||||
onCreate(trimmedName);
|
||||
onClose();
|
||||
};
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
|
||||
<div className="bg-white dark:bg-gray-900 rounded-xl shadow-xl w-full max-w-md">
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-gray-700">
|
||||
<h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100">
|
||||
New Markdown File
|
||||
</h2>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
|
||||
>
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="p-6">
|
||||
<div>
|
||||
<label htmlFor="fileName" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
||||
File Name
|
||||
</label>
|
||||
<input
|
||||
ref={inputRef}
|
||||
id="fileName"
|
||||
type="text"
|
||||
value={fileName}
|
||||
onChange={(e) => {
|
||||
setFileName(e.target.value);
|
||||
setError('');
|
||||
}}
|
||||
placeholder="example.md"
|
||||
className={`w-full px-3 py-2 border rounded-lg outline-none transition-colors ${
|
||||
error
|
||||
? 'border-red-300 dark:border-red-700 focus:border-red-500 dark:focus:border-red-500'
|
||||
: 'border-gray-300 dark:border-gray-600 focus:border-blue-500 dark:focus:border-blue-500'
|
||||
} bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100`}
|
||||
/>
|
||||
{error && (
|
||||
<p className="mt-2 text-sm text-red-600 dark:text-red-400">{error}</p>
|
||||
)}
|
||||
<p className="mt-2 text-xs text-gray-500 dark:text-gray-400">
|
||||
File name must end with .md
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-end gap-3 px-6 py-4 border-t border-gray-200 dark:border-gray-700">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
className="px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-lg transition-colors"
|
||||
>
|
||||
Create
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
51
frontend/src/hooks/useTheme.ts
Normal file
51
frontend/src/hooks/useTheme.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import type { Theme } from '../types';
|
||||
|
||||
const THEME_KEY = 'markdown-editor-theme';
|
||||
|
||||
export function useTheme() {
|
||||
const [theme, setThemeState] = useState<Theme>(() => {
|
||||
const stored = localStorage.getItem(THEME_KEY);
|
||||
if (stored && ['light', 'dark', 'system'].includes(stored)) {
|
||||
return stored as Theme;
|
||||
}
|
||||
return 'system';
|
||||
});
|
||||
const [resolvedTheme, setResolvedTheme] = useState<'light' | 'dark'>('light');
|
||||
|
||||
useEffect(() => {
|
||||
const root = window.document.documentElement;
|
||||
|
||||
const updateTheme = () => {
|
||||
let resolved: 'light' | 'dark';
|
||||
if (theme === 'system') {
|
||||
resolved = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
||||
} else {
|
||||
resolved = theme;
|
||||
}
|
||||
resolvedTheme !== resolved && setResolvedTheme(resolved);
|
||||
|
||||
if (resolved === 'dark') {
|
||||
root.classList.add('dark');
|
||||
} else {
|
||||
root.classList.remove('dark');
|
||||
}
|
||||
};
|
||||
|
||||
updateTheme();
|
||||
|
||||
if (theme === 'system') {
|
||||
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
|
||||
const handler = () => updateTheme();
|
||||
mediaQuery.addEventListener('change', handler);
|
||||
return () => mediaQuery.removeEventListener('change', handler);
|
||||
}
|
||||
}, [theme]);
|
||||
|
||||
const setTheme = (newTheme: Theme) => {
|
||||
setThemeState(newTheme);
|
||||
localStorage.setItem(THEME_KEY, newTheme);
|
||||
};
|
||||
|
||||
return { theme, resolvedTheme, setTheme };
|
||||
}
|
||||
107
frontend/src/index.css
Normal file
107
frontend/src/index.css
Normal file
@@ -0,0 +1,107 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
|
||||
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
|
||||
sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
code {
|
||||
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
|
||||
monospace;
|
||||
}
|
||||
|
||||
/* Markdown preview styles */
|
||||
.prose {
|
||||
max-width: none;
|
||||
}
|
||||
|
||||
.prose h1:first-child {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.prose a {
|
||||
color: #2563eb;
|
||||
}
|
||||
.dark .prose a {
|
||||
color: #60a5fa;
|
||||
}
|
||||
|
||||
.prose code {
|
||||
background-color: #f3f4f6;
|
||||
padding: 0.125rem 0.25rem;
|
||||
border-radius: 0.25rem;
|
||||
font-size: 0.875em;
|
||||
}
|
||||
.dark .prose code {
|
||||
background-color: #374151;
|
||||
}
|
||||
|
||||
.prose pre {
|
||||
background-color: #f3f4f6;
|
||||
border-radius: 0.5rem;
|
||||
padding: 1rem;
|
||||
overflow-x: auto;
|
||||
}
|
||||
.dark .prose pre {
|
||||
background-color: #1f2937;
|
||||
}
|
||||
|
||||
.prose pre code {
|
||||
background-color: transparent;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.prose blockquote {
|
||||
border-left-color: #d1d5db;
|
||||
background-color: #f9fafb;
|
||||
padding-left: 1rem;
|
||||
}
|
||||
.dark .prose blockquote {
|
||||
border-left-color: #4b5563;
|
||||
background-color: #1f2937;
|
||||
}
|
||||
|
||||
.prose table {
|
||||
border-collapse: collapse;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.prose th,
|
||||
.prose td {
|
||||
border-color: #e5e7eb;
|
||||
padding: 0.5rem;
|
||||
}
|
||||
.dark .prose th,
|
||||
.dark .prose td {
|
||||
border-color: #374151;
|
||||
}
|
||||
|
||||
.prose img {
|
||||
max-width: 100%;
|
||||
height: auto;
|
||||
}
|
||||
|
||||
/* Custom scrollbar for dark mode */
|
||||
.dark ::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
}
|
||||
|
||||
.dark ::-webkit-scrollbar-track {
|
||||
background: #1f2937;
|
||||
}
|
||||
|
||||
.dark ::-webkit-scrollbar-thumb {
|
||||
background: #4b5563;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.dark ::-webkit-scrollbar-thumb:hover {
|
||||
background: #6b7280;
|
||||
}
|
||||
10
frontend/src/main.tsx
Normal file
10
frontend/src/main.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import './index.css'
|
||||
import App from './App.tsx'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
)
|
||||
48
frontend/src/services/api.ts
Normal file
48
frontend/src/services/api.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import type { MarkdownFile, ApiError } from '../types';
|
||||
|
||||
const API_BASE = '/api/files';
|
||||
|
||||
async function handleResponse<T>(response: Response): Promise<T> {
|
||||
if (!response.ok) {
|
||||
const error: ApiError = await response.json().catch(() => ({ error: 'Unknown error' }));
|
||||
throw new Error(error.error || `HTTP ${response.status}`);
|
||||
}
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export const api = {
|
||||
async list(): Promise<MarkdownFile[]> {
|
||||
const response = await fetch(API_BASE);
|
||||
return handleResponse<MarkdownFile[]>(response);
|
||||
},
|
||||
|
||||
async get(name: string): Promise<MarkdownFile> {
|
||||
const response = await fetch(`${API_BASE}/${name}`);
|
||||
return handleResponse<MarkdownFile>(response);
|
||||
},
|
||||
|
||||
async create(name: string, content: string): Promise<MarkdownFile> {
|
||||
const response = await fetch(API_BASE, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name, content }),
|
||||
});
|
||||
return handleResponse<MarkdownFile>(response);
|
||||
},
|
||||
|
||||
async update(name: string, content: string): Promise<MarkdownFile> {
|
||||
const response = await fetch(`${API_BASE}/${name}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ content }),
|
||||
});
|
||||
return handleResponse<MarkdownFile>(response);
|
||||
},
|
||||
|
||||
async delete(name: string): Promise<void> {
|
||||
const response = await fetch(`${API_BASE}/${name}`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
await handleResponse<Record<string, never>>(response);
|
||||
},
|
||||
};
|
||||
87
frontend/src/test/App.test.tsx
Normal file
87
frontend/src/test/App.test.tsx
Normal file
@@ -0,0 +1,87 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import App from '../App';
|
||||
|
||||
// Mock the API
|
||||
vi.mock('../services/api', () => ({
|
||||
api: {
|
||||
list: vi.fn(),
|
||||
get: vi.fn(),
|
||||
create: vi.fn(),
|
||||
update: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const { api: mockApi } = await import('../services/api');
|
||||
|
||||
describe('App', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.stubGlobal('confirm', vi.fn(() => true));
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('renders loading state', () => {
|
||||
(mockApi.list as any).mockImplementation(() => new Promise(() => {}));
|
||||
render(<App />);
|
||||
expect(screen.getByText('Loading...')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders file list', async () => {
|
||||
(mockApi.list as any).mockResolvedValueOnce([
|
||||
{ name: 'test.md', content: '# Test', modified: 1234567890 },
|
||||
]);
|
||||
|
||||
render(<App />);
|
||||
await waitFor(() => screen.getByText('Files (1)'));
|
||||
expect(screen.getByText('test.md')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows empty state when no files', async () => {
|
||||
(mockApi.list as any).mockResolvedValueOnce([]);
|
||||
|
||||
render(<App />);
|
||||
await waitFor(() => screen.getByText(/no markdown files yet/i));
|
||||
expect(screen.getByText(/create a new file to get started/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('opens new file dialog', async () => {
|
||||
(mockApi.list as any).mockResolvedValueOnce([]);
|
||||
|
||||
render(<App />);
|
||||
await waitFor(() => screen.getByText('New'));
|
||||
|
||||
fireEvent.click(screen.getByText('New'));
|
||||
expect(screen.getByText('New Markdown File')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('can open new file dialog and enter filename', async () => {
|
||||
(mockApi.list as any).mockResolvedValue([]);
|
||||
|
||||
render(<App />);
|
||||
await waitFor(() => screen.getByText('New'));
|
||||
|
||||
fireEvent.click(screen.getByText('New'));
|
||||
|
||||
expect(screen.getByText('New Markdown File')).toBeInTheDocument();
|
||||
|
||||
const input = screen.getByLabelText('File Name');
|
||||
expect(input).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('displays files in the list', async () => {
|
||||
(mockApi.list as any).mockResolvedValue([
|
||||
{ name: 'example.md', content: '# Example', modified: 1234567890 },
|
||||
]);
|
||||
|
||||
render(<App />);
|
||||
|
||||
await waitFor(() => screen.getByText('Files (1)'));
|
||||
expect(screen.getByText('example.md')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
109
frontend/src/test/api.test.ts
Normal file
109
frontend/src/test/api.test.ts
Normal file
@@ -0,0 +1,109 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { api } from '../services/api';
|
||||
|
||||
describe('api service', () => {
|
||||
let fetchMock: ReturnType<typeof vi.fn>;
|
||||
// @ts-expect-error - We're intentionally shadowing global fetch
|
||||
const originalFetch = global.fetch;
|
||||
|
||||
beforeEach(() => {
|
||||
fetchMock = vi.fn();
|
||||
// @ts-expect-error - We're intentionally replacing global fetch
|
||||
global.fetch = fetchMock as any;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
// @ts-expect-error - We're intentionally restoring global fetch
|
||||
global.fetch = originalFetch;
|
||||
});
|
||||
|
||||
it('lists files', async () => {
|
||||
const mockFiles = [
|
||||
{ name: 'test.md', content: '# Test', modified: 1234567890 },
|
||||
];
|
||||
fetchMock.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => mockFiles,
|
||||
});
|
||||
|
||||
const files = await api.list();
|
||||
expect(files).toEqual(mockFiles);
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/files');
|
||||
});
|
||||
|
||||
it('gets a file', async () => {
|
||||
const mockFile = { name: 'test.md', content: '# Test', modified: 1234567890 };
|
||||
fetchMock.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => mockFile,
|
||||
});
|
||||
|
||||
const file = await api.get('test.md');
|
||||
expect(file).toEqual(mockFile);
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/files/test.md');
|
||||
});
|
||||
|
||||
it('creates a file', async () => {
|
||||
const mockFile = { name: 'new.md', content: '# New', modified: 1234567890 };
|
||||
fetchMock.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => mockFile,
|
||||
});
|
||||
|
||||
const file = await api.create('new.md', '# New');
|
||||
expect(file).toEqual(mockFile);
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/files', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'new.md', content: '# New' }),
|
||||
});
|
||||
});
|
||||
|
||||
it('updates a file', async () => {
|
||||
const mockFile = { name: 'test.md', content: '# Updated', modified: 1234567890 };
|
||||
fetchMock.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => mockFile,
|
||||
});
|
||||
|
||||
const file = await api.update('test.md', '# Updated');
|
||||
expect(file).toEqual(mockFile);
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/files/test.md', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ content: '# Updated' }),
|
||||
});
|
||||
});
|
||||
|
||||
it('deletes a file', async () => {
|
||||
fetchMock.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({}),
|
||||
});
|
||||
|
||||
await api.delete('test.md');
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/files/test.md', {
|
||||
method: 'DELETE',
|
||||
});
|
||||
});
|
||||
|
||||
it('throws error on failed request', async () => {
|
||||
fetchMock.mockResolvedValueOnce({
|
||||
ok: false,
|
||||
json: async () => ({ error: 'File not found' }),
|
||||
});
|
||||
|
||||
await expect(api.get('nonexistent.md')).rejects.toThrow('File not found');
|
||||
});
|
||||
|
||||
it('throws generic error on failed JSON parse', async () => {
|
||||
fetchMock.mockResolvedValueOnce({
|
||||
ok: false,
|
||||
json: async () => {
|
||||
throw new Error('Invalid JSON');
|
||||
},
|
||||
});
|
||||
|
||||
await expect(api.get('test.md')).rejects.toThrow('Unknown error');
|
||||
});
|
||||
});
|
||||
38
frontend/src/test/setup.ts
Normal file
38
frontend/src/test/setup.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import '@testing-library/jest-dom'
|
||||
|
||||
// Mock window.matchMedia
|
||||
Object.defineProperty(window, 'matchMedia', {
|
||||
writable: true,
|
||||
value: vi.fn().mockImplementation((query: string) => ({
|
||||
matches: false,
|
||||
media: query,
|
||||
onchange: null,
|
||||
addListener: vi.fn(),
|
||||
removeListener: vi.fn(),
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
dispatchEvent: vi.fn(),
|
||||
})),
|
||||
})
|
||||
|
||||
// Mock localStorage
|
||||
const localStorageMock = (() => {
|
||||
let store: Record<string, string> = {};
|
||||
|
||||
return {
|
||||
getItem: (key: string) => store[key] || null,
|
||||
setItem: (key: string, value: string) => {
|
||||
store[key] = value.toString();
|
||||
},
|
||||
removeItem: (key: string) => {
|
||||
delete store[key];
|
||||
},
|
||||
clear: () => {
|
||||
store = {};
|
||||
},
|
||||
};
|
||||
})();
|
||||
|
||||
Object.defineProperty(window, 'localStorage', {
|
||||
value: localStorageMock,
|
||||
})
|
||||
72
frontend/src/test/useTheme.test.ts
Normal file
72
frontend/src/test/useTheme.test.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
import { useTheme } from '../hooks/useTheme';
|
||||
|
||||
describe('useTheme', () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
document.documentElement.classList.remove('dark');
|
||||
});
|
||||
|
||||
it('defaults to system theme', () => {
|
||||
const { result } = renderHook(() => useTheme());
|
||||
expect(result.current.theme).toBe('system');
|
||||
});
|
||||
|
||||
it('resolves system theme to light when preference is light', () => {
|
||||
vi.spyOn(window, 'matchMedia').mockImplementation((query: string) => ({
|
||||
matches: query === '(prefers-color-scheme: dark)' ? false : true,
|
||||
media: query,
|
||||
onchange: null,
|
||||
addListener: vi.fn(),
|
||||
removeListener: vi.fn(),
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
dispatchEvent: vi.fn(),
|
||||
}));
|
||||
|
||||
const { result } = renderHook(() => useTheme());
|
||||
expect(result.current.resolvedTheme).toBe('light');
|
||||
});
|
||||
|
||||
it('can set light theme', () => {
|
||||
const { result } = renderHook(() => useTheme());
|
||||
|
||||
act(() => {
|
||||
result.current.setTheme('light');
|
||||
});
|
||||
|
||||
expect(result.current.theme).toBe('light');
|
||||
expect(result.current.resolvedTheme).toBe('light');
|
||||
expect(document.documentElement.classList.contains('dark')).toBe(false);
|
||||
});
|
||||
|
||||
it('can set dark theme', () => {
|
||||
const { result } = renderHook(() => useTheme());
|
||||
|
||||
act(() => {
|
||||
result.current.setTheme('dark');
|
||||
});
|
||||
|
||||
expect(result.current.theme).toBe('dark');
|
||||
expect(result.current.resolvedTheme).toBe('dark');
|
||||
expect(document.documentElement.classList.contains('dark')).toBe(true);
|
||||
});
|
||||
|
||||
it('persists theme to localStorage', () => {
|
||||
const { result } = renderHook(() => useTheme());
|
||||
|
||||
act(() => {
|
||||
result.current.setTheme('dark');
|
||||
});
|
||||
|
||||
expect(localStorage.getItem('markdown-editor-theme')).toBe('dark');
|
||||
});
|
||||
|
||||
it('restores theme from localStorage', () => {
|
||||
localStorage.setItem('markdown-editor-theme', 'light');
|
||||
|
||||
const { result } = renderHook(() => useTheme());
|
||||
expect(result.current.theme).toBe('light');
|
||||
});
|
||||
});
|
||||
11
frontend/src/types/index.ts
Normal file
11
frontend/src/types/index.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
export type Theme = 'light' | 'dark' | 'system';
|
||||
|
||||
export interface MarkdownFile {
|
||||
name: string;
|
||||
content: string;
|
||||
modified: number;
|
||||
}
|
||||
|
||||
export interface ApiError {
|
||||
error: string;
|
||||
}
|
||||
Reference in New Issue
Block a user