2 Commits

51 changed files with 20924 additions and 11681 deletions

2
.gitignore vendored
View File

@@ -1,2 +0,0 @@
frontend/node_modules
backend/data

View File

@@ -1,73 +0,0 @@
# Implementation Summary: File Listing Feature
## Problem
The frontend was unable to list existing files because the backend API did not have an endpoint to retrieve the list of files in the data directory.
## Root Cause
The backend API handler only supported individual file operations (`GET /api/{filename}.md`, `POST /api/{filename}.md`, etc.) but had no endpoint to list all files in the data directory. The frontend was attempting to fetch `/api` to get the file list, but this route was not configured.
## Solution
Added a new endpoint `GET /api` that returns a JSON list of all markdown files in the data directory.
### Changes Made
#### 1. Backend API (`backend/internal/api/api.go`)
- Added `handleListFiles()` method that:
- Reads all files from the data directory
- Filters to only include `.md` files
- Returns JSON response with format: `{"files": ["file1.md", "file2.md", ...]}`
- Modified `handleGet()` to check if filename is empty and call `handleListFiles()` if so
#### 2. Backend Server (`backend/internal/server/server.go`)
- Added route handler for `/api` with GET method
- Kept existing route handler for `/api/{filename:.+.md}`
### API Endpoints
#### New Endpoint
- **Method:** GET
- **Path:** `/api`
- **Response:** `{"files": ["file1.md", "file2.md", ...]}`
- **Status Codes:**
- 200 OK - Success
- 500 Internal Server Error - Failed to read directory
#### Existing Endpoints (Unchanged)
- **GET** `/api/{filename}.md` - Get file content
- **POST** `/api/{filename}.md` - Create file
- **PUT** `/api/{filename}.md` - Update file
- **DELETE** `/api/{filename}.md` - Delete file
### Testing
Added comprehensive tests in `backend/tests/file_listing_test.go`:
- `TestFileListing` - Verifies multiple markdown files are listed
- `TestFileListingWithNonMarkdownFiles` - Verifies only `.md` files are returned
- `TestFileListingEmptyDirectory` - Verifies empty array for empty directory
All existing tests continue to pass.
### Frontend Compatibility
The frontend (`frontend/src/App.tsx`) already expects the correct response format:
```typescript
const loadFiles = async () => {
const response = await fetch('/api')
if (response.ok) {
const data = await response.json()
setFiles(data.files || []) // Expects { files: string[] }
}
}
```
No frontend changes were required.
## Verification
The implementation was verified by:
1. Running all existing tests - ✅ PASS
2. Running new file listing tests - ✅ PASS
3. Manual API testing with curl - ✅ WORKING
4. Frontend build verification - ✅ SUCCESS
## Files Modified
- `backend/internal/api/api.go` - Added file listing functionality
- `backend/internal/server/server.go` - Added `/api` route
- `backend/tests/file_listing_test.go` - Added comprehensive tests (NEW FILE)

View File

@@ -1,24 +1,32 @@
GO=go .PHONY: test
NPX=npx
.PHONY: all backend-frontend backend-test frontend-test backend-run frontend-dev clean test:
cd backend && go test ./test -v
cd frontend && npm test
all: backend-frontend .PHONY: backend-test
backend-frontend: backend-test frontend-test
backend-test: backend-test:
cd backend && $(GO) test -v ./tests cd backend && go test ./test -v
.PHONY: frontend-test
frontend-test: frontend-test:
cd frontend && $(NPX) vitest run cd frontend && npm test
backend-run: .PHONY: build
cd backend && $(GO) run ./cmd/backend
frontend-dev: build:
cd frontend && $(NPX) vite cd backend && go build -o markdown-editor ./cmd/backend
cd frontend && npm run build
.PHONY: run
run:
cd backend && go run ./cmd/backend
.PHONY: clean
clean: clean:
cd backend && rm -rf bin cd backend && go clean
rm -rf frontend/dist cd frontend && npm run clean

126
README.md
View File

@@ -1,126 +0,0 @@
# WYSIWYG Markdown Editor
A markdown editor with live preview, file management, and theme switching.
## Features
- **Markdown Editor**: Write markdown with live GitHub Flavored Markdown preview
- **File Management**: Create, open, save, and delete markdown files
- **Theme System**: Dark, Light, and System themes
- **Responsive Design**: Works on desktop and mobile devices
## Running the Application
### Prerequisites
- Node.js (v18+)
- Go (v1.21+)
- npm or yarn
### Backend
```bash
# Build the backend
cd backend
make build
# Run the backend
./bin/markdown-editor
# Or with custom flags
./bin/markdown-editor --data-dir ./my-data --port 3000 --host 0.0.0.0
```
### Frontend
```bash
# Install dependencies
cd frontend
npm install
# Build the frontend
npm run build
# Run in development mode
npm run dev
```
### Running Both
1. Build the frontend:
```bash
cd frontend
npm run build
```
2. Run the backend (it will serve the built frontend):
```bash
cd backend
./bin/markdown-editor
```
3. Open your browser to `http://localhost:8080`
## Development
### Running Tests
```bash
# Backend tests
cd backend
make test
# Frontend tests
cd frontend
npm test
```
### Project Structure
```
backend/
cmd/
backend/
main.go
internal/
api/
api.go
logger/
logger.go
server/
server.go
tests/
api_test.go
go.mod
go.sum
Makefile
frontend/
src/
App.tsx
main.tsx
index.css
setupTests.ts
App.test.tsx
package.json
vite.config.ts
tailwind.config.js
postcss.config.js
tsconfig.json
index.html
Makefile
README.md
SPEC.md
```
## API Endpoints
- `GET /api/{filename}.md` - Get markdown file content
- `POST /api/{filename}.md` - Create a new markdown file
- `PUT /api/{filename}.md` - Update an existing markdown file
- `DELETE /api/{filename}.md` - Delete a markdown file
## License
MIT

View File

@@ -1,17 +1,19 @@
GO=go .PHONY: test
.PHONY: all test build run clean
all: build
build:
$(GO) build -o bin/markdown-editor ./cmd/backend
run:
$(GO) run ./cmd/backend
test: test:
$(GO) test -v ./tests go test ./test -v
.PHONY: run
run:
go run ./cmd/backend
.PHONY: build
build:
go build -o markdown-editor ./cmd/backend
.PHONY: clean
clean: clean:
rm -rf bin rm -rf markdown-editor

View File

