diff --git a/.github/workflows/jest.yml b/.github/workflows/backend_tests.yml similarity index 92% rename from .github/workflows/jest.yml rename to .github/workflows/backend_tests.yml index 8fb2c7eaa..5beeddace 100644 --- a/.github/workflows/jest.yml +++ b/.github/workflows/backend_tests.yml @@ -1,4 +1,4 @@ -name: Jest run +name: Backend tests on: push: @@ -7,7 +7,7 @@ on: branches: ['**'] jobs: - jest-tests: + backend-tests: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 diff --git a/.github/workflows/frontend_tests.yml b/.github/workflows/frontend_tests.yml new file mode 100644 index 000000000..94b82e282 --- /dev/null +++ b/.github/workflows/frontend_tests.yml @@ -0,0 +1,19 @@ +name: Frontend tests + +on: + push: + branches: ['**'] + pull_request: + branches: ['**'] + +jobs: + frontend-tests: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 24.x + cache: 'yarn' + - run: yarn install --frozen-lockfile + - run: npx vitest run --root apps/frontend diff --git a/apps/frontend/src/api/apiClient.ts b/apps/frontend/src/api/apiClient.ts index 2b19ea97b..30f61ad94 100644 --- a/apps/frontend/src/api/apiClient.ts +++ b/apps/frontend/src/api/apiClient.ts @@ -2,7 +2,7 @@ import axios, { type AxiosInstance } from 'axios'; import { fetchAuthSession } from 'aws-amplify/auth'; import { isAuthEnabled } from '../auth/auth.config'; -import type { Animal, CreateMatchBody, Match } from '../types'; +import type { Animal, CreateMatchBody, Match, Volunteer } from '../types'; const defaultBaseUrl = import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:3000'; @@ -50,6 +50,10 @@ export class ApiClient { return this.get('/api/animals') as Promise; } + public async getVolunteer(volunteerId: number): Promise { + return this.get(`/api/volunteers/${volunteerId}`) as Promise; + } + public async createMatch(body: CreateMatchBody): Promise { return this.post('/api/matches', body) as Promise; } diff --git a/apps/frontend/src/app.spec.tsx b/apps/frontend/src/app.spec.tsx index 95caf44df..9767fd8ae 100644 --- a/apps/frontend/src/app.spec.tsx +++ b/apps/frontend/src/app.spec.tsx @@ -2,14 +2,13 @@ import { render } from '@testing-library/react'; import App from './app'; +vi.mock('@api/apiClient', () => ({ + default: { getHello: vi.fn().mockResolvedValue('hello') }, +})); + describe('App', () => { it('should render successfully', () => { const { baseElement } = render(); expect(baseElement).toBeTruthy(); }); - - it('should have a greeting as the title', () => { - const { getByText } = render(); - expect(getByText(/Welcome frontend/gi)).toBeTruthy(); - }); }); diff --git a/apps/frontend/src/app.tsx b/apps/frontend/src/app.tsx index 666b9bbe3..50e2a746b 100644 --- a/apps/frontend/src/app.tsx +++ b/apps/frontend/src/app.tsx @@ -1,23 +1,41 @@ import { useEffect } from 'react'; -import { createBrowserRouter, RouterProvider } from 'react-router-dom'; +import { + createBrowserRouter, + RouterProvider, + type RouteObject, +} from 'react-router-dom'; import apiClient from '@api/apiClient'; import Root from '@containers/root'; +import Layout from '@containers/Layout'; import NotFound from '@containers/404'; import AnimalAvailability from '@pages/AnimalAvailability'; import { ROUTES } from './routes'; -const router = createBrowserRouter([ +// Every page is a child of Layout so the navbar renders once, above all pages. +// Page errors are caught by the inner errorElement so the navbar stays put; +// the outer one only catches errors from the layout itself. +export const routes: RouteObject[] = [ { - path: '/', - element: , + element: , errorElement: , + children: [ + { + errorElement: , + children: [ + { path: '/', element: }, + { + path: ROUTES.ANIMAL_AVAILABILITY, + element: , + }, + { path: '*', element: }, + ], + }, + ], }, - { - path: ROUTES.ANIMAL_AVAILABILITY, - element: , - }, -]); +]; + +const router = createBrowserRouter(routes); export const App: React.FC = () => { useEffect(() => { diff --git a/apps/frontend/src/components/Navbar.tsx b/apps/frontend/src/components/Navbar.tsx new file mode 100644 index 000000000..6459eccfa --- /dev/null +++ b/apps/frontend/src/components/Navbar.tsx @@ -0,0 +1,97 @@ +import { useEffect, useState } from 'react'; +import { Button, Flex, Image, Text } from '@chakra-ui/react'; + +import apiClient from '@api/apiClient'; +import type { Volunteer } from '../types'; +import { useVolunteerId } from '@utils/useVolunteerId'; +import { getAvatarColor, getInitials } from '@utils/volunteer'; +import logo from '../assets/mspca-logo.png'; + +/** Site-wide header: MSPCA logo and the current volunteer's profile button. */ +const Navbar: React.FC = () => { + const volunteerId = useVolunteerId(); + const [loaded, setLoaded] = useState(null); + const volunteer = loaded?.volunteerId === volunteerId ? loaded : null; + + useEffect(() => { + if (volunteerId === null) return; + + let cancelled = false; + apiClient + .getVolunteer(volunteerId) + .then((result) => { + if (!cancelled) setLoaded(result); + }) + .catch((err: unknown) => { + console.warn(`Could not load volunteer ${volunteerId}`, err); + }); + return () => { + cancelled = true; + }; + }, [volunteerId]); + + return ( + + MSPCA - Kindness and Care for Animals + {/* TODO: link to the volunteer profile page once it exists. */} + + + ); +}; + +export default Navbar; diff --git a/apps/frontend/src/components/modals/AnimalModal.tsx b/apps/frontend/src/components/modals/AnimalModal.tsx index 6e6e407dd..3d8429a8e 100644 --- a/apps/frontend/src/components/modals/AnimalModal.tsx +++ b/apps/frontend/src/components/modals/AnimalModal.tsx @@ -14,13 +14,10 @@ import { ExternalLink, House } from 'lucide-react'; import apiClient from '@api/apiClient'; import type { Animal } from '../../types'; import { HOMEBASE_ADDRESSES, formatAge } from '@utils/animals'; +import { useVolunteerId } from '@utils/useVolunteerId'; import { PLACEHOLDER_IMAGE } from '../AnimalCard'; import RestrictionTag from '../RestrictionTag'; -// TODO: replace with the logged-in volunteer's ID once the frontend has access -// to the current user's profile. -const CURRENT_VOLUNTEER_ID = 1; - interface AnimalModalProps { animal: Animal | null; onClose: () => void; @@ -42,6 +39,8 @@ const AnimalModal: React.FC = ({ animal, onClose }) => { const [submitting, setSubmitting] = useState(false); const [requested, setRequested] = useState(false); const [error, setError] = useState(null); + // TEMPORARY: comes from the URL until sign-in is implemented. + const volunteerId = useVolunteerId(); // Reset the form when a different animal is opened. const [formAnimalId, setFormAnimalId] = useState(animal?.animalId); @@ -54,12 +53,12 @@ const AnimalModal: React.FC = ({ animal, onClose }) => { } const handleRequest = async () => { - if (!animal) return; + if (!animal || volunteerId === null) return; setSubmitting(true); setError(null); try { await apiClient.createMatch({ - volunteerId: CURRENT_VOLUNTEER_ID, + volunteerId, chameleonAnimalId: animal.chameleonAnimalId, additionalComments: comments.trim() || undefined, }); @@ -328,6 +327,7 @@ const AnimalModal: React.FC = ({ animal, onClose }) => { lineHeight="24px" onClick={handleRequest} loading={submitting} + disabled={volunteerId === null} > Apply diff --git a/apps/frontend/src/containers/404.tsx b/apps/frontend/src/containers/404.tsx index d6a08187e..1b5246dd3 100644 --- a/apps/frontend/src/containers/404.tsx +++ b/apps/frontend/src/containers/404.tsx @@ -3,14 +3,24 @@ import { useRouteError } from 'react-router-dom'; import { getErrorMessage } from '@utils/router'; const NotFound: React.FC = () => { - const errorMessage = getErrorMessage(useRouteError()); + const error = useRouteError(); + + // Rendered by the catch-all route for unknown URLs, so there is no error. + if (error == null) { + return ( +
+

