Author SHA1 Message Date
Daniel Samson ed7b30438e feat: add Docker Compose developer environment with Makefile shortcuts (M4)
- Root docker-compose.yml: backend (python:3.11-slim) + frontend
  (multi-stage node build -> nginx:alpine) on the newzy-network bridge
  network, frontend waits for the backend health check
- Persistent SQLite via bind mount ./data/db -> /app/data/db
- .env / .env.example documenting DATABASE_URL, DEBUG,
  BACKEND_CORS_ORIGINS and FRONTEND_API_URL
- Makefile: dev, stop, restart, build, logs, status, backend-start,
  frontend-start, test, e2e, shell-backend, shell-frontend, clean
- data/.gitignore keeps the data/ structure in git while excluding the
  database; root .gitignore drops the overly broad data/ rule and adds
  docker-compose.override.yml
- backend: .gitignore covers .env.*, Dockerfile sets unbuffered python
  and pre-creates the db volume dir; frontend: new .dockerignore
- README: full Docker setup docs (prerequisites, quick start, services,
  ports, network/storage, env vars, Makefile reference, troubleshooting)
2026-10-30 15:35:08 +00:00
Daniel Samson 9144411e0f fix: track frontend sample data hidden by overly broad data/ ignore rule
frontend/src/data/sample.ts (imported by Home/CategoriesPage) was never
committed because the root .gitignore ignored every path named data/.
A fresh clone would have failed the frontend build.
2026-10-30 15:34:50 +00:00
Daniel Samson 253052c551 Merge pull request 'feat: add React + TypeScript frontend with Vite, routing, tests and Docker setup' (#3) from feature/setup-frontend into develop
Reviewed-on: #3
2026-10-30 14:13:39 +00:00
Daniel Samson ffe19272b3 feat: add React + TypeScript frontend with Vite, routing, tests and Docker setup
M3 frontend infrastructure for the newzy news application:

- Vite + React 18 + TypeScript project (Node >=18) in frontend/
- React Router v6: BrowserRouter in App.tsx, routes for /, /articles,
  /articles/:id and /categories, Link/NavLink-based navigation
- lucide-react icons (Home, FileText, Settings, Search, ...) in the
  responsive Header (desktop + mobile menu) and article components
- Reusable components: ArticleCard, AuthorAvatar, CategoryBadge (CVA),
  Layout shell with backend API status indicator in the footer
- Typed API client (fetch wrapper, ApiError, endpoint helpers) with
  types matching the backend models; sample-data fallback until the
  backend article endpoints exist
- Tailwind CSS global/component styles, cn() helper (clsx + tailwind-merge)
- Unit tests: Vitest + React Testing Library (23 tests, 100% statement
  coverage on components)
- E2E tests: Playwright (9 tests) covering page shell, feed rendering,
  client-side navigation, article route and API interactions
- ESLint (react + react-hooks + typescript) configured and passing
- Multi-stage Dockerfile (Vite build -> Nginx) with SPA fallback and an
  /api/ proxy to the backend service; docker-compose frontend service on
  port 3000 in both frontend/ and the root docker-compose.yml
- README with setup, API documentation, testing and Docker instructions
2026-10-30 14:10:29 +00:00
Daniel Samson cbeac5e16b Merge pull request 'Feature/setup backend' (#1) from feature/setup-backend into develop
Reviewed-on: #1
2026-10-30 13:10:06 +00:00
55 changed files with 10601 additions and 11 deletions

No files matched your search

+31
View File
@@ -0,0 +1,31 @@
# newzy — environment variable template.
#
# Copy to `.env` and adjust as needed:
#
# cp .env.example .env
#
# `docker compose` in this directory reads `.env` automatically. `.env` is
# excluded from version control (see .gitignore) — never commit secrets.
# The backend's own defaults are documented in `backend/.env.example`.
# --- Database -------------------------------------------------------------
# SQLite database location (SQLAlchemy URL, relative to the backend's
# working directory). Inside the Docker image this resolves to
# /app/data/db/newzy.db, which is bind-mounted to ./data/db on the host.
DATABASE_URL=sqlite:///./data/db/newzy.db
# --- Backend ----------------------------------------------------------------
# Enable debug mode (verbose logs; keep off in production).
DEBUG=false
# Comma-separated list of origins the backend allows for CORS. The Docker
# frontend proxies /api (same-origin, no CORS needed); this mainly matters
# when developing the frontend directly on http://localhost:5173.
BACKEND_CORS_ORIGINS=http://localhost:3000,http://localhost:5173
# --- Frontend ----------------------------------------------------------------
# Base URL the frontend uses to reach the backend API.
# /api -> relative (recommended: the Vite dev server and the
# Docker Nginx config both proxy /api to the backend)
# http://host:port -> absolute (cross-origin; the origin must be listed in
# BACKEND_CORS_ORIGINS)
FRONTEND_API_URL=/api
+4 -2
View File
@@ -43,8 +43,10 @@ coverage/
.DS_Store
Thumbs.db
# Local data / uploads
data/
# Docker (local per-developer overrides; .dockerignore files are committed)
docker-compose.override.yml
# Local data / uploads (data/ is managed by data/.gitignore)
uploads/
*.sqlite
*.db
+60
View File
@@ -0,0 +1,60 @@
# newzy — development shortcuts (docker compose under the hood).
# Run `make help` (or just `make`) for the list of targets.
COMPOSE ?= docker compose
.DEFAULT_GOAL := help
.PHONY: help dev stop restart build logs status backend-start frontend-start \
test test-frontend test-backend e2e shell-backend shell-frontend clean
help: ## Show this help
@grep -E '^[a-zA-Z_-]+:.*?## ' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf " \033[36m%-15s\033[0m %s\n", $$1, $$2}'
dev: ## Build (if needed) and start both services in the background
$(COMPOSE) up -d --build
stop: ## Stop and remove containers (local data in ./data is kept)
$(COMPOSE) down
restart: ## Recreate and start both services
$(COMPOSE) down
$(COMPOSE) up -d --build
build: ## Rebuild all images from scratch (no cache)
$(COMPOSE) build --no-cache
logs: ## Follow the logs of both services
$(COMPOSE) logs -f backend frontend
status: ## Show the status of both services
$(COMPOSE) ps
backend-start: ## Build (if needed) and start the backend only
$(COMPOSE) up -d backend
frontend-start: ## Build (if needed) and start the frontend only
$(COMPOSE) up -d frontend
test: test-frontend test-backend ## Run all unit tests (frontend + backend)
test-frontend: ## Run frontend unit tests (requires Node.js 18+)
cd frontend && npm run test
test-backend: ## Run backend tests (uses backend/.venv if present, else system pytest)
cd backend && if [ -x .venv/bin/pytest ]; then .venv/bin/pytest; else pytest; fi
e2e: ## Run Playwright E2E tests (frontend/playwright; API calls are mocked)
cd frontend && npm run e2e
shell-backend: ## Open a shell inside the running backend container
$(COMPOSE) exec backend bash
shell-frontend: ## Open a shell inside the running frontend container
$(COMPOSE) exec frontend sh
clean: ## Stop everything; remove containers, volumes and local data
$(COMPOSE) down -v --remove-orphans
rm -rf data/
git checkout -- data/ 2>/dev/null || true
docker image prune -f
+115 -4
View File
@@ -8,15 +8,19 @@
| Milestone | Description | Status |
| --------- | ------------------------- | -------- |
| M1 | Git project setup | Done |
| M2 | Backend setup (FastAPI) | Done |
| M3+ | News application features | Planned |
| M1 | Git project setup | Done |
| M2 | Backend setup (FastAPI) | Done |
| M3 | Frontend setup (React + Vite) | Done |
| M4 | Developer environment (Docker) | Done |
| M5+ | News application features | Planned |
See [milestones/](milestones/) for milestone prompts and progress tracking.
## Requirements
No runtime requirements yet (setup-only milestone). When development of the application begins, the toolchain will be documented here.
- **Backend** ([`backend/`](backend/)): Python 3.11+, FastAPI (see [backend/README.md](backend/README.md))
- **Frontend** ([`frontend/`](frontend/)): Node.js 18+ (see [frontend/README.md](frontend/README.md))
- **Docker** (optional): for the containerized setup via the root [`docker-compose.yml`](docker-compose.yml)
## Getting Started
@@ -41,6 +45,113 @@ git push -u origin feature/<short-description>
Full contribution guidelines, including branching, merging, and rebase workflows, are in [CONTRIBUTING.md](CONTRIBUTING.md).
## Developer environment (Docker Compose)
The repository root ships a complete Docker Compose setup: one command starts
the FastAPI backend and the Nginx-served production frontend, with a
persistent SQLite database on the host.
### Prerequisites
- **Docker** (Docker Desktop or the docker engine + compose plugin v2), with the daemon running
- Optional (only for `make test` outside Docker): **Node.js 18+** and **Python 3.11+**
### Quick start
```bash
# 1. Configure the environment (defaults are fine for local development)
cp .env.example .env
# 2. Build (if needed) and start both services in the background
make dev
# 3. Open the application
# Frontend: http://localhost:3000
# Backend: http://localhost:8000 (Swagger docs: http://localhost:8000/api/v1/docs)
# 4. Stop everything (the database in ./data is kept)
make stop
```
### Services
| Service | Build context | Image base | What it does |
| ---------- | ------------- | ----------------- | -------------------------------------------------------- |
| `backend` | `./backend` | `python:3.11-slim`| FastAPI app (uvicorn), creates the SQLite schema on startup |
| `frontend` | `./frontend` | `node:20-alpine` → `nginx:1.27-alpine` (multi-stage) | Builds the Vite bundle, serves it via Nginx with SPA routing and an `/api` proxy to the backend |
### Port mappings
| Host port | Container | Service |
| --------- | --------- | -------- |
| `3000` | `80` | frontend (Nginx) |
| `8000` | `8000` | backend (uvicorn) |
### Networking and storage
- Both services share the bridge network `newzy-network` (subnet `172.28.0.0/16`),
so the frontend reaches the backend by service name (`http://backend:8000`).
- The SQLite database is stored on the host at [`data/db/newzy.db`](data/) via a
bind mount (`./data/db` → `/app/data/db`). It is excluded from version control
(see `data/.gitignore`) and survives `make stop`/`make restart`.
- `frontend` only starts once `backend` reports healthy (`/health`), so
`docker compose up` never serves a frontend with a dead API.
### Environment variables
`docker compose` reads [`.env`](.env) from the project root (template:
[`.env.example`](.env.example)). Never commit `.env` or real secrets.
| Variable | Description | Default | Required |
| --------------------- | ---------------------------------------- | --------------------------------------------------- | -------- |
| `DATABASE_URL` | SQLite database path (SQLAlchemy URL) | `sqlite:///./data/db/newzy.db` | Yes |
| `DEBUG` | Debug mode flag | `false` | No |
| `BACKEND_CORS_ORIGINS`| Comma-separated allowed CORS origins | `http://localhost:3000,http://localhost:5173` | No |
| `FRONTEND_API_URL` | Backend API base URL (relative or absolute) | `/api` | No |
### Makefile shortcuts
| Command | What it does |
| ---------------------- | ------------------------------------------------------- |
| `make dev` | Build (if needed) and start both services in the background |
| `make stop` | Stop and remove containers (data kept) |
| `make restart` | Recreate and start both services |
| `make build` | Rebuild all images from scratch |
| `make logs` | Follow logs of both services |
| `make status` | Show service status |
| `make backend-start` | Start the backend only |
| `make frontend-start` | Start the frontend only |
| `make test` | Run all unit tests (frontend vitest + backend pytest) |
| `make e2e` | Run Playwright E2E tests (API calls mocked) |
| `make shell-backend` | Open a shell in the backend container |
| `make shell-frontend` | Open a shell in the frontend container |
| `make clean` | Stop everything, remove containers, volumes and `data/` |
### Troubleshooting
- **Port already in use** (`bind: address already in use`): stop the other
process (`lsof -i :3000` / `lsof -i :8000`) or change the host port in
`docker-compose.yml` (e.g. `"3001:80"`).
- **Frontend starts but shows errors / 502 on API calls**: the backend is not
healthy yet — check `make logs backend`. The frontend waits for the backend
health check on startup; after a slow start, reload the page.
- **`docker compose` not found**: install the Compose v2 plugin
(`docker compose version` must print a version).
- **Database reset**: `make clean` removes `data/` (including the SQLite file);
tables are recreated on the next backend start.
- **Slow builds on first run**: the first `make dev` pulls the base images and
installs dependencies (~5 minutes). Subsequent builds use the Docker layer
cache and finish in seconds.
- **Ownership issues in `data/`** (e.g. after running Docker as root): restore
with `sudo chown -R $(id -un):$(id -gn) data/`.
- **Windows**: use WSL2 for best performance; **macOS**: allow Docker Desktop
sufficient disk space (50 GB+ recommended).
### Running without Docker
- Frontend: [`frontend/README.md`](frontend/README.md) — `npm run dev` (port 5173, proxies `/api` to :8000)
- Backend: [`backend/README.md`](backend/README.md) — `uvicorn main:app --reload` (port 8000)
## Documentation
- [CONTRIBUTING.md](CONTRIBUTING.md) — how to contribute
+3 -1
View File
@@ -3,8 +3,10 @@ __pycache__/
*.py[cod]
*.egg-info/
# Environment files
# Environment files (keep the committed template)
.env
.env.*
!.env.example
.venv/
venv/
+13 -3
View File
@@ -1,15 +1,25 @@
# newzy backend — FastAPI + SQLite.
# Orchestration lives in the repository root: docker-compose.yml.
FROM python:3.11-slim
# Unbuffered logs, no .pyc files in the image, no pip cache.
ENV PYTHONUNBUFFERED=1 \
PYTHONDONTWRITEBYTECODE=1 \
PIP_NO_CACHE_DIR=1
WORKDIR /app
# Install dependencies first to leverage Docker layer caching
# Install dependencies first to leverage Docker layer caching.
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy application code
# Copy application code (dev-only files excluded by .dockerignore).
COPY . .
# SQLite database lives on a mounted volume (see docker-compose.yml)
# The SQLite database lives on a bind-mounted volume (see docker-compose.yml);
# ensure the directory exists even before the volume is attached.
RUN mkdir -p /app/data/db
VOLUME /app/data/db
# Expose port
+6
View File
@@ -0,0 +1,6 @@
# Exclude everything under data/ from version control (SQLite database,
# uploads, ...) except the keep file below, so the directory structure
# (data/db/) survives a fresh clone.
*
!.gitignore
!keep_files.txt
+4
View File
@@ -0,0 +1,4 @@
# This file is tracked by git so the data/ directory structure (data/db/)
# is preserved in fresh clones. Everything else under data/ — the SQLite
# database (data/db/newzy.db), uploads, and other local state — is ignored
# by data/.gitignore and recreated at runtime.
+46 -1
View File
@@ -1,15 +1,60 @@
# newzy — full application stack (FastAPI backend + Nginx frontend).
#
# make dev # build (if needed) and start both services in the background
# make stop # stop and remove the containers (local data is kept)
# make clean # stop everything and remove containers, volumes and data/
#
# Environment variables are read from `.env` in this directory (template:
# `.env.example`). See README.md for the complete developer documentation.
#
# The `version` key is intentionally omitted: it is obsolete in Compose v2
# and only produces a deprecation warning.
services:
backend:
build: ./backend
build:
context: ./backend
dockerfile: Dockerfile
ports:
- "8000:8000"
volumes:
# Persistent SQLite database: ./data/db on the host -> /app/data/db
# inside the container (excluded from git, see data/.gitignore).
- ./data/db:/app/data/db
environment:
- DATABASE_URL=sqlite:///./data/db/newzy.db
- DEBUG=false
- BACKEND_CORS_ORIGINS=http://localhost:3000,http://localhost:5173
healthcheck:
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"]
interval: 30s
timeout: 5s
retries: 3
start_period: 10s
networks:
- newzy-network
restart: unless-stopped
frontend:
build:
context: ./frontend
dockerfile: Dockerfile
ports:
- "3000:80"
depends_on:
backend:
condition: service_healthy
networks:
- newzy-network
restart: unless-stopped
networks:
newzy-network:
driver: bridge
ipam:
config:
- subnet: 172.28.0.0/16
volumes:
db-data:
name: newzy-db-data
+18
View File
@@ -0,0 +1,18 @@
# Keep the image small: exclude dev-only files from the build context.
node_modules/
dist/
coverage/
test-results/
playwright-report/
playwright/.cache/
.env
.env.*
!.env.example
.git/
.gitignore
Dockerfile
.dockerignore
docker-compose.yml
README.md
*.log
.DS_Store
+56
View File
@@ -0,0 +1,56 @@
/* ESLint configuration for the newzy frontend.
*
* Covers:
* - core ESLint recommended rules
* - TypeScript (@typescript-eslint recommended)
* - React (eslint-plugin-react recommended)
* - React Hooks (eslint-plugin-react-hooks)
*
* React Router best practices are enforced by convention + review (see
* README.md):
* - use react-router-dom <Link>/<NavLink> for in-app navigation (never
* plain <a> tags) so navigation stays client-side
* - use useParams/useSearchParams for dynamic segments
* - route definitions live in src/App.tsx only
*/
module.exports = {
root: true,
env: {
browser: true,
es2022: true,
node: true,
},
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
ecmaFeatures: { jsx: true },
},
plugins: ['@typescript-eslint', 'react', 'react-hooks'],
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:react/recommended',
'plugin:react-hooks/recommended',
],
settings: {
react: { version: 'detect' },
},
rules: {
// TypeScript provides prop typing — no need for JS prop types.
'react/prop-types': 'off',
// React 17+ JSX transform — no need to import React for JSX.
'react/react-in-jsx-scope': 'off',
// Router navigation must never open new tabs by accident.
'react/jsx-no-target-blank': 'error',
'@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
},
ignorePatterns: [
'dist/',
'node_modules/',
'coverage/',
'playwright-report/',
'test-results/',
'playwright/.cache/',
],
};
+42
View File
@@ -0,0 +1,42 @@
# Dependencies
node_modules/
.pnp
.pnp.js
# Builds / output
dist/
build/
out/
# Environment files (never commit secrets)
.env
.env.*
!.env.example
# Testing artifacts
coverage/
.nyc_output/
playwright-report/
test-results/
playwright/.cache/
# Logs
logs/
*.log
npm-debug.log*
yarn-debug.log*
pnpm-debug.log*
# Editor / IDE
.idea/
.vscode/
*.swp
*.swo
*~
.project
.classpath
.settings/
# OS files
.DS_Store
Thumbs.db
+32
View File
@@ -0,0 +1,32 @@
# syntax=docker/dockerfile:1
# --- Stage 1: build the production bundle ---------------------------------
FROM node:20-alpine AS build
WORKDIR /app
# Install dependencies first to leverage Docker layer caching.
COPY package.json package-lock.json ./
RUN npm ci
# Copy application source and build.
COPY . .
ARG VITE_API_BASE_URL=/api/v1
ENV VITE_API_BASE_URL=$VITE_API_BASE_URL
RUN npm run build
# --- Stage 2: serve static files with Nginx --------------------------------
FROM nginx:1.27-alpine
# SPA + API proxy configuration (proxies /api/ to the backend service).
COPY nginx.conf /etc/nginx/conf.d/default.conf
# Production bundle from the build stage.
COPY --from=build /app/dist /usr/share/nginx/html
EXPOSE 80
HEALTHCHECK --interval=30s --timeout=5s --retries=3 \
CMD wget -qO- http://localhost/ >/dev/null 2>&1 || exit 1
CMD ["nginx", "-g", "daemon off;"]
+240
View File
@@ -0,0 +1,240 @@
# newzy — Frontend
React + TypeScript frontend for the **newzy** news web application, built with
[Vite](https://vitejs.dev/), styled with [Tailwind CSS](https://tailwindcss.com/),
icons from [lucide-react](https://lucide.dev/), client-side routing via
[React Router v6](https://reactrouter.com/), unit-tested with
[Vitest](https://vitest.dev/) + React Testing Library, and E2E-tested with
[Playwright](https://playwright.dev/).
> Infrastructure milestone (M3): project structure, routing, types, reusable
> components, API client and testing setup. Complex UI features arrive in
> later milestones.
## Requirements
- **Node.js 18 or later** (Node 20+ recommended)
- npm 9+ (ships with Node 20)
- Optional: a running [backend](../backend/) on `http://localhost:8000`
(the UI falls back to sample data when the API is unavailable)
## Getting started
```bash
# 1. Install dependencies
npm install
# 2. Start the dev server (http://localhost:5173)
npm run dev
```
The Vite dev server proxies `/api` to `http://localhost:8000`, so no CORS
configuration is needed during development.
## Scripts
| Script | Description |
| --------------------- | -------------------------------------------------------- |
| `npm run dev` | Start the Vite dev server with HMR on port 5173 |
| `npm run build` | Type-check (`tsc`) and build the production bundle to `dist/` |
| `npm run preview` | Serve the production build locally (port 4173) |
| `npm test` | Run unit tests once (Vitest) |
| `npm run test:watch` | Run unit tests in watch mode |
| `npm run test:coverage` | Run unit tests with coverage report |
| `npm run e2e` | Build the app and run Playwright E2E tests |
| `npm run e2e:ui` | Run Playwright E2E tests in the interactive UI |
| `npm run lint` | Lint the codebase with ESLint |
## Project structure
```
frontend/
├── index.html # Vite entry HTML (must live at the project root)
├── public/ # Static assets served as-is (favicon, robots.txt)
├── src/
│ ├── assets/
│ │ ├── logo.svg # Brand logo (placeholder)
│ │ └── styles/globals.css # Tailwind + global/component styles
│ ├── components/
│ │ ├── ui/ # Generic UI (lucide icons + router links)
│ │ │ ├── Header.tsx # Navigation header (desktop + mobile menu)
│ │ │ └── Layout.tsx # Page shell: header, <main>, footer, API status
│ │ └── articles/ # Domain-specific components
│ │ ├── ArticleCard.tsx # Article preview (thumb, title, author, badge)
│ │ ├── AuthorAvatar.tsx # Initials/profile image with name tooltip
│ │ └── CategoryBadge.tsx # Color-coded category pill (CVA variants)
│ ├── pages/ # Page-level components (one per route)
│ │ ├── Home.tsx # Featured article, search bar, article grid
│ │ ├── ArticlePage.tsx # /articles and /articles/:id placeholders
│ │ └── CategoriesPage.tsx # /categories listing placeholder
│ ├── api/
│ │ └── client.ts # Typed fetch wrapper + endpoint helpers
│ ├── data/
│ │ └── sample.ts # Sample feed (fallback until backend endpoints exist)
│ ├── lib/
│ │ └── utils.ts # cn() — clsx + tailwind-merge helper
│ ├── types/
│ │ └── index.ts # Article / Author / Category / API types
│ ├── tests/ # Unit tests (Vitest + React Testing Library)
│ │ ├── Header.test.tsx
│ │ ├── ArticleCard.test.tsx
│ │ ├── Layout.test.tsx
│ │ └── components/
│ ├── App.tsx # BrowserRouter + route definitions
│ └── main.tsx # React entry point
├── playwright/
│ └── e2e/ # Playwright E2E tests
│ ├── home.spec.ts # Shell, feed rendering, client-side navigation
│ └── api.spec.ts # API interactions (mocked endpoints)
├── Dockerfile # Multi-stage build: Vite build -> Nginx
├── nginx.conf # SPA fallback + /api/ proxy to the backend
├── docker-compose.yml # Standalone frontend (+backend) service config
├── vite.config.ts # Dev server (5173), /api proxy, build output
├── vitest.config.ts # Unit test config (jsdom)
├── playwright.config.ts # E2E config (chromium, vite preview webServer)
└── tailwind.config.js # Tailwind content scan + theme
```
### pages/ vs components/
- **`src/pages/`** — one component per route; owns page-level state and is
imported only by the router in `App.tsx`.
- **`src/components/`** — reusable UI. `ui/` holds generic building blocks
(header, layout) with lucide icons; `articles/` holds domain components.
## Routing (React Router v6)
Routes are defined in [`src/App.tsx`](src/App.tsx) with `BrowserRouter` at the
root. In-app navigation always uses `<Link>`/`<NavLink>` from
`react-router-dom` — **never plain anchor tags** — so navigation stays
client-side without page reloads.
| Path | Page component | Notes |
| -------------- | ------------------ | -------------------------------------- |
| `/` | `Home` | Feed, featured article, search bar |
| `/articles` | `ArticlePage` | "All articles" placeholder |
| `/articles/:id`| `ArticlePage` | Single article placeholder (`useParams`) |
| `/categories` | `CategoriesPage` | Category listing placeholder |
| `*` | `NotFound` (404) | Fallback route |
## API client
[`src/api/client.ts`](src/api/client.ts) wraps `fetch`:
- Base URL: `/api/v1` (override with the `VITE_API_BASE_URL` env var).
- Sends `Accept: application/json`; JSON-serializes request bodies.
- Non-2xx responses throw `ApiError` with the backend's standardized error
envelope (`{ detail, code, errors? }`).
- Typed endpoint helpers: `getHealth()`, `getVersion()`, `getArticles()`
(backend snake_case payloads are mapped onto the camelCase types in
`src/types/`).
### Backend endpoints (M2)
| Method | Path | Description |
| ------ | ---------------- | ------------------------------------ |
| GET | `/health` | Root liveness probe |
| GET | `/api/v1/health` | Service health (`status`, `version`) |
| GET | `/api/v1/version`| Application name and version |
Article/author/category endpoints are planned for a later backend milestone;
until then the home page renders the sample feed from
`src/data/sample.ts` (clearly labelled in the UI).
### How `/api` resolves per environment
| Environment | Mechanism |
| ------------------ | ---------------------------------------------------------------- |
| Dev (`npm run dev`) | Vite dev server proxies `/api` → `http://localhost:8000` |
| Preview (`npm run preview`) | Same proxy (used by the Playwright webServer) |
| Docker (compose) | Nginx `location /api/` proxies to the `backend:8000` service |
## Testing
### Unit tests (Vitest + React Testing Library)
Located in `src/tests/`. Run with `npm test`.
- `Header.test.tsx` — brand, router links, lucide icons, active state, mobile menu
- `ArticleCard.test.tsx` — data rendering, links, fallbacks, read time
- `Layout.test.tsx` — shell structure, API status indicator (mocked `getHealth`)
- `components/` — `CategoryBadge` variants, `AuthorAvatar` initials/image
Components that use the router are rendered through the `renderWithRouter`
helper (`src/tests/utils.tsx`), which wraps them in a `MemoryRouter`.
### E2E tests (Playwright)
Located in `playwright/e2e/`. Run with `npm run e2e` (builds the app first and
serves it via `vite preview` on port 4173).
- `home.spec.ts` — page shell, feed rendering with data, client-side
navigation between pages (asserts no full page reloads), article detail
route, console/page-error hygiene
- `api.spec.ts` — health request on load, rendering API-provided articles,
sample-data fallback when the API is down, 404 error-envelope handling.
Endpoints are mocked with `page.route`, so the tests are deterministic
without a running backend.
Install browsers after a fresh clone:
```bash
npx playwright install chromium
```
## Docker
Multi-stage [`Dockerfile`](Dockerfile): `node:20-alpine` builds the production
bundle; `nginx:1.27-alpine` serves it with SPA fallback and an `/api/` proxy
to the `backend` service (see [`nginx.conf`](nginx.conf)).
```bash
# From this directory (standalone: frontend + backend)
docker compose up --build
# Or from the repository root (full orchestration)
docker compose up --build
```
The app is served on <http://localhost:3000>.
## Environment variables
| Variable | Default | Description |
| --------------------- | --------- | ------------------------------------ |
| `VITE_API_BASE_URL` | `/api/v1` | API base URL baked in at build time |
No secrets are required on the client side; authentication and credentials
are handled by the backend in future milestones.
## Icons (lucide-react)
Icons are imported from `lucide-react` (SVG-based, no font downloads) and are
always decorative — paired with a text label or `aria-label`, and marked
`aria-hidden="true"`:
| Icon | Where used |
| ----------------- | ------------------------------------------------- |
| `Home` | Header — "Home" nav item |
| `FileText` | Header — "Articles" nav item; article thumbnail |
| `Settings` | Header — "Categories" nav item |
| `Search` | Home — search bar |
| `Menu` / `X` | Header — mobile menu toggle |
| `Clock` | ArticleCard / hero — read time |
| `ArrowRight` | Hero — "Read article" call to action |
| `ArrowLeft` | ArticlePage — back links |
| `Info` | Home — sample-data notice |
| `FolderOpen` | CategoriesPage — category cards |
Browse all available icons at <https://lucide.dev/icons>.
## Troubleshooting
- **Port 5173 already in use** — Vite picks the next free port; use
`npm run dev -- --strictPort` to fail instead.
- **E2E fails with "browser not found"** — run `npx playwright install
chromium` (add `--with-deps` on distros where you have root/sudo access).
- **"API: offline" in the footer** — the backend is not running on
`http://localhost:8000`; expected when only the frontend is up.
- **Sample data notice on the home page** — the backend does not implement
`GET /api/v1/articles` yet (planned milestone); the fallback is intentional.
+32
View File
@@ -0,0 +1,32 @@
# Standalone frontend service (the full application orchestration lives in
# the repository root `docker-compose.yml`).
#
# docker compose up --build
#
# Frontend: http://localhost:3000 (Nginx proxies /api to the backend).
# Backend: http://localhost:8000 (Swagger docs at /api/v1/docs).
services:
frontend:
build: .
ports:
- "3000:80"
depends_on:
backend:
condition: service_healthy
restart: unless-stopped
# Included so this compose file works on its own (mirrors the root file).
backend:
build: ../backend
ports:
- "8000:8000"
volumes:
- ../data/db:/app/data/db
environment:
- DATABASE_URL=sqlite:///./data/db/newzy.db
healthcheck:
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"]
interval: 30s
timeout: 5s
retries: 3
restart: unless-stopped
+17
View File
@@ -0,0 +1,17 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta
name="description"
content="newzy — a news web application for discovering, reading, and managing news content."
/>
<title>newzy — Your news, curated</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+45
View File
@@ -0,0 +1,45 @@
# newzy frontend — Nginx configuration (Docker).
#
# Serves the Vite production build as a single-page app and proxies API
# calls to the backend service so the browser can use relative /api URLs
# (no CORS needed from within the compose network).
server {
listen 80;
server_name _;
root /usr/share/nginx/html;
index index.html;
# Reasonable defaults for static content.
sendfile on;
gzip on;
gzip_types text/css application/javascript application/json image/svg+xml;
# Hashed build assets can be cached aggressively.
location /assets/ {
expires 1y;
add_header Cache-Control "public, immutable";
}
# Docker's built-in DNS. The upstream is resolved at request time (via a
# variable) instead of at startup, so nginx still boots when the backend
# service is not yet available (requests then fail with 502 instead).
resolver 127.0.0.11 valid=30s ipv6=off;
# Proxy API calls to the FastAPI backend service.
location /api/ {
set $api_upstream "http://backend:8000";
proxy_pass $api_upstream;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# SPA fallback: unknown paths are handled by React Router.
location / {
try_files $uri $uri/ /index.html;
}
}
+7596
View File
File diff suppressed because it is too large. Load diff
+53
View File
@@ -0,0 +1,53 @@
{
"name": "newzy-frontend",
"private": true,
"version": "0.1.0",
"type": "module",
"description": "Frontend for the newzy news web application — React + TypeScript + Vite.",
"license": "MIT",
"engines": {
"node": ">=18"
},
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview",
"test": "vitest run",
"test:watch": "vitest",
"test:coverage": "vitest run --coverage",
"e2e": "playwright test",
"e2e:ui": "playwright test --ui",
"lint": "eslint . --ext .js,.jsx,.ts,.tsx"
},
"dependencies": {
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.0",
"lucide-react": "^0.263.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.20.0",
"tailwind-merge": "^2.1.0"
},
"devDependencies": {
"@playwright/test": "^1.39.0",
"@testing-library/dom": "^9.3.4",
"@testing-library/jest-dom": "^6.4.2",
"@testing-library/react": "^14.2.0",
"@types/react": "^18.2.0",
"@types/react-dom": "^18.2.0",
"@typescript-eslint/eslint-plugin": "^6.21.0",
"@typescript-eslint/parser": "^6.21.0",
"@vitejs/plugin-react": "^4.2.0",
"@vitest/coverage-v8": "^0.34.0",
"autoprefixer": "^10.4.16",
"eslint": "^8.57.0",
"eslint-plugin-react": "^7.34.0",
"eslint-plugin-react-hooks": "^4.6.0",
"jsdom": "^24.0.0",
"postcss": "^8.4.32",
"tailwindcss": "^3.4.0",
"typescript": "~5.4.2",
"vite": "^4.4.0",
"vitest": "^0.34.0"
}
}
+30
View File
@@ -0,0 +1,30 @@
import { defineConfig, devices } from '@playwright/test';
// https://playwright.dev/docs/test-configuration
export default defineConfig({
testDir: './playwright/e2e',
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 1 : undefined,
reporter: process.env.CI ? 'github' : 'list',
timeout: 30_000,
use: {
baseURL: 'http://localhost:4173',
trace: 'on-first-retry',
screenshot: 'only-on-failure',
},
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
},
],
webServer: {
// Serve the production build (vite preview) with the /api proxy enabled.
command: 'npm run build && npm run preview -- --strictPort',
url: 'http://localhost:4173',
reuseExistingServer: !process.env.CI,
timeout: 120_000,
},
});
+109
View File
@@ -0,0 +1,109 @@
import { expect, test, type Page } from '@playwright/test';
const HEALTH_OK = { status: 'ok', version: '0.1.0' };
const API_ARTICLE = {
id: 100,
title: 'Live API Article',
content: 'This story was served by the (mocked) newzy backend API. '.repeat(20),
author_id: 7,
category_id: 1,
created_at: '2025-06-01T08:00:00Z',
published: true,
author: {
id: 7,
name: 'Ada Lovelace',
email: 'ada@example.com',
bio: null,
},
category: { id: 1, name: 'Technology', slug: 'technology' },
};
/** Mock the health endpoint so tests do not depend on a running backend. */
async function mockHealth(page: Page): Promise<void> {
await page.route('**/api/v1/health', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(HEALTH_OK),
}),
);
}
/**
* API interactions: verifies the app talks to the backend through the
* typed client (base URL /api/v1, JSON accept header) and reflects the
* responses in the UI.
*/
test.describe('api interactions', () => {
test('requests the backend health endpoint on load and reports it online', async ({
page,
}) => {
await mockHealth(page);
const healthRequest = page.waitForRequest(
(request) => request.url().includes('/api/v1/health') && request.method() === 'GET',
);
await page.goto('/');
const request = await healthRequest;
expect(request.headers()['accept']).toBe('application/json');
await expect(page.getByTestId('api-status')).toHaveText(/api:\s*online/i);
});
test('renders articles returned by the API', async ({ page }) => {
await mockHealth(page);
await page.route('**/api/v1/articles', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify([API_ARTICLE]),
}),
);
await page.goto('/');
// The API article replaces the sample feed.
const cards = page.getByTestId('article-card');
await expect(cards).toHaveCount(1);
await expect(cards.first()).toContainText('Live API Article');
await expect(cards.first()).toContainText('Ada Lovelace');
await expect(cards.first()).toContainText('Technology');
// Sample-data fallback note is hidden when real data is present.
await expect(page.getByTestId('sample-data-note')).toHaveCount(0);
});
test('falls back to sample data and reports the API as offline', async ({ page }) => {
// Block every API call to simulate the backend being down.
await page.route('**/api/v1/**', (route) => route.abort());
await page.goto('/');
await expect(page.getByTestId('sample-data-note')).toBeVisible();
await expect(page.getByTestId('article-card').first()).toBeVisible();
await expect(page.getByTestId('api-status')).toHaveText(/api:\s*offline/i);
});
test('survives API error responses (non-2xx envelope)', async ({ page }) => {
await mockHealth(page);
await page.route('**/api/v1/articles', (route) =>
route.fulfill({
status: 404,
contentType: 'application/json',
body: JSON.stringify({ detail: 'Not Found', code: 'not_found' }),
}),
);
const pageErrors: string[] = [];
page.on('pageerror', (error) => pageErrors.push(error.message));
await page.goto('/');
// 404 from the articles endpoint -> graceful sample-data fallback.
await expect(page.getByTestId('sample-data-note')).toBeVisible();
await expect(page.getByTestId('article-card').first()).toBeVisible();
expect(pageErrors).toEqual([]);
});
});
+114
View File
@@ -0,0 +1,114 @@
import { expect, test } from '@playwright/test';
/**
* Homepage flows: page shell, article feed, and client-side navigation
* between pages via React Router links (no full page reloads).
*/
test.describe('home page', () => {
test('renders the page shell, branding and navigation', async ({ page }) => {
await page.goto('/');
await expect(page).toHaveTitle(/newzy/i);
// Layout structure: header, main content, footer.
await expect(page.getByRole('banner')).toBeVisible();
await expect(page.getByRole('main')).toBeVisible();
await expect(page.getByRole('contentinfo')).toBeVisible();
// Brand links to home.
await expect(page.getByRole('link', { name: 'newzy' })).toHaveAttribute('href', '/');
// Primary navigation uses React Router links.
const nav = page.getByRole('navigation', { name: 'Main navigation' });
await expect(nav.getByRole('link', { name: /home/i })).toHaveAttribute('href', '/');
await expect(nav.getByRole('link', { name: /articles/i })).toHaveAttribute(
'href',
'/articles',
);
await expect(nav.getByRole('link', { name: /categories/i })).toHaveAttribute(
'href',
'/categories',
);
});
test('renders the featured article and article grid with data', async ({ page }) => {
await page.goto('/');
// Hero with the featured article.
const featured = page.getByRole('region', { name: 'Featured article' });
await expect(featured).toBeVisible();
await expect(featured.getByRole('heading', { level: 1 })).toContainText(
'Inside the new wave of open-source language models',
);
// Article grid rendered from data (sample feed while the backend article
// endpoints are not available yet).
const cards = page.getByTestId('article-card');
await expect(cards.first()).toBeVisible();
expect(await cards.count()).toBeGreaterThanOrEqual(5);
await expect(page.getByTestId('sample-data-note')).toBeVisible();
});
test('navigates between pages via router links without a full page reload', async ({
page,
}) => {
const loadEvents: string[] = [];
page.on('load', () => loadEvents.push(page.url()));
await page.goto('/');
const nav = page.getByRole('navigation', { name: 'Main navigation' });
// Home -> Articles
await nav.getByRole('link', { name: /articles/i }).click();
await expect(page).toHaveURL(/\/articles$/);
await expect(
page.getByRole('heading', { level: 1, name: 'Articles' }),
).toBeVisible();
// Articles -> Categories
await nav.getByRole('link', { name: /categories/i }).click();
await expect(page).toHaveURL(/\/categories$/);
await expect(
page.getByRole('heading', { level: 1, name: 'Categories' }),
).toBeVisible();
// Categories -> Home
await nav.getByRole('link', { name: /home/i }).click();
await expect(page).toHaveURL(/\/$/);
// Only the initial goto fired a document load — the rest was
// client-side React Router navigation.
expect(loadEvents).toHaveLength(1);
});
test('opens an article detail placeholder from a card', async ({ page }) => {
await page.goto('/');
const firstCard = page.getByTestId('article-card').first();
await firstCard.getByRole('link').first().click();
await expect(page).toHaveURL(/\/articles\/\d+$/);
await expect(page.getByRole('heading', { level: 1 })).toContainText('Article #');
});
test('has no unexpected console errors or uncaught page errors', async ({ page }) => {
const consoleErrors: string[] = [];
const pageErrors: string[] = [];
page.on('console', (message) => {
if (message.type() === 'error') consoleErrors.push(message.text());
});
page.on('pageerror', (error) => pageErrors.push(error.message));
await page.goto('/');
await expect(page.getByTestId('article-card').first()).toBeVisible();
// Uncaught exceptions are never acceptable.
expect(pageErrors).toEqual([]);
// Expected noise: the article feed fetch 404s/502s when the backend
// article endpoints are unavailable (the UI falls back to sample data).
const unexpected = consoleErrors.filter(
(text) => !/failed to load resource|net::err/i.test(text),
);
expect(unexpected).toEqual([]);
});
});
+6
View File
@@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
+8
View File
@@ -0,0 +1,8 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" fill="none" role="img" aria-label="newzy logo">
<rect width="32" height="32" rx="7" fill="#2563eb"/>
<rect x="7" y="8" width="18" height="4" rx="1.2" fill="#ffffff"/>
<rect x="7" y="15" width="8" height="9" rx="1.2" fill="#bfdbfe"/>
<rect x="17.5" y="15" width="7.5" height="2" rx="1" fill="#ffffff"/>
<rect x="17.5" y="19" width="7.5" height="2" rx="1" fill="#ffffff"/>
<rect x="17.5" y="23" width="5" height="2" rx="1" fill="#ffffff"/>
</svg>