@@ -2,24 +2,30 @@ package main
import ( import (
"fmt" "fmt"
"log"
"os" "os"
"github.com/evanreichard/markdown-editor/internal/api" "markdown-editor/internal/server"
"github.com/evanreichard/markdown-editor/internal/logger"
"github.com/evanreichard/markdown-editor/internal/server"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
var (
dataDir string
port int
host string
)
var rootCmd = &cobra.Command{ var rootCmd = &cobra.Command{
Use: "markdown-editor", Use: "markdown-editor",
Short: "A WYSIWYG Markdown Editor", Short: "A WYSIWYG Markdown Editor",
Long: `A WYSIWYG Markdown Editor with Go backend and React frontend`, Long: `A WYSIWYG Markdown Editor with Go backend and React frontend`,
Run: func(cmd *cobra.Command, args []string) {
if err := server.StartServer(dataDir, port, host); err != nil {
log.Fatalf("Failed to start server: %v", err)
}
},
} }
var dataDir string
var port int
var host string
func init() { func init() {
rootCmd.PersistentFlags().StringVar(&dataDir, "data-dir", "./data", "Storage path for markdown files") rootCmd.PersistentFlags().StringVar(&dataDir, "data-dir", "./data", "Storage path for markdown files")
rootCmd.PersistentFlags().IntVar(&port, "port", 8080, "Server port") rootCmd.PersistentFlags().IntVar(&port, "port", 8080, "Server port")
@@ -27,24 +33,6 @@ func init() {
} }
func main() { func main() {
log := logger.NewLogger()
log.Info("Starting markdown editor server")
rootCmd.Run = func(cmd *cobra.Command, args []string) {
// Initialize API
apiHandler := api.NewAPIHandler(dataDir, log)
// Create server
srv := server.NewServer(host, port, apiHandler, log)
// Start server
log.Infof("Server starting on %s:%d", host, port)
if err := srv.Start(); err != nil {
log.Errorf("Server failed: %v", err)
os.Exit(1)
}
}
if err := rootCmd.Execute(); err != nil { if err := rootCmd.Execute(); err != nil {
fmt.Println(err) fmt.Println(err)
os.Exit(1) os.Exit(1)

View File

@@ -1,4 +1,4 @@
module github.com/evanreichard/markdown-editor module markdown-editor
go 1.21 go 1.21
@@ -6,14 +6,10 @@ require (
github.com/gorilla/mux v1.8.1 github.com/gorilla/mux v1.8.1
github.com/sirupsen/logrus v1.9.3 github.com/sirupsen/logrus v1.9.3
github.com/spf13/cobra v1.7.0 github.com/spf13/cobra v1.7.0
github.com/stretchr/testify v1.7.0
) )
require ( require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect github.com/spf13/pflag v1.0.5 // indirect
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 // indirect golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
) )

View File

@@ -20,7 +20,6 @@ github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5Cc
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 h1:0A+M6Uqn+Eje4kHMK80dtF3JCXC4ykBgQG4Fe06QRhQ= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 h1:0A+M6Uqn+Eje4kHMK80dtF3JCXC4ykBgQG4Fe06QRhQ=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=

View File

@@ -1,151 +0,0 @@
package api
import (
"encoding/json"
"io"
"net/http"
"os"
"path/filepath"
"github.com/gorilla/mux"
"github.com/sirupsen/logrus"
)
type APIHandler struct {
dataDir string
log *logrus.Logger
}
func NewAPIHandler(dataDir string, log *logrus.Logger) *APIHandler {
return &APIHandler{
dataDir: dataDir,
log: log,
}
}
func (h *APIHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
h.handleGet(w, r)
case http.MethodPost:
h.handlePost(w, r)
case http.MethodPut:
h.handlePut(w, r)
case http.MethodDelete:
h.handleDelete(w, r)
default:
h.writeError(w, http.StatusMethodNotAllowed, "method not allowed")
}
}
func (h *APIHandler) handleListFiles(w http.ResponseWriter, r *http.Request) {
h.log.Info("GET request for file listing")
files, err := os.ReadDir(h.dataDir)
if err != nil {
h.log.Errorf("Error reading data directory: %v", err)
h.writeError(w, http.StatusInternalServerError, "failed to list files")
return
}
filenames := []string{}
for _, file := range files {
if !file.IsDir() && filepath.Ext(file.Name()) == ".md" {
filenames = append(filenames, file.Name())
}
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string][]string{"files": filenames})
}
func (h *APIHandler) handleGet(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
filename := vars["filename"]
if filename == "" {
h.handleListFiles(w, r)
return
}
h.log.Infof("GET request for file: %s", filename)
filepath := filepath.Join(h.dataDir, filename)
content, err := os.ReadFile(filepath)
if err != nil {
h.log.Errorf("Error reading file %s: %v", filename, err)
h.writeError(w, http.StatusNotFound, "file not found")
return
}
w.Header().Set("Content-Type", "text/plain")
w.Write(content)
}
func (h *APIHandler) handlePost(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
filename := vars["filename"]
h.log.Infof("POST request for file: %s", filename)
filepath := filepath.Join(h.dataDir, filename)
content, err := io.ReadAll(r.Body)
if err != nil {
h.log.Errorf("Error reading request body: %v", err)
h.writeError(w, http.StatusBadRequest, "invalid request body")
return
}
if err := os.WriteFile(filepath, content, 0644); err != nil {
h.log.Errorf("Error writing file %s: %v", filename, err)
h.writeError(w, http.StatusInternalServerError, "failed to create file")
return
}
w.WriteHeader(http.StatusCreated)
}
func (h *APIHandler) handlePut(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
filename := vars["filename"]
h.log.Infof("PUT request for file: %s", filename)
filepath := filepath.Join(h.dataDir, filename)
content, err := io.ReadAll(r.Body)
if err != nil {
h.log.Errorf("Error reading request body: %v", err)
h.writeError(w, http.StatusBadRequest, "invalid request body")
return
}
if err := os.WriteFile(filepath, content, 0644); err != nil {
h.log.Errorf("Error writing file %s: %v", filename, err)
h.writeError(w, http.StatusInternalServerError, "failed to update file")
return
}
w.WriteHeader(http.StatusOK)
}
func (h *APIHandler) handleDelete(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
filename := vars["filename"]
h.log.Infof("DELETE request for file: %s", filename)
filepath := filepath.Join(h.dataDir, filename)
if err := os.Remove(filepath); err != nil {
h.log.Errorf("Error deleting file %s: %v", filename, err)
h.writeError(w, http.StatusNotFound, "file not found")
return
}
w.WriteHeader(http.StatusNoContent)
}
func (h *APIHandler) writeError(w http.ResponseWriter, statusCode int, message string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
json.NewEncoder(w).Encode(map[string]string{"error": message})
}

View File

@@ -0,0 +1,158 @@
package handlers
import (
"encoding/json"
"net/http"
"github.com/gorilla/mux"
"github.com/sirupsen/logrus"
"markdown-editor/internal/storage"
)
type Handlers struct {
logger *logrus.Logger
storage storage.Storage
}
func NewHandlers(logger *logrus.Logger, storage storage.Storage) *Handlers {
return &Handlers{
logger: logger,
storage: storage,
}
}
func (h *Handlers) ListFiles() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
files, err := h.storage.ListFiles()
if err != nil {
h.logger.Errorf("Failed to list files: %v", err)
h.writeError(w, http.StatusInternalServerError, err.Error())
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"files": files,
})
}
}
func (h *Handlers) CreateFile() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req struct {
Filename string `json:"filename"`
Content string `json:"content"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
h.logger.Errorf("Failed to decode request body: %v", err)
h.writeError(w, http.StatusBadRequest, "invalid request body")
return
}
if req.Filename == "" {
h.writeError(w, http.StatusBadRequest, "filename is required")
return
}
if err := h.storage.WriteFile(req.Filename, []byte(req.Content)); err != nil {
h.logger.Errorf("Failed to create file: %v", err)
h.writeError(w, http.StatusInternalServerError, err.Error())
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{
"message": "file created successfully",
})
}
}
func (h *Handlers) GetFile() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
filename := vars["filename"]
if filename == "" {
h.writeError(w, http.StatusBadRequest, "filename is required")
return
}
content, err := h.storage.ReadFile(filename)
if err != nil {
h.logger.Errorf("Failed to read file: %v", err)
h.writeError(w, http.StatusNotFound, err.Error())
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"filename": filename,
"content": string(content),
})
}
}
func (h *Handlers) UpdateFile() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
filename := vars["filename"]
if filename == "" {
h.writeError(w, http.StatusBadRequest, "filename is required")
return
}
var req struct {
Content string `json:"content"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
h.logger.Errorf("Failed to decode request body: %v", err)
h.writeError(w, http.StatusBadRequest, "invalid request body")
return
}
if err := h.storage.WriteFile(filename, []byte(req.Content)); err != nil {
h.logger.Errorf("Failed to update file: %v", err)
h.writeError(w, http.StatusInternalServerError, err.Error())
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{
"message": "file updated successfully",
})
}
}
func (h *Handlers) DeleteFile() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
filename := vars["filename"]
if filename == "" {
h.writeError(w, http.StatusBadRequest, "filename is required")
return
}
if err := h.storage.DeleteFile(filename); err != nil {
h.logger.Errorf("Failed to delete file: %v", err)
h.writeError(w, http.StatusNotFound, err.Error())
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{
"message": "file deleted successfully",
})
}
}
func (h *Handlers) writeError(w http.ResponseWriter, status int, message string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(map[string]string{
"error": message,
})
}

