feat: add React + TypeScript frontend with Vite, routing, tests and Docker setup
M3 frontend infrastructure for the newzy news application: - Vite + React 18 + TypeScript project (Node >=18) in frontend/ - React Router v6: BrowserRouter in App.tsx, routes for /, /articles, /articles/:id and /categories, Link/NavLink-based navigation - lucide-react icons (Home, FileText, Settings, Search, ...) in the responsive Header (desktop + mobile menu) and article components - Reusable components: ArticleCard, AuthorAvatar, CategoryBadge (CVA), Layout shell with backend API status indicator in the footer - Typed API client (fetch wrapper, ApiError, endpoint helpers) with types matching the backend models; sample-data fallback until the backend article endpoints exist - Tailwind CSS global/component styles, cn() helper (clsx + tailwind-merge) - Unit tests: Vitest + React Testing Library (23 tests, 100% statement coverage on components) - E2E tests: Playwright (9 tests) covering page shell, feed rendering, client-side navigation, article route and API interactions - ESLint (react + react-hooks + typescript) configured and passing - Multi-stage Dockerfile (Vite build -> Nginx) with SPA fallback and an /api/ proxy to the backend service; docker-compose frontend service on port 3000 in both frontend/ and the root docker-compose.yml - README with setup, API documentation, testing and Docker instructions
This commit is contained in:
1 parent
cbeac5e16b
commit
ffe19272b3
45 files changed
+9843
-4
No files matched your search
@@ -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" />
|
||||
Reference in new issue
Block a user