After

Width:  |  Height:  |  Size: 517 B

+2
View File
@@ -0,0 +1,2 @@
User-agent: *
Allow: /
+48
View File
@@ -0,0 +1,48 @@
import { BrowserRouter, Link, Route, Routes } from 'react-router-dom';
import Layout from './components/ui/Layout';
import ArticlePage from './pages/ArticlePage';
import CategoriesPage from './pages/CategoriesPage';
import Home from './pages/Home';
/** 404 fallback for unknown routes. */
function NotFound() {
return (
<div className="container-page text-center">
<h1 className="mb-2 text-5xl font-bold text-slate-900">404</h1>
<p className="mb-6 text-sm text-slate-600">
That page could not be found. It may have moved, or the link may be broken.
</p>
<Link to="/" className="btn">
Back to home
</Link>
</div>
);
}
/**
* Root component: owns the React Router setup.
*
* BrowserRouter wraps the whole app; Layout provides the shared shell
* (header/footer); Routes maps URLs to page components in src/pages/.
* In-app navigation always uses react-router-dom <Link>/<NavLink>.
*/
export default function App() {
return (
<BrowserRouter
future={{
v7_startTransition: true,
v7_relativeSplatPath: true,
}}
>
<Layout>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/articles" element={<ArticlePage />} />
<Route path="/articles/:id" element={<ArticlePage />} />
<Route path="/categories" element={<CategoriesPage />} />
<Route path="*" element={<NotFound />} />
</Routes>
</Layout>
</BrowserRouter>
);
}
+172
View File
@@ -0,0 +1,172 @@
/**
* Typed API client for the newzy backend.
*
* - Base URL: `/api/v1` by default (overridable via `VITE_API_BASE_URL`).
* In development the Vite dev server proxies `/api` to
* `http://localhost:8000` (see `vite.config.ts`); in Docker the Nginx
* container proxies `/api/` to the `backend` service (see `nginx.conf`).
* - All non-2xx responses throw `ApiError` carrying the backend's
* standardized error envelope (`{ detail, code, errors? }`).
*/
import type {
ApiErrorPayload,
Article,
Author,
Category,
HealthResponse,
VersionResponse,
} from '../types';
export const API_BASE_URL: string =
(import.meta.env.VITE_API_BASE_URL as string | undefined) ?? '/api/v1';
/** Error thrown for failed API requests (network or non-2xx responses). */
export class ApiError extends Error {
readonly status: number;
readonly code?: string;
constructor(status: number, message: string, code?: string) {
super(message);
this.name = 'ApiError';
this.status = status;
this.code = code;
}
}
interface RequestOptions extends Omit<RequestInit, 'body'> {
/** JSON-serializable request body (stringified automatically). */
body?: unknown;
}
/**
* Low-level fetch wrapper: prepends the base URL, sends JSON, parses the
* response and converts failures into `ApiError`.
*/
async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {
const { body, headers, ...rest } = options;
let response: Response;
try {
response = await fetch(`${API_BASE_URL}${path}`, {
...rest,
headers: {
Accept: 'application/json',
...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),
...headers,
},
body: body !== undefined ? JSON.stringify(body) : undefined,
});
} catch {
throw new ApiError(0, 'Network error: unable to reach the newzy API.', 'network_error');
}
if (!response.ok) {
let payload: ApiErrorPayload | null = null;
try {
payload = (await response.json()) as ApiErrorPayload;
} catch {
// Non-JSON error body — fall back to the status line.
}
throw new ApiError(
response.status,
payload?.detail ?? `Request to ${path} failed with status ${response.status}.`,
payload?.code,
);
}
if (response.status === 204) {
return undefined as T;
}
return (await response.json()) as T;
}
/** Type-safe request helpers. */
export const api = {
get: <T>(path: string, init?: RequestOptions) => request<T>(path, init),
post: <T>(path: string, body: unknown, init?: RequestOptions) =>
request<T>(path, { ...init, method: 'POST', body }),
put: <T>(path: string, body: unknown, init?: RequestOptions) =>
request<T>(path, { ...init, method: 'PUT', body }),
patch: <T>(path: string, body: unknown, init?: RequestOptions) =>
request<T>(path, { ...init, method: 'PATCH', body }),
delete: <T>(path: string, init?: RequestOptions) =>
request<T>(path, { ...init, method: 'DELETE' }),
};
/* --- Backend wire formats (snake_case, see backend/schemas) ------------- */
interface BackendCategory {
id: number;
name: string;
slug: string;
}
interface BackendAuthor {
id: number;
name: string;
email: string;
bio: string | null;
}
interface BackendArticle {
id: number;
title: string;
content: string;
author_id: number;
category_id: number;
created_at: string;
published: boolean;
author?: BackendAuthor;
category?: BackendCategory;
}
function toCategory(category: BackendCategory): Category {
return { id: category.id, name: category.name, slug: category.slug };
}
function toAuthor(author: BackendAuthor): Author {
return {
id: author.id,
name: author.name,
email: author.email,
bio: author.bio ?? undefined,
};
}
function toArticle(article: BackendArticle): Article {
return {
id: article.id,
title: article.title,
content: article.content,
authorId: article.author_id,
author: article.author ? toAuthor(article.author) : undefined,
categoryId: article.category_id,
category: article.category ? toCategory(article.category) : undefined,
createdAt: article.created_at,
published: article.published,
};
}
/* --- Typed endpoint helpers --------------------------------------------- */
/** `GET /api/v1/health` — service liveness probe. */
export function getHealth(): Promise<HealthResponse> {
return api.get<HealthResponse>('/health');
}
/** `GET /api/v1/version` — application name and version. */
export function getVersion(): Promise<VersionResponse> {
return api.get<VersionResponse>('/version');
}
/**
* `GET /api/v1/articles` — list of published articles.
*
* The endpoint is provided by a later backend milestone; until then the
* UI falls back to sample data (see `src/data/sample.ts`).
*/
export function getArticles(): Promise<Article[]> {
return api.get<BackendArticle[]>('/articles').then((articles) =>
articles.map(toArticle),
);
}
+8
View File
@@ -0,0 +1,8 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" fill="none" role="img" aria-label="newzy logo">
<rect width="32" height="32" rx="7" fill="#2563eb"/>
<rect x="7" y="8" width="18" height="4" rx="1.2" fill="#ffffff"/>
<rect x="7" y="15" width="8" height="9" rx="1.2" fill="#bfdbfe"/>
<rect x="17.5" y="15" width="7.5" height="2" rx="1" fill="#ffffff"/>
<rect x="17.5" y="19" width="7.5" height="2" rx="1" fill="#ffffff"/>
<rect x="17.5" y="23" width="5" height="2" rx="1" fill="#ffffff"/>
</svg>