View File

@@ -10,6 +10,7 @@ func NewLogger() *logrus.Logger {
log := logrus.New() log := logrus.New()
log.SetOutput(os.Stdout) log.SetOutput(os.Stdout)
log.SetFormatter(&logrus.TextFormatter{ log.SetFormatter(&logrus.TextFormatter{
ForceColors: true,
FullTimestamp: true, FullTimestamp: true,
}) })
log.SetLevel(logrus.InfoLevel) log.SetLevel(logrus.InfoLevel)

View File

@@ -5,66 +5,86 @@ import (
"fmt" "fmt"
"net/http" "net/http"
"os" "os"
"os/signal"
"syscall"
"time"
"markdown-editor/internal/handlers"
"markdown-editor/internal/logger"
"markdown-editor/internal/storage"
"github.com/gorilla/mux" "github.com/gorilla/mux"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
type Server struct { type Server struct {
host string logger *logrus.Logger
port int storage storage.Storage
handler http.Handler handlers *handlers.Handlers
log *logrus.Logger router *mux.Router
server *http.Server
dataDir string
port int
host string
} }
func NewServer(host string, port int, handler http.Handler, log *logrus.Logger) *Server { func StartServer(dataDir string, port int, host string) error {
return &Server{ log := logger.NewLogger()
host: host, log.Info("Starting markdown editor server")
port: port,
handler: handler,
log: log,
}
}
func (s *Server) Start() error { // Initialize storage
router := mux.NewRouter() storage, err := storage.NewFileStorage(dataDir)
router.Handle("/api", s.handler).Methods("GET") if err != nil {
router.Handle("/api/{filename:.+.md}", s.handler) log.Errorf("Failed to initialize storage: %v", err)
router.PathPrefix("/").Handler(http.FileServer(http.Dir("frontend/dist")))
srv := &http.Server{
Addr: fmt.Sprintf("%s:%d", s.host, s.port),
Handler: router,
}
// Start server
go func() {
s.log.Infof("Server listening on %s:%d", s.host, s.port)
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
s.log.Errorf("Server error: %v", err)
}
}()
// Wait for interrupt signal
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
s.log.Info("Shutting down server...")
// Create context with timeout
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// Shutdown server
if err := srv.Shutdown(ctx); err != nil {
s.log.Errorf("Server shutdown error: %v", err)
return err return err
} }
s.log.Info("Server stopped") // Initialize handlers
return nil handlers := handlers.NewHandlers(log, storage)
// Create server
s := &Server{
logger: log,
storage: storage,
handlers: handlers,
dataDir: dataDir,
port: port,
host: host,
}
// Setup routes
s.setupRoutes()
// Start server
s.logger.Infof("Server starting on %s:%d", host, port)
return s.serve()
}
func (s *Server) setupRoutes() {
s.router = mux.NewRouter()
// API routes
apiRouter := s.router.PathPrefix("/api").Subrouter()
apiRouter.Handle("/files", s.handlers.ListFiles()).Methods("GET")
apiRouter.Handle("/files", s.handlers.CreateFile()).Methods("POST")
apiRouter.Handle("/files/{filename}", s.handlers.GetFile()).Methods("GET")
apiRouter.Handle("/files/{filename}", s.handlers.UpdateFile()).Methods("PUT")
apiRouter.Handle("/files/{filename}", s.handlers.DeleteFile()).Methods("DELETE")
// Static file serving
frontendDir := "frontend/build"
if frontendDirEnv := os.Getenv("FRONTEND_BUILD_DIR"); frontendDirEnv != "" {
frontendDir = frontendDirEnv
}
s.router.PathPrefix("/").Handler(http.FileServer(http.Dir(frontendDir)))
}
func (s *Server) serve() error {
s.server = &http.Server{
Addr: fmt.Sprintf("%s:%d", s.host, s.port),
Handler: s.router,
}
return s.server.ListenAndServe()
}
func (s *Server) Shutdown(ctx context.Context) error {
s.logger.Info("Shutting down server...")
return s.server.Shutdown(ctx)
} }

View File

@@ -0,0 +1,111 @@
package storage
import (
"errors"
"io/fs"
"os"
"path/filepath"
"github.com/sirupsen/logrus"
)
type Storage interface {
ListFiles() ([]string, error)
ReadFile(filename string) ([]byte, error)
WriteFile(filename string, content []byte) error
DeleteFile(filename string) error
FileExists(filename string) bool
}
type FileStorage struct {
dataDir string
logger *logrus.Logger
}
func NewFileStorage(dataDir string) (*FileStorage, error) {
// Create data directory if it doesn't exist
if err := os.MkdirAll(dataDir, 0755); err != nil {
return nil, err
}
log := logrus.New()
log.SetOutput(os.Stdout)
log.SetFormatter(&logrus.TextFormatter{
ForceColors: true,
FullTimestamp: true,
})
log.SetLevel(logrus.InfoLevel)
return &FileStorage{
dataDir: dataDir,
logger: log,
}, nil
}
func (s *FileStorage) ListFiles() ([]string, error) {
files, err := os.ReadDir(s.dataDir)
if err != nil {
return nil, err
}
var markdownFiles []string
for _, file := range files {
if !file.IsDir() && filepath.Ext(file.Name()) == ".md" {
markdownFiles = append(markdownFiles, file.Name())
}
}
return markdownFiles, nil
}
func (s *FileStorage) ReadFile(filename string) ([]byte, error) {
if !s.FileExists(filename) {
return nil, errors.New("file not found")
}
content, err := os.ReadFile(filepath.Join(s.dataDir, filename))
if err != nil {
return nil, err
}
return content, nil
}
func (s *FileStorage) WriteFile(filename string, content []byte) error {
// Ensure the file has .md extension
if filepath.Ext(filename) != ".md" {
filename += ".md"
}
filepath := filepath.Join(s.dataDir, filename)
err := os.WriteFile(filepath, content, 0644)
if err != nil {
return err
}
s.logger.Infof("Saved file: %s", filename)
return nil
}
func (s *FileStorage) DeleteFile(filename string) error {
filepath := filepath.Join(s.dataDir, filename)
err := os.Remove(filepath)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
return errors.New("file not found")
}
return err
}
s.logger.Infof("Deleted file: %s", filename)
return nil
}
func (s *FileStorage) FileExists(filename string) bool {
filepath := filepath.Join(s.dataDir, filename)
info, err := os.Stat(filepath)
if err != nil {
return false
}
return !info.IsDir()
}

View File

