Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ffe19272b3 | ||
|
|
cbeac5e16b |
No files matched your search
@@ -8,15 +8,18 @@
|
|||||||
|
|
||||||
| Milestone | Description | Status |
|
| Milestone | Description | Status |
|
||||||
| --------- | ------------------------- | -------- |
|
| --------- | ------------------------- | -------- |
|
||||||
| M1 | Git project setup | Done |
|
| M1 | Git project setup | Done |
|
||||||
| M2 | Backend setup (FastAPI) | Done |
|
| M2 | Backend setup (FastAPI) | Done |
|
||||||
| M3+ | News application features | Planned |
|
| M3 | Frontend setup (React + Vite) | Done |
|
||||||
|
| M4+ | News application features | Planned |
|
||||||
|
|
||||||
See [milestones/](milestones/) for milestone prompts and progress tracking.
|
See [milestones/](milestones/) for milestone prompts and progress tracking.
|
||||||
|
|
||||||
## Requirements
|
## 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
|
## Getting Started
|
||||||
|
|
||||||
@@ -41,6 +44,18 @@ git push -u origin feature/<short-description>
|
|||||||
|
|
||||||
Full contribution guidelines, including branching, merging, and rebase workflows, are in [CONTRIBUTING.md](CONTRIBUTING.md).
|
Full contribution guidelines, including branching, merging, and rebase workflows, are in [CONTRIBUTING.md](CONTRIBUTING.md).
|
||||||
|
|
||||||
|
## Running the application
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Full stack (backend :8000 + frontend :3000)
|
||||||
|
docker compose up --build
|
||||||
|
```
|
||||||
|
|
||||||
|
Or run each half locally — see the component READMEs for details:
|
||||||
|
|
||||||
|
- [frontend/README.md](frontend/README.md) — `npm run dev` (port 5173)
|
||||||
|
- [backend/README.md](backend/README.md) — `uvicorn main:app --reload` (port 8000)
|
||||||
|
|
||||||
## Documentation
|
## Documentation
|
||||||
|
|
||||||
- [CONTRIBUTING.md](CONTRIBUTING.md) — how to contribute
|
- [CONTRIBUTING.md](CONTRIBUTING.md) — how to contribute
|
||||||
|
|||||||
@@ -13,3 +13,11 @@ services:
|
|||||||
timeout: 5s
|
timeout: 5s
|
||||||
retries: 3
|
retries: 3
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
frontend:
|
||||||
|
build: ./frontend
|
||||||
|
ports:
|
||||||
|
- "3000:80"
|
||||||
|
depends_on:
|
||||||
|
backend:
|
||||||
|
condition: service_healthy
|
||||||
|
restart: unless-stopped
|
||||||
@@ -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/',
|
||||||
|
],
|
||||||
|
};
|
||||||
@@ -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
|
||||||
@@ -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;"]
|
||||||
@@ -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.
|
||||||
@@ -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
|
||||||
@@ -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>
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
Generated
+7596
File diff suppressed because it is too large.
Load diff
@@ -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"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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,
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -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([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
export default {
|
||||||
|
plugins: {
|
||||||
|
tailwindcss: {},
|
||||||
|
autoprefixer: {},
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -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 |
@@ -0,0 +1,2 @@
|
|||||||
|
User-agent: *
|
||||||
|
Allow: /
|
||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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 |
@@ -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;
|
||||||
@@ -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;
|
||||||
@@ -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>
|
||||||
|
© {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;
|
||||||
@@ -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));
|
||||||
|
}
|
||||||
@@ -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>,
|
||||||
|
);
|
||||||
@@ -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;
|
||||||
@@ -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;
|
||||||
@@ -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;
|
||||||
@@ -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);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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;
|
||||||
@@ -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');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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();
|
||||||
|
});
|
||||||
@@ -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,
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
Vendored
+1
@@ -0,0 +1 @@
|
|||||||
|
/// <reference types="vite/client" />
|
||||||
@@ -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: [],
|
||||||
|
};
|
||||||
@@ -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" }]
|
||||||
|
}
|
||||||
@@ -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"]
|
||||||
|
}
|
||||||
@@ -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,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -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/**'],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
Reference in new issue
Block a user