Page not found

+

Sorry, we couldn't find the page you're looking for.

+
+ ); + } return (

Oops!

Sorry, an unexpected error has occurred.

- {errorMessage} + {getErrorMessage(error)}

); diff --git a/apps/frontend/src/containers/Layout.tsx b/apps/frontend/src/containers/Layout.tsx new file mode 100644 index 000000000..37c84e7f0 --- /dev/null +++ b/apps/frontend/src/containers/Layout.tsx @@ -0,0 +1,17 @@ +import { Flex } from '@chakra-ui/react'; +import { Outlet } from 'react-router-dom'; + +import Navbar from '@components/Navbar'; + +/** + * Shared app shell: the navbar sits above every page. The column fills the + * viewport so pages can grow into the remaining height with `flex="1"`. + */ +const Layout: React.FC = () => ( + + + + +); + +export default Layout; diff --git a/apps/frontend/src/pages/AnimalAvailability.tsx b/apps/frontend/src/pages/AnimalAvailability.tsx index 325d8af0d..4c37f02ee 100644 --- a/apps/frontend/src/pages/AnimalAvailability.tsx +++ b/apps/frontend/src/pages/AnimalAvailability.tsx @@ -4,7 +4,6 @@ import { Button, Flex, Heading, - Image, SimpleGrid, Spinner, Text, @@ -20,70 +19,6 @@ import { matchesFilters, type AnimalFilterState, } from '@utils/animals'; -import logo from '../assets/mspca-logo.png'; - -/** - * The top bar of the page: the MSPCA logo on the left and the volunteer's - * profile avatar and "My Profile" label on the right. The initials are - * hard-coded for now until the logged-in volunteer is available to the - * frontend. - */ -const PageHeader: React.FC = () => ( - - MSPCA - Kindness and Care for Animals - - - {/* TODO: use the logged-in volunteer's initials */} - - MW - - - - My Profile - - - -); /** * Page where volunteers browse the animals that are available to foster. @@ -133,8 +68,7 @@ const AnimalAvailability: React.FC = () => { ); return ( - - + {String(useVolunteerId())}; + +const renderAt = (route: string) => + render( + + + , + ); + +describe('useVolunteerId', () => { + it('reads volunteerId from the query string', () => { + expect(renderAt('/x?volunteerId=7').getByText('7')).toBeTruthy(); + }); + + it('returns null when volunteerId is missing', () => { + expect(renderAt('/x').getByText('null')).toBeTruthy(); + }); + + it('returns null when volunteerId is not a valid ID', () => { + expect(renderAt('/x?volunteerId=abc').getByText('null')).toBeTruthy(); + }); +}); diff --git a/apps/frontend/src/utils/useVolunteerId.ts b/apps/frontend/src/utils/useVolunteerId.ts new file mode 100644 index 000000000..3f3a1a809 --- /dev/null +++ b/apps/frontend/src/utils/useVolunteerId.ts @@ -0,0 +1,12 @@ +import { useSearchParams } from 'react-router-dom'; + +import { parseVolunteerId } from './volunteer'; + +/** + * The current volunteer's ID, read from the `?volunteerId=` query param. + * TEMPORARY: replace with the signed-in volunteer once sign-in is implemented. + */ +export const useVolunteerId = (): number | null => { + const [searchParams] = useSearchParams(); + return parseVolunteerId(searchParams.get('volunteerId')); +}; diff --git a/apps/frontend/src/utils/volunteer.spec.ts b/apps/frontend/src/utils/volunteer.spec.ts new file mode 100644 index 000000000..2b9f7c2a2 --- /dev/null +++ b/apps/frontend/src/utils/volunteer.spec.ts @@ -0,0 +1,65 @@ +import { colors } from '../theme'; +import { + AVATAR_COLORS, + getAvatarColor, + getInitials, + parseVolunteerId, +} from './volunteer'; + +describe('getInitials', () => { + it('uses the first letter of each name', () => { + expect(getInitials('Matt', 'Wong')).toBe('MW'); + }); + + it('trims whitespace and uppercases', () => { + expect(getInitials(' anna ', 'lee')).toBe('AL'); + }); + + it('returns an empty string when both names are empty', () => { + expect(getInitials('', '')).toBe(''); + }); + + it('returns a single initial when the last name is empty', () => { + expect(getInitials('Cher', '')).toBe('C'); + }); +}); + +describe('getAvatarColor', () => { + it('uses the Trello label colors in theme order', () => { + expect(getAvatarColor(0)).toBe('trello.noRestrictions'); + expect(getAvatarColor(1)).toBe('trello.dogFreeHome'); + }); + + it('wraps around the palette', () => { + expect(getAvatarColor(7)).toBe('trello.noRestrictions'); + }); + + it('includes every Trello label color', () => { + expect(AVATAR_COLORS).toEqual( + Object.keys(colors.trello).map((key) => `trello.${key}`), + ); + }); + + it('is stable for the same volunteer', () => { + expect(getAvatarColor(42)).toBe(getAvatarColor(42)); + }); +}); + +describe('parseVolunteerId', () => { + it('parses a positive integer', () => { + expect(parseVolunteerId('12')).toBe(12); + }); + + it.each([ + null, + '', + 'abc', + '0', + '-3', + '1.5', + '12abc', + '99999999999999999999999', + ])('returns null for %j', (raw) => { + expect(parseVolunteerId(raw)).toBeNull(); + }); +}); diff --git a/apps/frontend/src/utils/volunteer.ts b/apps/frontend/src/utils/volunteer.ts new file mode 100644 index 000000000..9788f0639 --- /dev/null +++ b/apps/frontend/src/utils/volunteer.ts @@ -0,0 +1,21 @@ +import { colors } from '../theme'; + +// Avatars reuse the Trello label colors, so changing those in theme.ts +// updates avatars too. +export const AVATAR_COLORS: readonly string[] = Object.keys(colors.trello).map( + (key) => `trello.${key}`, +); + +const initial = (name: string): string => name.trim().charAt(0).toUpperCase(); + +export const getInitials = (firstName: string, lastName: string): string => + initial(firstName) + initial(lastName); + +export const getAvatarColor = (volunteerId: number): string => + AVATAR_COLORS[volunteerId % AVATAR_COLORS.length]; + +export const parseVolunteerId = (raw: string | null): number | null => { + if (raw === null || !/^\d+$/.test(raw)) return null; + const id = Number(raw); + return id > 0 && Number.isSafeInteger(id) ? id : null; +};