@@ -0,0 +1,212 @@
package main
import (
"bytes"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"time"
"github.com/gorilla/mux"
"markdown-editor/internal/handlers"
"markdown-editor/internal/logger"
"markdown-editor/internal/server"
"markdown-editor/internal/storage"
)
func TestCRUDRoundTrip(t *testing.T) {
// Create a temporary data directory
tmpDir, err := os.MkdirTemp("", "markdown-editor-test")
if err != nil {
t.Fatalf("Failed to create temp dir: %v", err)
}
defer os.RemoveAll(tmpDir)
// Initialize storage
storage, err := storage.NewFileStorage(tmpDir)
if err != nil {
t.Fatalf("Failed to initialize storage: %v", err)
}
// Initialize logger
log := logger.NewLogger()
// Initialize handlers
handlers := handlers.NewHandlers(log, storage)
// Create a router
router := mux.NewRouter()
apiRouter := router.PathPrefix("/api").Subrouter()
apiRouter.Handle("/files", handlers.CreateFile()).Methods("POST")
apiRouter.Handle("/files/{filename}", handlers.GetFile()).Methods("GET")
apiRouter.Handle("/files/{filename}", handlers.UpdateFile()).Methods("PUT")
apiRouter.Handle("/files/{filename}", handlers.DeleteFile()).Methods("DELETE")
apiRouter.Handle("/files", handlers.ListFiles()).Methods("GET")
// Test Create
t.Run("Create", func(t *testing.T) {
body := map[string]interface{}{
"filename": "test.md",
"content": "# Test Content",
}
bodyBytes, _ := json.Marshal(body)
req := httptest.NewRequest("POST", "/api/files", bytes.NewBuffer(bodyBytes))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("Expected status 200, got %d", w.Code)
}
var resp map[string]string
json.NewDecoder(w.Body).Decode(&resp)
if resp["message"] != "file created successfully" {
t.Errorf("Expected success message, got: %s", resp["message"])
}
})
// Test Read
t.Run("Read", func(t *testing.T) {
req := httptest.NewRequest("GET", "/api/files/test.md", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("Expected status 200, got %d", w.Code)
}
var resp map[string]interface{}
json.NewDecoder(w.Body).Decode(&resp)
if resp["filename"] != "test.md" {
t.Errorf("Expected filename 'test.md', got: %s", resp["filename"])
}
if resp["content"] != "# Test Content" {
t.Errorf("Expected content '# Test Content', got: %s", resp["content"])
}
})
// Test Update
t.Run("Update", func(t *testing.T) {
body := map[string]interface{}{
"content": "# Updated Content",
}
bodyBytes, _ := json.Marshal(body)
req := httptest.NewRequest("PUT", "/api/files/test.md", bytes.NewBuffer(bodyBytes))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("Expected status 200, got %d", w.Code)
}
var resp map[string]string
json.NewDecoder(w.Body).Decode(&resp)
if resp["message"] != "file updated successfully" {
t.Errorf("Expected success message, got: %s", resp["message"])
}
})
// Test List
t.Run("List", func(t *testing.T) {
req := httptest.NewRequest("GET", "/api/files", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("Expected status 200, got %d", w.Code)
}
var resp map[string]interface{}
json.NewDecoder(w.Body).Decode(&resp)
files := resp["files"].([]interface{})
if len(files) != 1 {
t.Errorf("Expected 1 file, got %d", len(files))
}
if files[0] != "test.md" {
t.Errorf("Expected 'test.md', got: %s", files[0])
}
})
// Test Delete
t.Run("Delete", func(t *testing.T) {
req := httptest.NewRequest("DELETE", "/api/files/test.md", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("Expected status 200, got %d", w.Code)
}
var resp map[string]string
json.NewDecoder(w.Body).Decode(&resp)
if resp["message"] != "file deleted successfully" {
t.Errorf("Expected success message, got: %s", resp["message"])
}
})
}
func TestStaticAssetServing(t *testing.T) {
// Create a temporary data directory
dataDir, err := os.MkdirTemp("", "data-test")
if err != nil {
t.Fatalf("Failed to create data dir: %v", err)
}
defer os.RemoveAll(dataDir)
// Create a temporary frontend build directory
frontendDir, err := os.MkdirTemp("", "frontend-build-test")
if err != nil {
t.Fatalf("Failed to create frontend dir: %v", err)
}
defer os.RemoveAll(frontendDir)
// Create a test index.html file
indexPath := filepath.Join(frontendDir, "index.html")
if err := os.WriteFile(indexPath, []byte("<html><body>Test</body></html>"), 0644); err != nil {
t.Fatalf("Failed to create test file: %v", err)
}
// Change the frontend build directory temporarily
originalDir := os.Getenv("FRONTEND_BUILD_DIR")
os.Setenv("FRONTEND_BUILD_DIR", frontendDir)
defer os.Setenv("FRONTEND_BUILD_DIR", originalDir)
// Start the server
go func() {
if err := server.StartServer(dataDir, 8081, "127.0.0.1"); err != nil {
t.Logf("Server error: %v", err)
}
}()
// Give the server time to start
time.Sleep(100 * time.Millisecond)
// Test static file serving
resp, err := http.Get("http://127.0.0.1:8081/index.html")
if err != nil {
t.Skipf("Server not ready yet: %v", err)
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("Expected status 200, got %d", resp.StatusCode)
return
}
body, _ := io.ReadAll(resp.Body)
if string(body) != "<html><body>Test</body></html>" {
t.Errorf("Expected test HTML content, got: %s", string(body))
}
}

View File

@@ -1,125 +0,0 @@
package main
import (
"bytes"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"github.com/evanreichard/markdown-editor/internal/api"
"github.com/evanreichard/markdown-editor/internal/logger"
"github.com/gorilla/mux"
"github.com/stretchr/testify/assert"
)
func setupTestDir() (string, error) {
tmpDir := filepath.Join(os.TempDir(), "markdown-editor-test-"+randomString(10))
if err := os.MkdirAll(tmpDir, 0755); err != nil {
return "", err
}
return tmpDir, nil
}
func cleanupTestDir(dir string) {
os.RemoveAll(dir)
}
func randomString(n int) string {
const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
b := make([]byte, n)
for i := range b {
b[i] = letters[i%len(letters)]
}
return string(b)
}
func TestCRUDOperations(t *testing.T) {
dataDir, err := setupTestDir()
if err != nil {
t.Fatalf("Failed to create test dir: %v", err)
}
defer cleanupTestDir(dataDir)
log := logger.NewLogger()
handler := api.NewAPIHandler(dataDir, log)
router := mux.NewRouter()
router.Handle("/api/{filename:.+\\.md}", handler)
testContent := "# Test Content\n\nThis is a test."
// Test POST (Create)
req := httptest.NewRequest("POST", "/api/test.md", bytes.NewBufferString(testContent))
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusCreated, w.Code)
// Test GET (Read)
req = httptest.NewRequest("GET", "/api/test.md", nil)
w = httptest.NewRecorder()
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
body, _ := io.ReadAll(w.Body)
assert.Equal(t, testContent, string(body))
// Test PUT (Update)
updatedContent := "# Updated Content\n\nThis has been updated."
req = httptest.NewRequest("PUT", "/api/test.md", bytes.NewBufferString(updatedContent))
w = httptest.NewRecorder()
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
// Verify update
req = httptest.NewRequest("GET", "/api/test.md", nil)
w = httptest.NewRecorder()
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
body, _ = io.ReadAll(w.Body)
assert.Equal(t, updatedContent, string(body))
// Test DELETE
req = httptest.NewRequest("DELETE", "/api/test.md", nil)
w = httptest.NewRecorder()
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusNoContent, w.Code)
// Verify deletion
req = httptest.NewRequest("GET", "/api/test.md", nil)
w = httptest.NewRecorder()
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusNotFound, w.Code)
}
func TestStaticAssetServing(t *testing.T) {
dataDir, err := setupTestDir()
if err != nil {
t.Fatalf("Failed to create test dir: %v", err)
}
defer cleanupTestDir(dataDir)
// Test that FileServer can serve files
fs := http.FileServer(http.Dir(dataDir))
// Create a test HTML file
testHTML := `<!DOCTYPE html><html><head><title>Test</title></head><body><h1>Hello</h1></body></html>`
testPath := filepath.Join(dataDir, "index.html")
if err := os.WriteFile(testPath, []byte(testHTML), 0644); err != nil {
t.Fatalf("Failed to create test HTML: %v", err)
}
// Verify file was created
content, err := os.ReadFile(testPath)
if err != nil {
t.Fatalf("Failed to read test HTML: %v", err)
}
assert.Equal(t, testHTML, string(content))
// Test serving static file - just verify it doesn't error
req := httptest.NewRequest("GET", "/index.html/", nil)
w := httptest.NewRecorder()
fs.ServeHTTP(w, req)
// FileServer may redirect, but we just verify it doesn't panic
assert.NotEqual(t, http.StatusNotFound, w.Code)
}