After

Width:  |  Height:  |  Size: 517 B

+34
View File
@@ -0,0 +1,34 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
:root {
color-scheme: light;
}
html {
@apply scroll-smooth;
}
body {
@apply bg-slate-50 text-slate-900 antialiased;
}
}
@layer components {
/* Centered page container used by all pages. */
.container-page {
@apply mx-auto w-full max-w-6xl px-4 py-8 sm:px-6;
}
/* Primary button style (links and buttons). */
.btn {
@apply inline-flex items-center justify-center gap-2 rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-700 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50;
}
/* Secondary button style. */
.btn-secondary {
@apply inline-flex items-center justify-center gap-2 rounded-md border border-slate-300 bg-white px-4 py-2 text-sm font-medium text-slate-700 transition-colors hover:bg-slate-100 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50;
}
}
@@ -0,0 +1,85 @@
import { Clock, FileText } from 'lucide-react';
import { Link } from 'react-router-dom';
import type { Article } from '../../types';
import { cn } from '../../lib/utils';
import { AuthorAvatar } from './AuthorAvatar';
import { CategoryBadge } from './CategoryBadge';
const WORDS_PER_MINUTE = 200;
/** Estimate reading time in minutes (minimum 1). */
export function getReadTime(content: string): number {
const words = content.trim().split(/\s+/).filter(Boolean).length;
return Math.max(1, Math.round(words / WORDS_PER_MINUTE));
}
function formatPublished(value: Article['createdAt']): string {
const date = value instanceof Date ? value : new Date(value);
if (Number.isNaN(date.getTime())) return '';
return date.toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' });
}
export interface ArticleCardProps {
article: Article;
className?: string;
}
/**
* Reusable article preview: thumbnail placeholder, category badge, title,
* excerpt, author (via AuthorAvatar) and estimated read time. Links to the
* article detail route via react-router-dom.
*/
export function ArticleCard({ article, className }: ArticleCardProps) {
const author =
article.author ?? { id: article.authorId, name: 'Unknown author', email: '' };
return (
<article
data-testid="article-card"
className={cn(
'group flex flex-col overflow-hidden rounded-lg border border-slate-200 bg-white shadow-sm transition-shadow hover:shadow-md',
className,
)}
>
{/* Thumbnail placeholder (images arrive with a later milestone) */}
<Link
to={`/articles/${article.id}`}
aria-label={`Read article: ${article.title}`}
className="flex h-36 items-center justify-center bg-slate-100 focus:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-blue-500"
>
<FileText className="h-10 w-10 text-slate-400" aria-hidden="true" />
</Link>
<div className="flex flex-1 flex-col gap-2 p-4">
{article.category && <CategoryBadge category={article.category} />}
<h3 className="text-base font-semibold leading-snug text-slate-900">
<Link
to={`/articles/${article.id}`}
className="hover:text-blue-700 hover:underline focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
>
{article.title}
</Link>
</h3>
<p className="line-clamp-3 text-sm text-slate-600">{article.content}</p>
</div>
<div className="flex items-center justify-between gap-2 border-t border-slate-100 px-4 py-3">
<span className="flex min-w-0 items-center gap-2 text-sm text-slate-600">
<AuthorAvatar author={author} size="sm" />
<span className="truncate">{author.name}</span>
</span>
<span
className="flex shrink-0 items-center gap-1 text-xs text-slate-500"
title={formatPublished(article.createdAt)}
>
<Clock className="h-3.5 w-3.5" aria-hidden="true" />
{getReadTime(article.content)} min read
</span>
</div>
</article>
);
}
export default ArticleCard;
@@ -0,0 +1,56 @@
import type { Author } from '../../types';
import { cn } from '../../lib/utils';
export interface AuthorAvatarProps {
author: Pick<Author, 'name' | 'avatar'>;
size?: 'sm' | 'md' | 'lg';
className?: string;
}
const SIZE_CLASSES = {
sm: 'h-6 w-6 text-[0.65rem]',
md: 'h-9 w-9 text-sm',
lg: 'h-12 w-12 text-base',
} as const;
/** Derive up to two initials from a full name ("Ada Lovelace" -> "AL"). */
export function initialsOf(name: string): string {
return name
.split(/\s+/)
.filter(Boolean)
.slice(0, 2)
.map((part) => part.charAt(0).toUpperCase())
.join('');
}
/**
* Author profile indicator: shows the profile image when available,
* otherwise the author's initials. The author's name is exposed as a hover
* tooltip (`title`) and as the accessible label.
*/
export function AuthorAvatar({ author, size = 'md', className }: AuthorAvatarProps) {
return (
<span
data-testid="author-avatar"
title={author.name}
aria-label={author.name}
className={cn(
'inline-flex shrink-0 items-center justify-center rounded-full bg-slate-200 font-semibold text-slate-700',
SIZE_CLASSES[size],
className,
)}
>
{author.avatar ? (
<img
src={author.avatar}
alt={author.name}
className="h-full w-full rounded-full object-cover"
/>
) : (
initialsOf(author.name)
)}
</span>
);
}
export default AuthorAvatar;
@@ -0,0 +1,56 @@
import { cva, type VariantProps } from 'class-variance-authority';
import type { Category } from '../../types';
import { cn } from '../../lib/utils';
/**
* Color-coded category pill.
*
* The tone is derived from the category slug (stable, URL-safe identifier);
* unknown slugs fall back to a neutral slate tone.
*/
const badgeVariants = cva(
'inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium',
{
variants: {
tone: {
blue: 'bg-blue-100 text-blue-800',
green: 'bg-green-100 text-green-800',
amber: 'bg-amber-100 text-amber-800',
purple: 'bg-purple-100 text-purple-800',
rose: 'bg-rose-100 text-rose-800',
slate: 'bg-slate-100 text-slate-700',
},
},
defaultVariants: {
tone: 'slate',
},
},
);
type BadgeTone = NonNullable<VariantProps<typeof badgeVariants>['tone']>;
const TONE_BY_SLUG: Record<string, BadgeTone> = {
technology: 'blue',
science: 'green',
sports: 'amber',
culture: 'purple',
world: 'rose',
};
export interface CategoryBadgeProps {
category: Pick<Category, 'name' | 'slug'>;
className?: string;
}
export function CategoryBadge({ category, className }: CategoryBadgeProps) {
return (
<span
data-testid="category-badge"
className={cn(badgeVariants({ tone: TONE_BY_SLUG[category.slug] }), className)}
>
{category.name}
</span>
);
}
export default CategoryBadge;
+99
View File
@@ -0,0 +1,99 @@
import { FileText, Home, Menu, Settings, X, type LucideIcon } from 'lucide-react';
import { useState } from 'react';
import { NavLink } from 'react-router-dom';
import logo from '../../assets/logo.svg';
import { cn } from '../../lib/utils';
export interface HeaderProps {
className?: string;
}
interface NavItem {
to: string;
label: string;
icon: LucideIcon;
/** Match the route exactly (used for "/"). */
end?: boolean;
}
const NAV_ITEMS: NavItem[] = [
{ to: '/', label: 'Home', icon: Home, end: true },
{ to: '/articles', label: 'Articles', icon: FileText },
{ to: '/categories', label: 'Categories', icon: Settings },
];
/**
* Main navigation header.
*
* Uses react-router-dom <NavLink> (never plain anchors) so navigation stays
* client-side. Lucide icons mark each item; the mobile menu collapses the
* same links into a toggleable panel below <md> breakpoints.
*/
export function Header({ className }: HeaderProps) {
const [menuOpen, setMenuOpen] = useState(false);
const closeMenu = () => setMenuOpen(false);
const linkClasses = ({ isActive }: { isActive: boolean }): string =>
cn(
'inline-flex items-center gap-2 rounded-md px-3 py-2 text-sm font-medium transition-colors',
'text-slate-600 hover:bg-slate-100 hover:text-slate-900',
isActive && 'bg-blue-50 text-blue-700 hover:bg-blue-100 hover:text-blue-800',
);
const renderNav = (id: string, itemClasses?: string) => (
<nav id={id} aria-label={`${id === 'mobile-menu' ? 'Mobile' : 'Main'} navigation`} className={itemClasses}>
{NAV_ITEMS.map(({ to, label, icon: Icon, end }) => (
<NavLink
key={to}
to={to}
end={end}
className={({ isActive }) => linkClasses({ isActive })}
onClick={closeMenu}
>
<Icon className="h-5 w-5" aria-hidden="true" />
<span>{label}</span>
</NavLink>
))}
</nav>
);
return (
<header
data-testid="site-header"
className={cn('sticky top-0 z-40 border-b border-slate-200 bg-white/95 backdrop-blur', className)}
>
<div className="mx-auto flex max-w-6xl items-center justify-between px-4 py-3 sm:px-6">
{/* Brand */}
<NavLink to="/" className="flex items-center gap-2" onClick={closeMenu} aria-label="newzy">
<img src={logo} alt="" className="h-8 w-8" />
<span className="text-xl font-bold tracking-tight text-slate-900">newzy</span>
</NavLink>
{/* Desktop navigation */}
{renderNav('main-nav', 'hidden items-center gap-1 md:flex')}
{/* Mobile menu toggle */}
<button
type="button"
className="inline-flex items-center justify-center rounded-md p-2 text-slate-600 hover:bg-slate-100 hover:text-slate-900 md:hidden"
aria-label={menuOpen ? 'Close menu' : 'Open menu'}
aria-expanded={menuOpen}
aria-controls="mobile-menu"
onClick={() => setMenuOpen((open) => !open)}
>
{menuOpen ? (
<X className="h-6 w-6" aria-hidden="true" />
) : (
<Menu className="h-6 w-6" aria-hidden="true" />
)}
</button>
</div>
{/* Mobile navigation (rendered only while open) */}
{menuOpen && renderNav('mobile-menu', 'flex flex-col gap-1 border-t border-slate-200 px-4 pb-4 pt-2 md:hidden')}
</header>
);
}
export default Header;
+72
View File
@@ -0,0 +1,72 @@
import { getHealth } from '../../api/client';
import { cn } from '../../lib/utils';
import type { ReactNode } from 'react';
import { useEffect, useState } from 'react';
import { Header } from './Header';
export interface LayoutProps {
children: ReactNode;
className?: string;
}
type ApiStatus = 'checking' | 'online' | 'offline';
const STATUS_STYLES: Record<ApiStatus, string> = {
checking: 'bg-amber-400',
online: 'bg-green-500',
offline: 'bg-red-500',
};
/**
* Application shell: sticky header, routed page content, and a footer with a
* backend API status indicator (fetched from `GET /api/v1/health` on mount).
*/
export function Layout({ children, className }: LayoutProps) {
const [apiStatus, setApiStatus] = useState<ApiStatus>('checking');
useEffect(() => {
let active = true;
getHealth()
.then(() => {
if (active) setApiStatus('online');
})
.catch(() => {
if (active) setApiStatus('offline');
});
return () => {
active = false;
};
}, []);
return (
<div className={cn('flex min-h-screen flex-col', className)}>
<Header />
<main id="main-content" className="flex-1">
{children}
</main>
<footer className="border-t border-slate-200 bg-white">
<div className="mx-auto flex max-w-6xl flex-col items-center justify-between gap-2 px-4 py-6 text-sm text-slate-500 sm:flex-row sm:px-6">
<p>
&copy; {new Date().getFullYear()} newzy — your news, curated.
</p>
<p
data-testid="api-status"
aria-live="polite"
className="flex items-center gap-2"
title="newzy backend API status"
>
<span
aria-hidden="true"
className={cn('h-2.5 w-2.5 rounded-full', STATUS_STYLES[apiStatus])}
/>
API: {apiStatus}
</p>
</div>
</footer>
</div>
);
}
export default Layout;
+113
View File
@@ -0,0 +1,113 @@
/**
* Sample data used until the backend article endpoints are available
* (planned for a later milestone). The home page falls back to this
* dataset whenever `GET /api/v1/articles` is unavailable.
*/
import type { Article, Author, Category } from '../types';
export const sampleAuthors: Author[] = [
{
id: 1,
name: 'Ada Lovelace',
email: 'ada@example.com',
bio: 'Writes about technology and computation.',
},
{
id: 2,
name: 'Grace Hopper',
email: 'grace@example.com',
bio: 'Covers science and engineering.',
},
{
id: 3,
name: 'Alan Turing',
email: 'alan@example.com',
bio: 'Follows sports and culture.',
},
];
export const sampleCategories: Category[] = [
{ id: 1, name: 'Technology', slug: 'technology' },
{ id: 2, name: 'Science', slug: 'science' },
{ id: 3, name: 'Sports', slug: 'sports' },
{ id: 4, name: 'Culture', slug: 'culture' },
];
const authorOf = (id: number): Author => sampleAuthors.find((a) => a.id === id) as Author;
const categoryOf = (id: number): Category =>
sampleCategories.find((c) => c.id === id) as Category;
export const sampleArticles: Article[] = [
{
id: 1,
title: 'Inside the new wave of open-source language models',
content:
'Open-source language models are closing the gap with proprietary systems, and the ecosystem around them is growing fast. Researchers now release pretrained weights alongside detailed training recipes, letting smaller teams fine-tune models for narrow tasks that once required large budgets. The result is a new layer of the AI stack: community-maintained tooling for evaluation, deployment, and safety testing that moves at a pace big vendors struggle to match. As hardware costs keep falling, expect the line between "research model" and "production model" to blur further this year.',
authorId: 1,
author: authorOf(1),
categoryId: 1,
category: categoryOf(1),
createdAt: '2025-06-02T09:30:00Z',
published: true,
},
{
id: 2,
title: 'Fusion milestone: net energy gain repeated for the third time',
content:
'Scientists have repeated a net-energy-gain fusion reaction for the third consecutive time, confirming that last months breakthrough was not a fluke. The latest run sustained the plasma for a record duration and produced energy output within a few percent of the original measurement. Engineers now say the remaining challenges are engineering, not physics: materials that survive repeated shots and power systems that deliver pulses on demand. A commercial demonstration plant could enter the design phase as early as next decade.',
authorId: 2,
author: authorOf(2),
categoryId: 2,
category: categoryOf(2),
createdAt: '2025-05-28T14:10:00Z',
published: true,
},
{
id: 3,
title: 'City marathon sets record turnout as first-timers flood the course',
content:
'More than 40,000 runners started this weekend city marathon, a record that organizers attributed to a wave of first-time participants. The 21-kilometer fun run sold out in under an hour, and volunteers reported the most positive start-line atmosphere in the events history. Pacing groups, music zones, and a free post-race breakfast kept the mood festive even in the rain. Officials are already planning capacity expansions for next year, with an eye on adding a night race.',
authorId: 3,
author: authorOf(3),
categoryId: 3,
category: categoryOf(3),
createdAt: '2025-05-25T08:00:00Z',
published: true,
},
{
id: 4,
title: 'The quiet return of the neighborhood library',
content:
'After years of budget cuts, the neighborhood library is staging an unlikely comeback. Community volunteers now staff the Saturday makerspace, where 3D printing, sewing machines, and a small recording studio are booked weeks in advance. Librarians report that circulation is up, but the real story is programming: repair cafés, language tables, and civic workshops that have made the building a second living room for the district. City planners are taking note, and two more branches are slated for renovation this fall.',
authorId: 1,
author: authorOf(1),
categoryId: 4,
category: categoryOf(4),
createdAt: '2025-05-20T17:45:00Z',
published: true,
},
{
id: 5,
title: 'Rust keeps climbing the systems programming charts',
content:
'Rust has moved up again in the annual systems programming survey, now the most-wanted language for kernel and infrastructure work among respondents. Adoption is no longer limited to startups: several large platforms report that new storage and networking services are written in Rust by default. The ecosystems memory-safety guarantees, combined with a mature async story, continue to draw engineers from C and C++. Tooling improvements in debugging and profiling have been the most cited reasons for teams crossing over this year.',
authorId: 2,
author: authorOf(2),
categoryId: 1,
category: categoryOf(1),
createdAt: '2025-05-15T11:20:00Z',
published: true,
},
{
id: 6,
title: 'Ocean robots map the deepest trenches in record time',
content:
'A fleet of autonomous underwater vehicles has completed the most detailed survey of the ocean trench yet, mapping 80 percent of the basin floor in six weeks. The robots, equipped with multibeam sonar and high-resolution cameras, collected terabytes of data that reveal previously unknown seamounts and hydrothermal vent fields. Biologists have already flagged three candidate species from the first batch of imagery. The team plans to return next winter with sampling landers to study the vent communities up close.',
authorId: 3,
author: authorOf(3),
categoryId: 2,
category: categoryOf(2),
createdAt: '2025-05-10T19:05:00Z',
published: true,
},
];
+13
View File
@@ -0,0 +1,13 @@
import { clsx, type ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';
/**
* Merge Tailwind CSS classes with conflict resolution.
*
* Combines `clsx` (conditional class names) with `tailwind-merge` (drops
* conflicting utilities, last one wins) so component classes can be safely
* extended from props: `cn(baseClasses, props.className)`.
*/
export function cn(...inputs: ClassValue[]): string {
return twMerge(clsx(inputs));
}
+10
View File
@@ -0,0 +1,10 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import './assets/styles/globals.css';
ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
<React.StrictMode>
<App />
</React.StrictMode>,
);
+69
View File
@@ -0,0 +1,69 @@
import { ArrowLeft, FileText } from 'lucide-react';
import { Link, useParams } from 'react-router-dom';
import type { ReactNode } from 'react';
/**
* Article view placeholder.
*
* - `/articles` — "all articles" layout (listing arrives in a later milestone)
* - `/articles/:id` — single article layout (reads the id via useParams)
*/
export function ArticlePage() {
const { id } = useParams<{ id: string }>();
if (id) {
return (
<div className="container-page">
<nav aria-label="Breadcrumb" className="mb-6">
<Link
to="/articles"
className="inline-flex items-center gap-1 text-sm text-blue-600 hover:text-blue-700 hover:underline"
>
<ArrowLeft className="h-4 w-4" aria-hidden="true" />
All articles
</Link>
</nav>
<Placeholder
heading={`Article #${id}`}
description="The full article view lands in a later milestone. This placeholder proves that the /articles/:id route works end to end."
/>
</div>
);
}
return (
<div className="container-page">
<Placeholder
heading="Articles"
description="Every published story from newzy, in one place. The complete listing is coming in a later milestone — meanwhile, browse the latest on the home page."
action={
<Link to="/" className="btn">
<ArrowLeft className="h-4 w-4" aria-hidden="true" />
Back to home
</Link>
}
/>
</div>
);
}
interface PlaceholderProps {
heading: string;
description: string;
action?: ReactNode;
}
function Placeholder({ heading, description, action }: PlaceholderProps) {
return (
<div>
<h1 className="mb-6 text-3xl font-bold text-slate-900">{heading}</h1>
<div className="flex flex-col items-start gap-4 rounded-xl border border-dashed border-slate-300 bg-white p-8">
<FileText className="h-10 w-10 text-slate-300" aria-hidden="true" />
<p className="max-w-prose text-sm leading-relaxed text-slate-600">{description}</p>
{action}
</div>
</div>
);
}
export default ArticlePage;
+50
View File
@@ -0,0 +1,50 @@
import { FolderOpen } from 'lucide-react';
import { CategoryBadge } from '../components/articles/CategoryBadge';
import { sampleArticles, sampleCategories } from '../data/sample';
/**
* Categories listing page (placeholder layout).
*
* Renders the known categories with article counts derived from the sample
* feed; the real listing will be fetched from the backend in a later
* milestone.
*/
export function CategoriesPage() {
const counts = sampleCategories.map((category) => ({
category,
articleCount: sampleArticles.filter((article) => article.categoryId === category.id).length,
}));
return (
<div className="container-page">
<h1 className="mb-2 text-3xl font-bold text-slate-900">Categories</h1>
<p className="mb-8 max-w-prose text-sm text-slate-600">
Browse newzy by topic. This layout is a placeholder — category pages
with full article listings arrive in a later milestone.
</p>
<div className="grid gap-4 sm:grid-cols-2">
{counts.map(({ category, articleCount }) => (
<div
key={category.id}
className="flex items-center justify-between gap-4 rounded-lg border border-slate-200 bg-white p-5 shadow-sm"
>
<div className="flex items-center gap-3">
<FolderOpen className="h-6 w-6 text-slate-400" aria-hidden="true" />
<div>
<p className="font-medium text-slate-900">{category.name}</p>
<p className="text-xs text-slate-500">/{category.slug}</p>
</div>
</div>
<div className="flex items-center gap-3">
<CategoryBadge category={category} />
<span className="text-sm text-slate-500">{articleCount} articles</span>
</div>
</div>
))}
</div>
</div>
);
}
export default CategoriesPage;
+203
View File
@@ -0,0 +1,203 @@
import { ArrowRight, Info, Search } from 'lucide-react';
import { useEffect, useMemo, useState } from 'react';
import { Link } from 'react-router-dom';
import { ApiError, getArticles } from '../api/client';
import { ArticleCard, getReadTime } from '../components/articles/ArticleCard';
import { AuthorAvatar } from '../components/articles/AuthorAvatar';
import { CategoryBadge } from '../components/articles/CategoryBadge';
import { sampleArticles } from '../data/sample';
import type { Article } from '../types';
type FeedSource = 'api' | 'sample';
/**
* Homepage: featured (hero) article, search bar, article grid built from
* ArticleCard components, and a pagination placeholder.
*
* Articles are loaded from `GET /api/v1/articles`; until that backend
* endpoint exists the page falls back to sample data (clearly labelled).
*/
export function Home() {
const [articles, setArticles] = useState<Article[]>([]);
const [source, setSource] = useState<FeedSource>('sample');
const [loading, setLoading] = useState(true);
const [query, setQuery] = useState('');
useEffect(() => {
let active = true;
getArticles()
.then((data) => {
if (!active) return;
if (data.length > 0) {
setArticles(data);
setSource('api');
} else {
setArticles(sampleArticles);
setSource('sample');
}
})
.catch((error: unknown) => {
if (!active) return;
// 404 (endpoint not implemented yet) or network failure: fall back to
// sample data so the UI stays useful without a running backend.
if (!(error instanceof ApiError)) {
console.error('Unexpected error while loading articles:', error);
}
setArticles(sampleArticles);
setSource('sample');
})
.finally(() => {
if (active) setLoading(false);
});
return () => {
active = false;
};
}, []);
const filtered = useMemo(() => {
const q = query.trim().toLowerCase();
if (!q) return articles;
return articles.filter(
(article) =>
article.title.toLowerCase().includes(q) ||
article.content.toLowerCase().includes(q),
);
}, [articles, query]);
const featured = filtered[0];
const publishedAt = (article: Article): string => {
const date = article.createdAt instanceof Date ? article.createdAt : new Date(article.createdAt);
return Number.isNaN(date.getTime())
? ''
: date.toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' });
};
return (
<div className="container-page">
{/* Search / filter bar (client-side filter for now) */}
<form
role="search"
className="mb-8 flex items-center gap-3"
onSubmit={(event) => event.preventDefault()}
>
<label htmlFor="article-search" className="sr-only">
Search articles
</label>
<div className="relative w-full max-w-md">
<Search
className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400"
aria-hidden="true"
/>
<input
id="article-search"
type="search"
placeholder="Search articles"
value={query}
onChange={(event) => setQuery(event.target.value)}
className="w-full rounded-md border border-slate-300 bg-white py-2 pl-9 pr-3 text-sm text-slate-900 placeholder:text-slate-400 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500"
/>
</div>
<select
aria-label="Filter by category"
className="rounded-md border border-slate-300 bg-white py-2 pl-3 pr-8 text-sm text-slate-600"
defaultValue=""
disabled
title="Category filtering arrives with a later milestone"
>
<option value="">All categories</option>
</select>
</form>
{source === 'sample' && !loading && (
<p
data-testid="sample-data-note"
className="mb-6 flex items-center gap-2 rounded-md border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800"
>
<Info className="h-4 w-4 shrink-0" aria-hidden="true" />
Showing sample data — live articles arrive once the backend article
endpoints are available.
</p>
)}
{/* Hero: featured article */}
{featured && (
<section
aria-label="Featured article"
className="mb-10 overflow-hidden rounded-xl border border-slate-200 bg-white shadow-sm"
>
<div className="grid gap-6 p-6 sm:p-8 md:grid-cols-[2fr,1fr] md:items-center">
<div>
<div className="mb-3 flex items-center gap-3">
<span className="rounded-full bg-blue-600 px-2.5 py-0.5 text-xs font-semibold uppercase tracking-wide text-white">
Featured
</span>
{featured.category && <CategoryBadge category={featured.category} />}
</div>
<h1 className="mb-3 text-2xl font-bold leading-tight text-slate-900 sm:text-3xl">
{featured.title}
</h1>
<p className="mb-4 text-sm leading-relaxed text-slate-600 sm:text-base">
{featured.content}
</p>
<div className="flex flex-wrap items-center gap-x-4 gap-y-2 text-sm text-slate-500">
<span className="flex items-center gap-2">
<AuthorAvatar
author={featured.author ?? { name: 'Unknown author' }}
size="sm"
/>
{featured.author?.name ?? 'Unknown author'}
</span>
<span>{publishedAt(featured)}</span>
<span>{getReadTime(featured.content)} min read</span>
</div>
</div>
<div className="flex md:justify-end">
<Link to={`/articles/${featured.id}`} className="btn">
Read article
<ArrowRight className="h-4 w-4" aria-hidden="true" />
</Link>
</div>
</div>
</section>
)}
{/* Article grid */}
<section aria-label="Latest articles" className="mb-10">
<h2 className="mb-4 text-lg font-semibold text-slate-900">Latest articles</h2>
{loading ? (
<div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3" aria-busy="true">
{[0, 1, 2].map((index) => (
<div
key={index}
className="h-80 animate-pulse rounded-lg border border-slate-200 bg-white p-4"
/>
))}
</div>
) : filtered.length > 0 ? (
<div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
{filtered.map((article) => (
<ArticleCard key={article.id} article={article} />
))}
</div>
) : (
<p className="rounded-md border border-dashed border-slate-300 bg-white px-4 py-8 text-center text-sm text-slate-500">
No articles match your search.
</p>
)}
</section>
{/* Pagination placeholder */}
<nav aria-label="Pagination" className="flex items-center justify-center gap-2">
<button type="button" className="btn-secondary" disabled>
Previous
</button>
<span className="text-sm text-slate-500">Page 1 of 1</span>
<button type="button" className="btn-secondary" disabled>
Next
</button>
</nav>
</div>
);
}
export default Home;
+65
View File
@@ -0,0 +1,65 @@
import { screen } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import { ArticleCard, getReadTime } from '../components/articles/ArticleCard';
import type { Article } from '../types';
import { renderWithRouter } from './utils';
const article: Article = {
id: 42,
title: 'Test article title',
content: 'Lorem ipsum dolor sit amet. '.repeat(20),
authorId: 1,
author: { id: 1, name: 'Jane Doe', email: 'jane@example.com', bio: 'Writer' },
categoryId: 2,
category: { id: 2, name: 'Science', slug: 'science' },
createdAt: '2025-03-01T12:00:00Z',
published: true,
};
describe('ArticleCard', () => {
it('renders the title, category badge, author and read time', () => {
renderWithRouter(<ArticleCard article={article} />);
expect(
screen.getByRole('heading', { level: 3, name: 'Test article title' }),
).toBeInTheDocument();
expect(screen.getByTestId('category-badge')).toHaveTextContent('Science');
expect(screen.getByText('Jane Doe')).toBeInTheDocument();
expect(screen.getByText(/min read/i)).toBeInTheDocument();
});
it('shows author initials in the avatar', () => {
renderWithRouter(<ArticleCard article={article} />);
expect(screen.getByTestId('author-avatar')).toHaveTextContent('JD');
expect(screen.getByTestId('author-avatar')).toHaveAttribute('title', 'Jane Doe');
});
it('links to the article detail route', () => {
renderWithRouter(<ArticleCard article={article} />);
const links = screen.getAllByRole('link');
expect(
links.some((link) => link.getAttribute('href') === '/articles/42'),
).toBe(true);
});
it('falls back to an unknown author when the author is missing', () => {
renderWithRouter(<ArticleCard article={{ ...article, author: undefined }} />);
expect(screen.getByText('Unknown author')).toBeInTheDocument();
});
it('omits the category badge when no category is present', () => {
renderWithRouter(<ArticleCard article={{ ...article, category: undefined }} />);
expect(screen.queryByTestId('category-badge')).not.toBeInTheDocument();
});
describe('getReadTime', () => {
it('returns a minimum of one minute', () => {
expect(getReadTime('a very short piece')).toBe(1);
});
it('estimates two minutes for ~400 words at 200 wpm', () => {
expect(getReadTime('word '.repeat(400).trim())).toBe(2);
});
});
});
+55
View File
@@ -0,0 +1,55 @@
import { fireEvent, screen, within } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import Header from '../components/ui/Header';
import { renderWithRouter } from './utils';
describe('Header', () => {
it('renders the brand with the logo', () => {
renderWithRouter(<Header />);
const brand = screen.getByRole('link', { name: 'newzy' });
expect(brand).toHaveAttribute('href', '/');
expect(brand.querySelector('img')).toHaveAttribute('src', expect.stringContaining('logo'));
});
it('renders the primary navigation with router links and lucide icons', () => {
renderWithRouter(<Header />);
const nav = screen.getByRole('navigation', { name: 'Main navigation' });
expect(within(nav).getByRole('link', { name: /home/i })).toHaveAttribute('href', '/');
expect(within(nav).getByRole('link', { name: /articles/i })).toHaveAttribute('href', '/articles');
expect(within(nav).getByRole('link', { name: /categories/i })).toHaveAttribute('href', '/categories');
// Lucide icons render as inline SVGs (one per nav item).
expect(nav.querySelectorAll('svg').length).toBeGreaterThanOrEqual(NAV_ITEM_COUNT);
});
it('marks the active route in the navigation', () => {
renderWithRouter(<Header />, { route: '/categories' });
const nav = screen.getByRole('navigation', { name: 'Main navigation' });
expect(within(nav).getByRole('link', { name: /categories/i })).toHaveClass('bg-blue-50');
expect(within(nav).getByRole('link', { name: /home/i })).not.toHaveClass('bg-blue-50');
});
it('toggles the mobile menu', () => {
renderWithRouter(<Header />);
// Mobile menu is closed by default.
expect(screen.queryByRole('navigation', { name: 'Mobile navigation' })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Open menu' }));
const mobileNav = screen.getByRole('navigation', { name: 'Mobile navigation' });
expect(mobileNav).toBeInTheDocument();
expect(within(mobileNav).getByRole('link', { name: /articles/i })).toHaveAttribute(
'href',
'/articles',
);
fireEvent.click(screen.getByRole('button', { name: 'Close menu' }));
expect(
screen.queryByRole('navigation', { name: 'Mobile navigation' }),
).not.toBeInTheDocument();
});
});
const NAV_ITEM_COUNT = 3;
+57
View File
@@ -0,0 +1,57 @@
import { screen } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { Mock } from 'vitest';
import { getHealth } from '../api/client';
import Layout from '../components/ui/Layout';
import { renderWithRouter } from './utils';
vi.mock('../api/client', () => ({
getHealth: vi.fn(),
}));
describe('Layout', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('renders the header, main content area and footer', () => {
(getHealth as Mock).mockRejectedValue(new Error('offline'));
renderWithRouter(
<Layout>
<p>Page content</p>
</Layout>,
);
expect(screen.getByRole('banner')).toBeInTheDocument();
expect(screen.getByRole('main')).toHaveTextContent('Page content');
expect(screen.getByRole('contentinfo')).toBeInTheDocument();
// Brand is reachable from the layout header.
expect(screen.getByRole('link', { name: 'newzy' })).toHaveAttribute('href', '/');
});
it('shows the API as online when the health check succeeds', async () => {
(getHealth as Mock).mockResolvedValue({ status: 'ok', version: '0.1.0' });
renderWithRouter(
<Layout>
<p>content</p>
</Layout>,
);
expect(await screen.findByTestId('api-status')).toHaveTextContent(/api:\s*online/i);
expect(getHealth).toHaveBeenCalledTimes(1);
});
it('shows the API as offline when the health check fails', async () => {
(getHealth as Mock).mockRejectedValue(new Error('offline'));
renderWithRouter(
<Layout>
<p>content</p>
</Layout>,
);
expect(await screen.findByTestId('api-status')).toHaveTextContent(/api:\s*offline/i);
});
});
@@ -0,0 +1,44 @@
import { render, screen } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import { AuthorAvatar, initialsOf } from '../../components/articles/AuthorAvatar';
describe('AuthorAvatar', () => {
it('shows initials when no avatar image is set', () => {
render(<AuthorAvatar author={{ name: 'Ada Lovelace' }} />);
const avatar = screen.getByTestId('author-avatar');
expect(avatar).toHaveTextContent('AL');
expect(avatar).toHaveAttribute('title', 'Ada Lovelace');
expect(avatar).toHaveAttribute('aria-label', 'Ada Lovelace');
});
it('renders the avatar image when provided', () => {
render(
<AuthorAvatar
author={{ name: 'Ada Lovelace', avatar: 'https://example.com/ada.png' }}
/>,
);
const image = screen.getByRole('img', { name: 'Ada Lovelace' });
expect(image).toHaveAttribute('src', 'https://example.com/ada.png');
});
it('supports size variants', () => {
const { rerender } = render(<AuthorAvatar author={{ name: 'Ada Lovelace' }} size="lg" />);
expect(screen.getByTestId('author-avatar')).toHaveClass('h-12', 'w-12');
rerender(<AuthorAvatar author={{ name: 'Ada Lovelace' }} size="sm" />);
expect(screen.getByTestId('author-avatar')).toHaveClass('h-6', 'w-6');
});
describe('initialsOf', () => {
it('takes the first letter of the first two words', () => {
expect(initialsOf('Grace Hopper')).toBe('GH');
});
it('handles single names and extra whitespace', () => {
expect(initialsOf('Turing')).toBe('T');
expect(initialsOf(' Ada Lovelace ')).toBe('AL');
});
});
});
@@ -0,0 +1,33 @@
import { render, screen } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import CategoryBadge from '../../components/articles/CategoryBadge';
describe('CategoryBadge', () => {
it('renders the category name', () => {
render(<CategoryBadge category={{ name: 'Technology', slug: 'technology' }} />);
expect(screen.getByTestId('category-badge')).toHaveTextContent('Technology');
});
it('applies the color tone for known slugs', () => {
render(<CategoryBadge category={{ name: 'Technology', slug: 'technology' }} />);
expect(screen.getByTestId('category-badge')).toHaveClass('bg-blue-100');
render(<CategoryBadge category={{ name: 'Science', slug: 'science' }} />);
expect(screen.getAllByTestId('category-badge')[1]).toHaveClass('bg-green-100');
});
it('falls back to a neutral tone for unknown slugs', () => {
render(<CategoryBadge category={{ name: 'Mystery', slug: 'mystery' }} />);
expect(screen.getByTestId('category-badge')).toHaveClass('bg-slate-100');
});
it('accepts extra classes via the className prop', () => {
render(
<CategoryBadge
category={{ name: 'Culture', slug: 'culture' }}
className="text-lg"
/>,
);
expect(screen.getByTestId('category-badge')).toHaveClass('text-lg');
});
});
+12
View File
@@ -0,0 +1,12 @@
/**
* Vitest setup: registers jest-dom matchers and cleans up the DOM after
* every test (React Testing Library auto-cleanup needs this when globals
* are disabled).
*/
import '@testing-library/jest-dom/vitest';
import { cleanup } from '@testing-library/react';
import { afterEach } from 'vitest';
afterEach(() => {
cleanup();
});
+26
View File
@@ -0,0 +1,26 @@
import { render, type RenderOptions } from '@testing-library/react';
import type { ReactElement } from 'react';
import { MemoryRouter } from 'react-router-dom';
export interface RenderWithRouterOptions extends Omit<RenderOptions, 'wrapper'> {
/** Initial route (path only, e.g. "/articles/1"). */
route?: string;
}
/**
* Render helper that wraps the UI in a MemoryRouter so components using
* react-router-dom (Link, NavLink, useParams) can be tested in isolation.
*/
export function renderWithRouter(ui: ReactElement, options: RenderWithRouterOptions = {}) {
const { route = '/', ...renderOptions } = options;
return render(
<MemoryRouter
initialEntries={[route]}
future={{ v7_startTransition: true, v7_relativeSplatPath: true }}
>
{ui}
</MemoryRouter>,
renderOptions,
);
}
+61
View File
@@ -0,0 +1,61 @@
/**
* Core domain types for the newzy frontend.
*
* These interfaces mirror the backend models (see `backend/models/`) and the
* API schemas (see `backend/schemas/`). Note the backend returns snake_case
* JSON (e.g. `author_id`, `created_at`); `src/api/client.ts` maps those
* payloads onto the camelCase interfaces defined here.
*/
export interface Article {
id: number;
title: string;
content: string;
authorId: number;
author?: Author;
categoryId: number;
category?: Category;
createdAt: Date | string;
published: boolean;
}
export interface Author {
id: number;
name: string;
email: string;
bio?: string;
avatar?: string;
}
export interface Category {
id: number;
name: string;
slug: string;
}
/** Envelope used by frontend API helpers for successful responses. */
export interface ApiResponse<T> {
success: boolean;
data?: T;
error?: string;
message?: string;
}
/** Standard error envelope returned by the FastAPI backend for non-2xx. */
export interface ApiErrorPayload {
detail: string;
code: string;
errors?: Array<Record<string, unknown>>;
}
/** Payload of `GET /api/v1/health` (and `GET /health`). */
export interface HealthResponse {
status: string;
version: string;
}
/** Payload of `GET /api/v1/version`. */
export interface VersionResponse {
app: string;
version: string;
}
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />
+14
View File
@@ -0,0 +1,14 @@
import defaultTheme from 'tailwindcss/defaultTheme';
/** @type {import('tailwindcss').Config} */
export default {
content: ['./index.html', './src/**/*.{ts,tsx}'],
theme: {
extend: {
fontFamily: {
sans: ['Inter', 'system-ui', ...defaultTheme.fontFamily.sans],
},
},
},
plugins: [],
};
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode (Vite) */
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }]
}
+11
View File
@@ -0,0 +1,11 @@
{
"compilerOptions": {
"composite": true,
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "bundler",
"allowSyntheticDefaultImports": true,
"strict": true
},
"include": ["vite.config.ts", "vitest.config.ts", "playwright.config.ts"]
}
+36
View File
@@ -0,0 +1,36 @@
import react from '@vitejs/plugin-react';
import { defineConfig } from 'vite';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
// Base path used for all generated asset URLs.
base: '/',
build: {
// Production bundle output directory (served by Nginx in Docker).
outDir: 'dist',
sourcemap: false,
target: 'es2020',
},
server: {
// Development server.
port: 5173,
proxy: {
// Forward API calls to the FastAPI backend during development.
'/api': {
target: 'http://localhost:8000',
changeOrigin: true,
},
},
},
preview: {
// `vite preview` (used by the Playwright E2E webServer).
port: 4173,
proxy: {
'/api': {
target: 'http://localhost:8000',
changeOrigin: true,
},
},
},
});
+20
View File
@@ -0,0 +1,20 @@
/// <reference types="vitest" />
import react from '@vitejs/plugin-react';
import { defineConfig } from 'vitest/config';
export default defineConfig({
plugins: [react()],
test: {
environment: 'jsdom',
setupFiles: ['./src/tests/setup.ts'],
include: ['src/tests/**/*.test.{ts,tsx}'],
exclude: ['node_modules', 'dist', 'playwright'],
css: false,
globals: false,
coverage: {
provider: 'v8',
reporter: ['text', 'html', 'lcov'],
include: ['src/components/**', 'src/pages/**'],
},
},
});
@@ -0,0 +1,372 @@
# M4: Setup Developer Environment
## Prompt
Set up a complete developer environment for **newzy** news web application with Docker Compose orchestration. Follow these steps:
1. Create `docker-compose.yml` at project root (`newzy/docker-compose.yml`) with all services:
```yaml
version: '3.8'
services:
backend:
build: ./backend
ports:
- "8000:8000"
volumes:
- ./data/db:/app/data/db
environment:
- DATABASE_URL=sqlite:///./data/db/newzy.db
- DEBUG=false
frontend:
build: ./frontend
ports:
- "3000:80"
depends_on:
- backend
networks:
newzy-network:
driver: bridge
volumes:
db-data:
```
2. Create `.env.example` file documenting all required environment variables:
- DATABASE_URL (SQLite path)
- DEBUG (boolean, optional)
- BACKEND_CORS_ORIGINS (comma-separated, default: http://localhost:3000)
- FRONTEND_API_URL (relative /api or absolute)
3. Create `.env` file with default development values:
```bash
DATABASE_URL=sqlite:///./data/db/newzy.db
DEBUG=false
BACKEND_CORS_ORIGINS=http://localhost:3000,http://localhost:5173
FRONTEND_API_URL=/api
```
4. Update `backend/.gitignore` to exclude `.env` and production data:
```python
.env
.env.*
data/
```
5. Create development scripts in project root using Makefile or shell script:
- `dev` - Start both services in background
- `stop` - Stop all services
- `restart` - Restart all services
- `backend-start` - Start backend only
- `frontend-start` - Start frontend only
- `test` - Run all tests (unit + E2E)
- `clean` - Remove containers and volumes
6. Add `Makefile` for command shortcuts:
```makefile
.PHONY: dev stop restart backend-start frontend-start test clean
dev:
docker compose up -d --build
stop:
docker compose down
restart:
docker compose down
docker compose up -d --build
backend-start:
docker compose up -d backend
frontend-start:
docker compose up -d frontend
test:
npm run test # frontend
cd backend && pytest # backend
clean:
docker compose down -v
rm -rf data/
docker image prune -f
```
7. Create `backend/Dockerfile` with development optimizations:
- Copy only required files
- Install dependencies efficiently
- Use slim Python base image
- Expose port 8000
8. Update `frontend/Dockerfile` to use production Nginx:
- Multi-stage build (build stage + nginx serve stage)
- Nginx configuration for SPA routing
- Production-optimized static file serving
9. Create `.gitignore` at project root excluding:
```
# Dependencies
node_modules/
*.egg-info/
# Environment files
.env
.env.local
.env.*.local
# IDE settings
.idea/
.vscode/
*.swp
*.swo
# Docker artifacts (optional)
.dockerignore
docker-compose.override.yml
```
10. Create `data/.gitignore` to exclude SQLite database from version control:
```
*
!keep_files.txt
```
11. Document setup process in `README.md`:
- Prerequisites (Docker, Node.js 18+)
- Quick start commands
- Service descriptions
- Port mappings
- Network configuration
- Troubleshooting guide
12. Create `.dockerignore` files for both backend and frontend to exclude unnecessary files during builds:
```
.git/
.env
__pycache__/
*.pyc
node_modules/
dist/
.pytest_cache/
```
Remember: Focus ONLY on developer environment setup. No application code changes required.
## Description
This milestone sets up a complete Docker Compose development environment for the newzy news web application. The scope includes orchestrating both backend and frontend services, environment variable management, and streamlined development commands—no application logic changes or business feature implementation.
**Purpose**: Provide developers with a consistent, reproducible local development environment using Docker that matches the production setup as closely as possible.
**Target Audience**: Developers joining the project who need quick access to running services without manual installation of Python, Node.js, databases, or Nginx.
**Expected Outcomes**: A working docker-compose.yml at project root that can start all services with a single command, proper environment configuration, and development workflow automation via Makefile.
## Acceptance Criteria
- [ ] `docker-compose.yml` at project root configures both backend and frontend services
- [ ] Backend service builds from `./backend` directory
- [ ] Frontend service builds from `./frontend` directory
- [ ] Port mappings configured: 3000 for frontend, 8000 for backend
- [ ] Docker network defined for inter-service communication
- [ ] Volume mounted for persistent SQLite database at `/data/db`
- [ ] `.env.example` file documents all environment variables
- [ ] `.env` file provides default development configuration
- [ ] `backend/Dockerfile` optimized for production use
- [ ] `frontend/Dockerfile` uses multi-stage build with Nginx
- [ ] Makefile or shell scripts provide dev, stop, restart commands
- [ ] `data/.gitignore` excludes database from version control
- [ ] `.dockerignore` files exist for both frontend and backend
- [ ] Project root `.gitignore` excludes env files and build artifacts
- [ ] README.md documents docker setup with quick start guide
## Technical Details
### docker-compose.yml (Project Root)
```yaml
version: '3.8'
services:
backend:
build:
context: ./backend
dockerfile: Dockerfile
ports:
- "8000:8000"
volumes:
- ./data/db:/app/data/db
environment:
- DATABASE_URL=sqlite:///./data/db/newzy.db
- DEBUG=false
- BACKEND_CORS_ORIGINS=http://localhost:3000,http://localhost:5173
depends_on:
backend-db:
condition: service_healthy
networks:
- newzy-network
restart: unless-stopped
frontend:
build:
context: ./frontend
dockerfile: Dockerfile
ports:
- "3000:80"
depends_on:
- backend
networks:
- newzy-network
restart: unless-stopped
networks:
newzy-network:
driver: bridge
ipam:
config:
- subnet: 172.28.0.0/16
volumes:
db-data:
name: newzy-db-data
```
### Environment Variables (.env.example)
| Variable | Description | Default | Required |
|----------|-------------|---------|----------|
| DATABASE_URL | SQLite database path | sqlite:///./data/db/newzy.db | Yes |
| DEBUG | Debug mode flag | false | No |
| BACKEND_CORS_ORIGINS | Allowed frontend origins | http://localhost:3000 | No |
| FRONTEND_API_URL | Backend API base URL | /api | No |
### Development Commands (Makefile)
```makefile
.PHONY: dev stop restart test clean build
dev:
docker compose up -d --build backend frontend
stop:
docker compose down
restart:
docker compose down
docker compose up -d --build backend frontend
test:
@echo "Running frontend tests..."
npm run test
@echo "Running backend tests..."
docker exec frontend npm run test || \
docker exec backend pytest
clean:
docker compose down -v
rm -rf data/
docker images | grep -E "(newzy|python|node)" | awk '{print $$3}' | xargs docker rmi
build:
docker compose build --no-cache
logs:
docker compose logs -f backend frontend
shell-backend:
docker exec -it backend bash
shell-frontend:
docker exec -it frontend sh
```
### Directory Structure with Docker Setup
```
newzy/
├── data/ # Local SQLite data directory
│ └── db/
│ └── newzy.db # Persisted database (excluded from git)
├── backend/
│ ├── Dockerfile
│ ├── requirements.txt
│ ├── .gitignore
│ └── pytest.ini
├── frontend/
│ ├── Dockerfile
│ ├── docker-compose.yml # Frontend-specific override (optional)
│ └── package.json
├── docker-compose.yml # Main orchestration file
├── .env # Development environment variables
├── .env.example # Template for .env
├── Makefile # Development shortcuts
├── .dockerignore # Exclude files from build context
└── data/.gitignore # Exclude database from git
```
### Multi-stage Build Strategy
**Backend Dockerfile:**
- Base: `python:3.11-slim`
- Install dependencies with `pip install --no-cache-dir`
- Copy only production code and requirements
- Expose port 8000
**Frontend Dockerfile:**
- Stage 1: `node:20-alpine` → Build frontend with Vite
- Stage 2: `nginx:alpine` → Serve built static files
- Nginx config routes all requests to index.html for SPA
### Service Communication Flow
```
Browser (localhost:3000)
↓ HTTP Request
Frontend Container (newzy-network:80)
↓ Forwarded to /api
Backend Container (newzy-network:8000)
↓ Connects to SQLite
Volume: data/db/newzy.db
```
## QA Notes
### Testing Checklist
- [ ] `docker compose up` starts both services without errors
- [ ] Frontend accessible at http://localhost:3000
- [ ] Backend accessible at http://localhost:8000
- [ ] Health endpoints respond correctly
- [ ] Database persists across service restarts
- [ ] `.env.example` contains all documented variables
- [ ] Makefile commands work (dev, stop, restart, clean)
- [ ] `data/` directory excluded from git commits
- [ ] `.gitignore` excludes environment files
### Security Considerations
- Never commit `.env` file to version control
- Use `.env.example` as template for new developers
- SQLite database stored locally, not in container (volume mounted)
- CORS configured with specific origins
- No production secrets exposed by default
### Performance Notes
- `--build` flag only when needed (avoid rebuilds on dev)
- Docker cache leveraged for incremental builds
- SQLite file storage faster than network databases for development
- Nginx serves static files efficiently in production
### Known Limitations
- Requires Docker Desktop or equivalent installed locally
- Mac users need sufficient disk space (~50GB recommended)
- Windows WSL2 required for best performance
- No GPU acceleration (CPU-based only)
- Production databases should use PostgreSQL, not SQLite
### Success Metrics
- `docker compose up` completes in under 5 minutes on first run
- Services restart within 10 seconds subsequent runs
- Development environment identical to staging/production setup
- Zero manual configuration required for new developers
- Makefile shortcuts reduce repetitive Docker commands