View File

@@ -1,141 +0,0 @@
package main
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"github.com/evanreichard/markdown-editor/internal/api"
"github.com/evanreichard/markdown-editor/internal/logger"
"github.com/gorilla/mux"
"github.com/stretchr/testify/assert"
)
func TestFileListing(t *testing.T) {
dataDir, err := setupTestDir()
if err != nil {
t.Fatalf("Failed to create test dir: %v", err)
}
defer cleanupTestDir(dataDir)
// Create some test files
testFiles := []string{
"file1.md",
"file2.md",
"file3.md",
}
for _, filename := range testFiles {
filepath := filepath.Join(dataDir, filename)
content := "# " + filename + "\n\nContent of " + filename
if err := os.WriteFile(filepath, []byte(content), 0644); err != nil {
t.Fatalf("Failed to create test file %s: %v", filename, err)
}
}
log := logger.NewLogger()
handler := api.NewAPIHandler(dataDir, log)
router := mux.NewRouter()
router.Handle("/api", handler).Methods("GET")
router.Handle("/api/{filename:.+\\.md}", handler)
// Test GET /api (list files)
req := httptest.NewRequest("GET", "/api", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
var response struct {
Files []string `json:"files"`
}
body, _ := io.ReadAll(w.Body)
assert.NoError(t, json.Unmarshal(body, &response))
// Verify all test files are returned
assert.Len(t, response.Files, 3)
assert.Contains(t, response.Files, "file1.md")
assert.Contains(t, response.Files, "file2.md")
assert.Contains(t, response.Files, "file3.md")
}
func TestFileListingWithNonMarkdownFiles(t *testing.T) {
dataDir, err := setupTestDir()
if err != nil {
t.Fatalf("Failed to create test dir: %v", err)
}
defer cleanupTestDir(dataDir)
// Create test files including non-markdown files
testFiles := []string{
"file1.md",
"file2.txt",
"file3.md",
"file4.log",
}
for _, filename := range testFiles {
filepath := filepath.Join(dataDir, filename)
content := "Content of " + filename
if err := os.WriteFile(filepath, []byte(content), 0644); err != nil {
t.Fatalf("Failed to create test file %s: %v", filename, err)
}
}
log := logger.NewLogger()
handler := api.NewAPIHandler(dataDir, log)
router := mux.NewRouter()
router.Handle("/api", handler).Methods("GET")
router.Handle("/api/{filename:.+\\.md}", handler)
// Test GET /api (list files)
req := httptest.NewRequest("GET", "/api", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
var response struct {
Files []string `json:"files"`
}
body, _ := io.ReadAll(w.Body)
assert.NoError(t, json.Unmarshal(body, &response))
// Verify only markdown files are returned
assert.Len(t, response.Files, 2)
assert.Contains(t, response.Files, "file1.md")
assert.Contains(t, response.Files, "file3.md")
assert.NotContains(t, response.Files, "file2.txt")
assert.NotContains(t, response.Files, "file4.log")
}
func TestFileListingEmptyDirectory(t *testing.T) {
dataDir, err := setupTestDir()
if err != nil {
t.Fatalf("Failed to create test dir: %v", err)
}
defer cleanupTestDir(dataDir)
log := logger.NewLogger()
handler := api.NewAPIHandler(dataDir, log)
router := mux.NewRouter()
router.Handle("/api", handler).Methods("GET")
router.Handle("/api/{filename:.+\\.md}", handler)
// Test GET /api (list files in empty directory)
req := httptest.NewRequest("GET", "/api", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
var response struct {
Files []string `json:"files"`
}
body, _ := io.ReadAll(w.Body)
assert.NoError(t, json.Unmarshal(body, &response))
// Verify empty array is returned
assert.Len(t, response.Files, 0)
}

23
frontend/.gitignore vendored Normal file
View File

@@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

19
frontend/Makefile Normal file
View File

@@ -0,0 +1,19 @@
.PHONY: test
test:
npm test
.PHONY: build
build:
npm run build
.PHONY: start
start:
npm start
.PHONY: clean
clean:
npm run clean

46
frontend/README.md Normal file
View File

@@ -0,0 +1,46 @@
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.\
You will also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you cant go back!**
If you arent satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point youre on your own.
You dont have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldnt feel obligated to use this feature. However we understand that this tool wouldnt be useful if you couldnt customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -1,13 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Markdown Editor</title>
<script type="module" crossorigin src="/assets/index-D8_kwvOB.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-DyDMOPN8.css">
</head>
<body>
<div id="root"></div>
</body>
</html>

View File

@@ -1,12 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Markdown Editor</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

11
frontend/jest.config.js Normal file
View File

@@ -0,0 +1,11 @@
module.exports = {
preset: 'ts-jest',
testEnvironment: 'jsdom',
transformIgnorePatterns: [
"node_modules/(?!(react-markdown|@mui)/)",
],
setupFilesAfterEnv: ['<rootDir>/src/setupTests.ts'],
moduleNameMapper: {
'\.(css|less|scss|sass)$': 'identity-obj-proxy',
},
};

22476
frontend/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,34 +1,54 @@
{ {
"name": "markdown-editor", "name": "frontend",
"private": true,
"version": "0.1.0", "version": "0.1.0",
"type": "module", "private": true,
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"test": "vitest run"
},
"dependencies": { "dependencies": {
"react": "^18.2.0", "@emotion/react": "^11.14.0",
"react-dom": "^18.2.0", "@emotion/styled": "^11.14.1",
"react-markdown": "^9.0.1", "@mui/icons-material": "^7.3.7",
"remark-gfm": "^4.0.0" "@mui/material": "^7.3.7",
"@mui/system": "^7.3.7",
"@testing-library/dom": "^10.4.1",
"@types/node": "^16.18.126",
"@types/react": "^19.2.13",
"@types/react-dom": "^19.2.3",
"react": "^19.2.4",
"react-dom": "^19.2.4",
"react-markdown": "^10.1.0",
"react-scripts": "5.0.1",
"typescript": "^4.9.5",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}, },
"devDependencies": { "devDependencies": {
"@tailwindcss/typography": "^0.5.19",
"@testing-library/jest-dom": "^6.9.1", "@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.2", "@testing-library/react": "^16.3.2",
"@types/react": "^18.2.0", "@testing-library/user-event": "^14.6.1",
"@types/react-dom": "^18.2.0", "@types/jest": "^30.0.0",
"@types/testing-library__jest-dom": "^5.14.9", "identity-obj-proxy": "^3.0.0",
"@vitejs/plugin-react": "^4.2.1", "ts-jest": "^29.4.6"
"autoprefixer": "^10.4.16",
"jsdom": "^28.0.0",
"postcss": "^8.4.31",
"tailwindcss": "^3.3.3",
"typescript": "^5.2.2",
"vite": "^5.0.10",
"vitest": "^1.6.1"
} }
} }

View File

@@ -1,6 +0,0 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}

BIN
frontend/public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

View File

@@ -0,0 +1,43 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

BIN
frontend/public/logo192.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

BIN
frontend/public/logo512.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

View File

@@ -0,0 +1,25 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

View File

@@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

38
frontend/src/App.css Normal file
View File

@@ -0,0 +1,38 @@
.App {
text-align: center;
}
.App-logo {
height: 40vmin;
pointer-events: none;
}
@media (prefers-reduced-motion: no-preference) {
.App-logo {
animation: App-logo-spin infinite 20s linear;
}
}
.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.App-link {
color: #61dafb;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}

View File

@@ -1,53 +1,168 @@
import { describe, it, expect, vi, beforeEach } from 'vitest' import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react' import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import App from './App' import App from './App';
// Mock react-markdown
jest.mock('react-markdown', () => () => <div>Preview</div>);
// Mock window.matchMedia
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation((query) => ({
matches: false,
media: query,
addListener: jest.fn(),
removeListener: jest.fn(),
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
onchange: null,
})),
});
// Mock fetch // Mock fetch
global.fetch = vi.fn(() => Promise.resolve({ global.fetch = jest.fn((input: RequestInfo | URL, init?: RequestInit) => {
ok: true, const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url;
json: () => Promise.resolve({ files: [] }), if (url.includes('/api/files') && !url.includes('/api/files/')) {
text: () => Promise.resolve(''), return Promise.resolve({
})) as any ok: true,
status: 200,
headers: new Headers(),
json: () => Promise.resolve({ files: ['test.md'] }),
} as Response);
}
return Promise.resolve({
ok: true,
status: 200,
headers: new Headers(),
json: () => Promise.resolve({}),
} as Response);
}) as jest.MockedFunction<typeof fetch>;
describe('App', () => { describe('App', () => {
beforeEach(() => { beforeEach(() => {
vi.clearAllMocks() jest.clearAllMocks();
}) });
it('renders the markdown editor', () => { test('renders markdown editor', () => {
render(<App />) render(<App />);
expect(screen.getByText('Markdown Editor')).toBeInTheDocument() expect(screen.getByText('Markdown Editor')).toBeInTheDocument();
}) });
it('displays theme selector', () => { test('lists files when fetched', async () => {
render(<App />) render(<App />);
expect(screen.getByText('System')).toBeInTheDocument()
expect(screen.getByText('Light')).toBeInTheDocument() // Wait for files to be fetched
expect(screen.getByText('Dark')).toBeInTheDocument() await waitFor(() => {
}) expect(screen.getByText('test.md')).toBeInTheDocument();
});
});
it('toggles theme', () => { test('opens file when clicked', async () => {
render(<App />) // Mock the file content fetch with a custom mock
const select = screen.getByRole('combobox') const mockFetch = jest.fn((input: RequestInfo | URL, init?: RequestInit) => {
fireEvent.change(select, { target: { value: 'dark' } }) const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url;
expect(select).toHaveValue('dark') if (url.includes('/api/files')) {
}) return Promise.resolve({
ok: true,
status: 200,
headers: new Headers(),
json: () => Promise.resolve({ files: ['test.md'] }),
} as Response);
}
if (url.includes('test.md')) {
return Promise.resolve({
ok: true,
status: 200,
headers: new Headers(),
json: () => Promise.resolve({ content: '# Test Content' }),
} as Response);
}
return Promise.resolve({
ok: true,
status: 200,
headers: new Headers(),
} as Response);
});
global.fetch = mockFetch;
it('displays files list', () => { render(<App />);
render(<App />)
expect(screen.getByText('Files')).toBeInTheDocument() // Wait for files to be fetched
expect(screen.getByText('New Document')).toBeInTheDocument() await waitFor(() => {
}) expect(screen.getByText('test.md')).toBeInTheDocument();
});
it('displays editor and preview', () => { // Click on the file
render(<App />) fireEvent.click(screen.getByText('test.md'));
expect(screen.getByText('Editor')).toBeInTheDocument()
expect(screen.getByText('Preview')).toBeInTheDocument() // Wait for the editor to appear
}) await waitFor(() => {
expect(screen.getByPlaceholderText('Write markdown here...')).toBeInTheDocument();
});
});
it('displays save button when file is selected', () => { test('creates new file', async () => {
render(<App />) // Mock the create file endpoint
expect(screen.queryByText('Save')).not.toBeInTheDocument() const mockFetch = jest.fn((input: RequestInfo | URL, init?: RequestInit) => {
// After selecting a file, save button should appear const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url;
}) if (url.includes('/api/files') && !init?.method) {
}) return Promise.resolve({
ok: true,
status: 200,
headers: new Headers(),
json: () => Promise.resolve({ files: [] }),
} as Response);
}
return Promise.resolve({
ok: true,
status: 200,
headers: new Headers(),
} as Response);
});
global.fetch = mockFetch;
render(<App />);
// Wait for initial fetch
await waitFor(() => {
expect(screen.getByLabelText('New filename')).toBeInTheDocument();
});
// Enter filename and content
const filenameInput = screen.getByLabelText('New filename');
const contentInput = screen.getByLabelText('Content');
fireEvent.change(filenameInput, { target: { value: 'newfile.md' } });
fireEvent.change(contentInput, { target: { value: '# New Content' } });
// Click create button
fireEvent.click(screen.getByText('Create File'));
// Verify fetch was called with POST
await waitFor(() => {
expect(mockFetch).toHaveBeenCalledWith('/api/files', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
filename: 'newfile.md',
content: '# New Content',
}),
});
});
});
test('changes theme', () => {
render(<App />);
const themeSelect = screen.getByLabelText('Theme');
expect(themeSelect).toBeInTheDocument();
// Change to dark theme
fireEvent.mouseDown(themeSelect);
fireEvent.click(screen.getByText('Dark'));
expect(themeSelect).toHaveValue('dark');
});
});

View File

@@ -1,184 +1,297 @@
import { useState, useEffect } from 'react' import React, { useState, useEffect } from 'react';
import { marked } from 'marked' import ReactMarkdown from 'react-markdown';
import ReactMarkdown from 'react-markdown' import { Box, Typography, TextField, Button, List, ListItem, ListItemText, IconButton, Divider, AppBar, Toolbar, Drawer, CssBaseline, ThemeProvider, createTheme, Select, MenuItem, FormControl, InputLabel, SelectChangeEvent } from '@mui/material';
import remarkGfm from 'remark-gfm' import { Delete, Add, Save, Menu as MenuIcon } from '@mui/icons-material';
interface FileInfo { interface FileItem {
name: string filename: string;
content: string content: string;
} }
const App = () => { const App: React.FC = () => {
const [files, setFiles] = useState<string[]>([]) const [files, setFiles] = useState<string[]>([]);
const [currentFile, setCurrentFile] = useState<string>('') const [currentFile, setCurrentFile] = useState<FileItem | null>(null);
const [markdownContent, setMarkdownContent] = useState<string>('') const [newFilename, setNewFilename] = useState('');
const [theme, setTheme] = useState<'dark' | 'light' | 'system'>('system') const [newContent, setNewContent] = useState('');
const [isDrawerOpen, setIsDrawerOpen] = useState(false);
const [themeMode, setThemeMode] = useState<'light' | 'dark' | 'system'>('system');
useEffect(() => { useEffect(() => {
loadFiles() fetchFiles();
applyTheme(theme) }, []);
}, [])
useEffect(() => { const fetchFiles = async () => {
if (currentFile) {
loadFile(currentFile)
}
}, [currentFile])
const applyTheme = (theme: 'dark' | 'light' | 'system') => {
if (theme === 'system') {
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
document.documentElement.classList.toggle('dark', prefersDark)
} else {
document.documentElement.classList.toggle('dark', theme === 'dark')
}
}
const loadFiles = async () => {
try { try {
const response = await fetch('/api') const response = await fetch('/api/files');
if (response.ok) { const data = await response.json();
const data = await response.json() setFiles(data.files || []);
setFiles(data.files || [])
}
} catch (error) { } catch (error) {
console.error('Error loading files:', error) console.error('Error fetching files:', error);
} }
} };
const loadFile = async (filename: string) => { const handleCreateFile = async () => {
try { if (!newFilename) return;
const response = await fetch(`/api/${filename}`)
if (response.ok) {
const content = await response.text()
setMarkdownContent(content)
}
} catch (error) {
console.error('Error loading file:', error)
}
}
const createFile = async (filename: string) => {
try { try {
await fetch(`/api/${filename}`, { const response = await fetch('/api/files', {
method: 'POST', method: 'POST',
body: '# New Document\n\nWrite your markdown here...', headers: {
}) 'Content-Type': 'application/json',
setCurrentFile(filename) },
await loadFiles() body: JSON.stringify({
} catch (error) { filename: newFilename,
console.error('Error creating file:', error) content: newContent,
} }),
} });
const saveFile = async (filename: string) => { if (response.ok) {
setNewFilename('');
setNewContent('');
fetchFiles();
}
} catch (error) {
console.error('Error creating file:', error);
}
};
const handleOpenFile = async (filename: string) => {
try { try {
await fetch(`/api/${filename}`, { const response = await fetch(`/api/files/${filename}`);
const data = await response.json();
setCurrentFile({
filename,
content: data.content,
});
setIsDrawerOpen(false);
} catch (error) {
console.error('Error opening file:', error);
}
};
const handleSaveFile = async () => {
if (!currentFile) return;
try {
const response = await fetch(`/api/files/${currentFile.filename}`, {
method: 'PUT', method: 'PUT',
body: markdownContent, headers: {
}) 'Content-Type': 'application/json',
} catch (error) { },
console.error('Error saving file:', error) body: JSON.stringify({
} content: currentFile.content,
} }),
});
const deleteFile = async (filename: string) => { if (response.ok) {
try { alert('File saved successfully!');
await fetch(`/api/${filename}`, { }
method: 'DELETE',
})
setCurrentFile('')
setMarkdownContent('')
await loadFiles()
} catch (error) { } catch (error) {
console.error('Error deleting file:', error) console.error('Error saving file:', error);
} }
} };
const handleDeleteFile = async (filename: string) => {
if (!window.confirm('Are you sure you want to delete this file?')) return;
try {
const response = await fetch(`/api/files/${filename}`, {
method: 'DELETE',
});
if (response.ok) {
fetchFiles();
if (currentFile?.filename === filename) {
setCurrentFile(null);
}
}
} catch (error) {
console.error('Error deleting file:', error);
}
};
const theme = createTheme({
palette: {
mode: themeMode === 'system' ? 'light' : themeMode,
},
});
const handleThemeChange = (event: SelectChangeEvent<'light' | 'dark' | 'system'>) => {
setThemeMode(event.target.value as 'light' | 'dark' | 'system');
};
return ( return (
<div className="min-h-screen bg-gray-50 dark:bg-gray-900"> <ThemeProvider theme={theme}>
<nav className="bg-blue-600 text-white p-4"> <CssBaseline />
<div className="container mx-auto flex justify-between items-center"> <Box sx={{ display: 'flex' }}>
<h1 className="text-xl font-bold">Markdown Editor</h1> <AppBar position="fixed" sx={{ zIndex: (theme) => theme.zIndex.drawer + 1 }}>
<div className="flex items-center space-x-4"> <Toolbar>
<select <IconButton color="inherit" aria-label="open drawer" edge="start" onClick={() => setIsDrawerOpen(true)} sx={{ mr: 2, display: { sm: 'none' } }}>
value={theme} <MenuIcon />
onChange={(e) => { </IconButton>
const newTheme = e.target.value as 'dark' | 'light' | 'system' <Typography variant="h6" noWrap component="div">
setTheme(newTheme) Markdown Editor
applyTheme(newTheme) </Typography>
}} <Box sx={{ ml: 'auto' }}>
className="bg-blue-700 text-white p-2 rounded" <FormControl size="small" sx={{ minWidth: 120 }}>
> <InputLabel id="theme-select-label">Theme</InputLabel>
<option value="system">System</option> <Select
<option value="light">Light</option> labelId="theme-select-label"
<option value="dark">Dark</option> id="theme-select"
</select> value={themeMode}
</div> label="Theme"
</div> onChange={handleThemeChange}
</nav> >
<MenuItem value="light">Light</MenuItem>
<MenuItem value="dark">Dark</MenuItem>
<MenuItem value="system">System</MenuItem>
</Select>
</FormControl>
</Box>
</Toolbar>
</AppBar>
<div className="container mx-auto p-4 flex flex-col lg:flex-row gap-4"> <Drawer
<div className="w-full lg:w-1/4 bg-white dark:bg-gray-800 rounded-lg shadow p-4"> variant="temporary"
<h2 className="text-lg font-semibold mb-4">Files</h2> open={isDrawerOpen}
<div className="space-y-2 mb-4"> onClose={() => setIsDrawerOpen(false)}
{files.map((file) => ( ModalProps={{ keepMounted: true }}
<div sx={{ display: { xs: 'block', sm: 'none' }, '& .MuiDrawer-paper': { boxSizing: 'border-box', width: 240 } }}
key={file} >
className={`p-2 rounded cursor-pointer ${currentFile === file ? 'bg-blue-100 dark:bg-blue-900' : 'hover:bg-gray-100 dark:hover:bg-gray-700'}`} <Box sx={{ overflow: 'auto' }}>
onClick={() => setCurrentFile(file)} <Typography variant="h6" sx={{ p: 2 }}>Files</Typography>
> <Divider />
{file} <List>
</div> {files.map((file) => (
))} <ListItem key={file} secondaryAction={
</div> <IconButton edge="end" onClick={(e) => {
<button e.stopPropagation();
onClick={() => createFile(`document-${Date.now()}.md`)} handleDeleteFile(file);
className="w-full bg-green-500 text-white p-2 rounded hover:bg-green-600" }}>
> <Delete />
New Document </IconButton>
</button> }>
</div> <ListItemText primary={file} onClick={() => handleOpenFile(file)} />
</ListItem>
<div className="flex-1 flex flex-col gap-4"> ))}
<div className="flex justify-between items-center"> </List>
{currentFile && ( <Divider />
<h2 className="text-lg font-semibold">{currentFile}</h2> <Box sx={{ p: 2 }}>
)} <TextField
{currentFile && ( label="New filename"
<button value={newFilename}
onClick={() => saveFile(currentFile)} onChange={(e) => setNewFilename(e.target.value)}
className="bg-blue-500 text-white p-2 rounded hover:bg-blue-600" fullWidth
> size="small"
Save sx={{ mb: 1 }}
</button>
)}
</div>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
<div className="bg-white dark:bg-gray-800 rounded-lg shadow p-4">
<h3 className="text-md font-medium mb-2">Editor</h3>
<textarea
value={markdownContent}
onChange={(e) => setMarkdownContent(e.target.value)}
className="w-full h-96 p-2 border rounded dark:bg-gray-900 dark:text-white dark:border-gray-700"
placeholder="Write markdown here..."
/> />
</div> <TextField
label="Content"
value={newContent}
onChange={(e) => setNewContent(e.target.value)}
fullWidth
multiline
rows={4}
size="small"
sx={{ mb: 1 }}
/>
<Button variant="contained" startIcon={<Add />} onClick={handleCreateFile} fullWidth>
Create File
</Button>
</Box>
</Box>
</Drawer>
<div className="bg-white dark:bg-gray-800 rounded-lg shadow p-4"> <Drawer
<h3 className="text-md font-medium mb-2">Preview</h3> variant="permanent"
<div className="w-full h-96 p-2 border rounded overflow-auto dark:bg-gray-900 dark:text-white dark:border-gray-700 prose dark:prose-invert"> sx={{ display: { xs: 'none', sm: 'block' }, '& .MuiDrawer-paper': { boxSizing: 'border-box', width: 240 } }}
<ReactMarkdown remarkPlugins={[remarkGfm]}> open
{markdownContent} >
</ReactMarkdown> <Box sx={{ overflow: 'auto' }}>
</div> <Typography variant="h6" sx={{ p: 2 }}>Files</Typography>
</div> <Divider />
</div> <List>
</div> {files.map((file) => (
</div> <ListItem key={file} secondaryAction={
</div> <IconButton edge="end" onClick={(e) => {
) e.stopPropagation();
} handleDeleteFile(file);
}}>
<Delete />
</IconButton>
}>
<ListItemText primary={file} onClick={() => handleOpenFile(file)} />
</ListItem>
))}
</List>
<Divider />
<Box sx={{ p: 2 }}>
<TextField
label="New filename"
value={newFilename}
onChange={(e) => setNewFilename(e.target.value)}
fullWidth
size="small"
sx={{ mb: 1 }}
/>
<TextField
label="Content"
value={newContent}
onChange={(e) => setNewContent(e.target.value)}
fullWidth
multiline
rows={4}
size="small"
sx={{ mb: 1 }}
/>
<Button variant="contained" startIcon={<Add />} onClick={handleCreateFile} fullWidth>
Create File
</Button>
</Box>
</Box>
</Drawer>
export default App <Box component="main" sx={{ flexGrow: 1, p: 3, mt: 9, display: { xs: 'block', sm: 'flex' } }}>
{currentFile ? (
<Box sx={{ width: '100%', display: 'flex', flexDirection: { xs: 'column', sm: 'row' }, gap: 2 }}>
<Box sx={{ flex: 1 }}>
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
<Typography variant="h6">{currentFile.filename}</Typography>
<Button variant="contained" startIcon={<Save />} onClick={handleSaveFile}>
Save
</Button>
</Box>
<TextField
value={currentFile.content}
onChange={(e) => setCurrentFile({ ...currentFile, content: e.target.value })}
fullWidth
multiline
rows={20}
variant="outlined"
placeholder="Write markdown here..."
/>
</Box>
<Box sx={{ flex: 1 }}>
<Typography variant="h6" sx={{ mb: 2 }}>Preview</Typography>
<Box sx={{ border: '1px solid', borderColor: 'grey.300', p: 2, borderRadius: 1, minHeight: '500px', overflow: 'auto' }}>
<ReactMarkdown>{currentFile.content}</ReactMarkdown>
</Box>
</Box>
</Box>
) : (
<Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%' }}>
<Typography variant="h5" gutterBottom>
No file selected
</Typography>
<Typography variant="body1" color="text.secondary">
Please select a file from the sidebar or create a new one
</Typography>
</Box>
)}
</Box>
</Box>
</ThemeProvider>
);
};
export default App;

View File

@@ -1,12 +1,13 @@
@tailwind base; body {
@tailwind components; margin: 0;
@tailwind utilities; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
@layer base { sans-serif;
html.dark { -webkit-font-smoothing: antialiased;
@apply bg-gray-900 text-white; -moz-osx-font-smoothing: grayscale;
} }
html.light {
@apply bg-white text-gray-900; code {
} font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
} }

17
frontend/src/index.tsx Normal file
View File

@@ -0,0 +1,17 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
reportWebVitals();

1
frontend/src/logo.svg Normal file
View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3"><g fill="#61DAFB"><path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/><circle cx="420.9" cy="296.5" r="45.7"/><path d="M520.5 78.1z"/></g></svg>

After

Width:  |  Height:  |  Size: 2.6 KiB

View File

@@ -1,10 +0,0 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import './index.css'
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<App />
</React.StrictMode>
)

1
frontend/src/react-app-env.d.ts vendored Normal file
View File

@@ -0,0 +1 @@
/// <reference types="react-scripts" />

View File

@@ -0,0 +1,15 @@
import { ReportHandler } from 'web-vitals';
const reportWebVitals = (onPerfEntry?: ReportHandler) => {
if (onPerfEntry && onPerfEntry instanceof Function) {
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
getCLS(onPerfEntry);
getFID(onPerfEntry);
getFCP(onPerfEntry);
getLCP(onPerfEntry);
getTTFB(onPerfEntry);
});
}
};
export default reportWebVitals;

View File

@@ -1,23 +1,2 @@
import { afterEach } from 'vitest' // Jest DOM extends jest's expectation methods with methods from testing-library/jest-dom
import { cleanup } from '@testing-library/react' import '@testing-library/jest-dom';
import * as matchers from '@testing-library/jest-dom/matchers'
// Extend expect with jest-dom matchers
expect.extend(matchers)
// Mock window.matchMedia
global.matchMedia = global.matchMedia || function() {
return {
matches: false,
addListener: function() {},
removeListener: function() {},
addEventListener: function() {},
removeEventListener: function() {},
dispatchEvent: function() {},
}
}
// Run cleanup after each test
afterEach(() => {
cleanup()
})

View File

@@ -1,35 +0,0 @@
/** @type {import('tailwindcss').Config} */
export default {
content: [
"./index.html",
"./src/**/*.{js,ts,jsx,tsx}",
],
darkMode: 'class',
theme: {
extend: {
typography: (theme) => ({
dark: {
css: {
'--tw-prose-body': theme('colors.gray.300'),
'--tw-prose-headings': theme('colors.white'),
'--tw-prose-links': theme('colors.blue.400'),
'--tw-prose-links-hover': theme('colors.blue.300'),
'--tw-prose-bold': theme('colors.white'),
'--tw-prose-counters': theme('colors.gray.400'),
'--tw-prose-bullets': theme('colors.gray.400'),
'--tw-prose-hr': theme('colors.gray.700'),
'--tw-prose-quotes': theme('colors.gray.200'),
'--tw-prose-quote-borders': theme('colors.gray.700'),
'--tw-prose-captions': theme('colors.gray.400'),
'--tw-prose-code': theme('colors.gray.200'),
'--tw-prose-pre-code': theme('colors.gray.200'),
'--tw-prose-pre-bg': theme('colors.gray.800'),
'--tw-prose-th-borders': theme('colors.gray.700'),
'--tw-prose-td-borders': theme('colors.gray.700'),
},
},
}),
},
},
plugins: [require('@tailwindcss/typography')],
}

26
frontend/tsconfig.json Normal file
View File

@@ -0,0 +1,26 @@
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": [
"src"
]
}

View File

@@ -1,20 +0,0 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
build: {
outDir: 'dist',
emptyOutDir: true,
},
server: {
port: 3000,
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
},
},
},
})

View File

@@ -1,11 +0,0 @@
import { defineConfig } from 'vitest/config'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
test: {
environment: 'jsdom',
globals: true,
setupFiles: './src/setupTests.ts',
},
})

Binary file not shown.

Before

Width:  |  Height:  |  Size: 210 KiB

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long