From a76b0dbf262941696b2402ba90ab21fcc8b84775 Mon Sep 17 00:00:00 2001 From: Kong Meng Xiong Date: Wed, 4 Nov 2026 19:40:01 -0800 Subject: [PATCH] Created filters/sorting for bounties --- app/posts/FilterPopover.tsx | 225 +++++++++++++++++++ app/posts/PostsBrowser.tsx | 120 ++++++++++ app/posts/page.tsx | 14 +- app/posts/post-data.ts | 52 ++++- app/posts/post-filters.ts | 67 ++++++ app/posts/posts.module.css | 204 +++++++++++++++++ generated/prisma/internal/class.ts | 4 +- generated/prisma/internal/prismaNamespace.ts | 12 +- tests/unit/filter-popover.test.tsx | 85 +++++++ tests/unit/post-data.test.ts | 126 +++++++++++ tests/unit/posts-browser.test.tsx | 145 ++++++++++++ tests/unit/posts-list.test.tsx | 10 + 12 files changed, 1037 insertions(+), 27 deletions(-) create mode 100644 app/posts/FilterPopover.tsx create mode 100644 app/posts/PostsBrowser.tsx create mode 100644 app/posts/post-filters.ts create mode 100644 tests/unit/filter-popover.test.tsx create mode 100644 tests/unit/posts-browser.test.tsx diff --git a/app/posts/FilterPopover.tsx b/app/posts/FilterPopover.tsx new file mode 100644 index 0000000..10f7200 --- /dev/null +++ b/app/posts/FilterPopover.tsx @@ -0,0 +1,225 @@ +'use client' + +import { useEffect, useRef, useState } from 'react' + +import { + defaultPostFilters, + type PostFilters, + type PostSortOrder, +} from './post-filters' +import styles from './posts.module.css' + +type FilterPopoverProps = { + filters: PostFilters + onApplyFilters: (filters: PostFilters) => void +} + +export function FilterPopover({ filters, onApplyFilters }: FilterPopoverProps) { + const [isOpen, setIsOpen] = useState(false) + const closeButtonRef = useRef(null) + const formRef = useRef(null) + + useEffect(() => { + if (!isOpen) return + + closeButtonRef.current?.focus() + + function closeOnEscape(event: KeyboardEvent) { + if (event.key === 'Escape') setIsOpen(false) + } + + document.addEventListener('keydown', closeOnEscape) + return () => document.removeEventListener('keydown', closeOnEscape) + }, [isOpen]) + + return ( +
+ + + {isOpen && ( +
{ + event.preventDefault() + const formData = new FormData(event.currentTarget) + const value = formData.get('sortOrder') + const nextOrder: PostSortOrder = + value === 'oldest' || + value === 'earliest-event' || + value === 'latest-event' + ? value + : 'newest' + const availability = formData.get('availability') + const parsedAvailability = Number(availability) + const nextAvailability = + typeof availability === 'string' && + availability.trim() !== '' && + Number.isInteger(parsedAvailability) && + parsedAvailability > 0 + ? parsedAvailability + : null + const difficulty = formData + .getAll('difficulty') + .filter((value): value is PostFilters['difficulty'][number] => + ['EASY', 'MEDIUM', 'NORMAL', 'HARD', 'EXTRA_HARD'].includes( + value as string, + ), + ) + onApplyFilters({ + search: String(formData.get('search') ?? '').trim(), + location: String(formData.get('location') ?? ''), + availability: nextAvailability, + difficulty, + sortOrder: nextOrder, + }) + setIsOpen(false) + }} + ref={formRef} + role="dialog" + aria-modal="true" + aria-labelledby="filter-title" + > +
+
+

Filter posts

+

Find a community task that fits your day.

+
+ +
+ +
+
+ + +
+
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ Difficulty + + + + + +
+
+ +
+ + +
+
+ )} +
+ ) +} diff --git a/app/posts/PostsBrowser.tsx b/app/posts/PostsBrowser.tsx new file mode 100644 index 0000000..7971930 --- /dev/null +++ b/app/posts/PostsBrowser.tsx @@ -0,0 +1,120 @@ +'use client' + +import { useState } from 'react' + +import { FilterPopover } from './FilterPopover' +import type { PostCardData } from './post-data' +import { + defaultPostFilters, + filterPosts, + sortPosts, + type PostSortOrder, +} from './post-filters' +import { PostsList } from './PostsList' +import styles from './posts.module.css' + +type ActiveFilterKey = + 'search' | 'location' | 'availability' | 'difficulty' | 'sortOrder' + +type PostsBrowserProps = { + posts: PostCardData[] +} + +export function PostsBrowser({ posts }: PostsBrowserProps) { + const [filters, setFilters] = useState(defaultPostFilters) + const visiblePosts = sortPosts(filterPosts(posts, filters), filters.sortOrder) + const activeFilters: Array<{ key: ActiveFilterKey; label: string }> = [] + + if (filters.search.trim()) { + activeFilters.push({ + key: 'search', + label: `Search: ${filters.search.trim()}`, + }) + } + if (filters.location.trim()) { + activeFilters.push({ + key: 'location', + label: `Location: ${filters.location.trim()}`, + }) + } + if (filters.availability !== null) { + activeFilters.push({ + key: 'availability', + label: `At least ${filters.availability} spots`, + }) + } + for (const difficulty of filters.difficulty) { + activeFilters.push({ + key: 'difficulty', + label: `Difficulty: ${formatDifficulty(difficulty)}`, + }) + } + if (filters.sortOrder !== defaultPostFilters.sortOrder) { + activeFilters.push({ + key: 'sortOrder', + label: `Sort: ${formatSortOrder(filters.sortOrder)}`, + }) + } + + function removeFilter(key: ActiveFilterKey) { + setFilters((current) => { + if (key === 'search') return { ...current, search: '' } + if (key === 'difficulty') return { ...current, difficulty: [] } + if (key === 'location') return { ...current, location: '' } + if (key === 'availability') return { ...current, availability: null } + return { ...current, sortOrder: defaultPostFilters.sortOrder } + }) + } + + return ( + <> +
+ + +
+ {activeFilters.length > 0 && ( +
+ {activeFilters.map((filter) => ( + + ))} + +
+ )} +
+ +
+ + ) +} + +function formatDifficulty(difficulty: PostCardData['difficulty']) { + return difficulty + .toLowerCase() + .replace('_', ' ') + .replace(/\b\w/g, (letter) => letter.toUpperCase()) +} + +function formatSortOrder(sortOrder: PostSortOrder) { + return { + newest: 'Most recent', + oldest: 'Oldest', + 'earliest-event': 'Earliest event', + 'latest-event': 'Latest event', + }[sortOrder] +} diff --git a/app/posts/page.tsx b/app/posts/page.tsx index 8d7a6d6..16c7a86 100644 --- a/app/posts/page.tsx +++ b/app/posts/page.tsx @@ -1,5 +1,5 @@ -import { PostsList } from './PostsList' import { getPublicPostCards } from './post-data' +import { PostsBrowser } from './PostsBrowser' import styles from './posts.module.css' export default async function PostsPage() { @@ -11,17 +11,7 @@ export default async function PostsPage() {

Posts

-
- - -
-
- -
+ ) diff --git a/app/posts/post-data.ts b/app/posts/post-data.ts index 2136982..400a188 100644 --- a/app/posts/post-data.ts +++ b/app/posts/post-data.ts @@ -1,16 +1,27 @@ export type PostListingRecord = { id: string title: string + description: string location: string imageUrl: string | null + createdAt: Date + scheduledAt: Date maximumVolunteers: number currentVolunteers: number + difficulty: 'EASY' | 'MEDIUM' | 'NORMAL' | 'HARD' | 'EXTRA_HARD' } export type PostCardData = Pick< PostListingRecord, 'id' | 'title' | 'location' | 'imageUrl' -> +> & { + description?: string + createdAt: string + scheduledAt: string + maximumVolunteers: number + currentVolunteers: number + difficulty: PostListingRecord['difficulty'] +} export interface PostListingSource { listPublicPosts(): Promise @@ -28,9 +39,13 @@ const databaseSource: PostListingSource = { select: { id: true, title: true, + description: true, locationLabel: true, imageUrl: true, + createdAt: true, + scheduledAt: true, maxVolunteers: true, + difficulty: true, _count: { select: { volunteerAttendances: { @@ -44,10 +59,14 @@ const databaseSource: PostListingSource = { return bounties.map((bounty) => ({ id: bounty.id, title: bounty.title, + description: bounty.description, location: bounty.locationLabel, imageUrl: bounty.imageUrl, + createdAt: bounty.createdAt, + scheduledAt: bounty.scheduledAt, maximumVolunteers: bounty.maxVolunteers, currentVolunteers: bounty._count.volunteerAttendances, + difficulty: bounty.difficulty, })) }, } @@ -70,12 +89,31 @@ export async function getPublicPostCards( record.currentVolunteers >= 0 && record.currentVolunteers < record.maximumVolunteers, ) - .map(({ id, title, location, imageUrl }) => ({ - id, - title, - location, - imageUrl: getSafeImageUrl(imageUrl), - })) + .map( + ({ + id, + title, + description, + location, + imageUrl, + createdAt, + scheduledAt, + maximumVolunteers, + currentVolunteers, + difficulty, + }) => ({ + id, + title, + description, + location, + imageUrl: getSafeImageUrl(imageUrl), + createdAt: createdAt.toISOString(), + scheduledAt: scheduledAt.toISOString(), + maximumVolunteers, + currentVolunteers, + difficulty, + }), + ) } function getSafeImageUrl(imageUrl: string | null): string | null { diff --git a/app/posts/post-filters.ts b/app/posts/post-filters.ts new file mode 100644 index 0000000..8bdfab5 --- /dev/null +++ b/app/posts/post-filters.ts @@ -0,0 +1,67 @@ +import type { PostCardData, PostListingRecord } from './post-data' + +export type PostSortOrder = + 'newest' | 'oldest' | 'earliest-event' | 'latest-event' + +export type PostAvailability = number | null + +export type PostFilters = { + search: string + location: string + availability: PostAvailability + difficulty: PostListingRecord['difficulty'][] + sortOrder: PostSortOrder +} + +export const defaultPostFilters: PostFilters = { + search: '', + location: '', + availability: null, + difficulty: [], + sortOrder: 'newest', +} + +export function filterPosts( + posts: PostCardData[], + filters: PostFilters, +): PostCardData[] { + const location = filters.location.trim().toLowerCase() + const search = filters.search.trim().toLowerCase() + + return posts.filter((post) => { + const availableSpots = post.maximumVolunteers - post.currentVolunteers + const matchesLocation = + !location || post.location.toLowerCase().includes(location) + const searchableText = + `${post.title} ${post.description ?? ''}`.toLowerCase() + const matchesSearch = !search || searchableText.includes(search) + const matchesAvailability = + filters.availability === null || availableSpots >= filters.availability + const matchesDifficulty = + filters.difficulty.length === 0 || + filters.difficulty.includes(post.difficulty) + + return ( + matchesSearch && + matchesLocation && + matchesAvailability && + matchesDifficulty + ) + }) +} + +export function sortPosts( + posts: PostCardData[], + order: PostSortOrder, +): PostCardData[] { + return [...posts].sort((a, b) => { + const field = + order === 'earliest-event' || order === 'latest-event' + ? 'scheduledAt' + : 'createdAt' + const difference = Date.parse(a[field]) - Date.parse(b[field]) + return order === 'newest' || order === 'latest-event' + ? -difference + : difference + }) +} diff --git a/app/posts/posts.module.css b/app/posts/posts.module.css index d221567..1f492a8 100644 --- a/app/posts/posts.module.css +++ b/app/posts/posts.module.css @@ -16,12 +16,179 @@ } .controls { + position: relative; display: grid; grid-template-columns: 1fr 1fr; gap: 0.75rem; margin: 1.25rem 0; } +.filterControl { + position: relative; +} + +.filterButton, +.filterClose, +.clearButton, +.applyButton { + font: inherit; + cursor: pointer; +} + +.filterButton { + width: 100%; + min-height: 2.75rem; + padding: 0.5rem 0.75rem; + color: var(--ink); + border: 1px solid var(--ink); + border-radius: 0; + background: var(--canvas); + text-align: left; +} + +.filterButton:hover, +.filterButton[aria-expanded='true'] { + background: var(--accent-soft); +} + +.filterPopover { + position: absolute; + z-index: 2; + top: calc(100% + 0.5rem); + left: 0; + width: min(32rem, calc(200% + 0.75rem)); + padding: 1rem; + border: 1px solid var(--ink); + background: #fffdf8; + box-shadow: 0.4rem 0.4rem 0 var(--accent-soft); +} + +.filterHeader { + display: flex; + align-items: start; + justify-content: space-between; + gap: 1rem; + padding-bottom: 1rem; + border-bottom: 1px solid var(--line); +} + +.filterHeader h2 { + margin: 0; + font-family: Arial, Helvetica, sans-serif; + font-size: 1.15rem; + font-weight: 700; +} + +.filterHeader p { + margin-top: 0.25rem; + color: var(--muted); + font-size: 0.875rem; +} + +.filterClose { + width: 2rem; + height: 2rem; + border: 1px solid var(--line); + color: var(--ink); + background: var(--canvas); + font-size: 1.5rem; + line-height: 1; +} + +.filterFields { + display: grid; + gap: 1rem; + padding: 1rem 0; +} + +.filterField, +.filterFieldset { + display: grid; + gap: 0.4rem; + margin: 0; + padding: 0; + border: 0; +} + +.filterField label, +.filterFieldset legend { + font-size: 0.875rem; + font-weight: 700; +} + +.filterField input, +.filterField select { + width: 100%; + min-height: 2.5rem; + padding: 0.5rem 0.75rem; + border: 1px solid var(--line); + border-radius: 0; + color: var(--ink); + background: #fffefa; + font: inherit; +} + +.filterFieldset { + grid-template-columns: repeat(3, 1fr); + gap: 0.5rem; +} + +.filterFieldset legend { + grid-column: 1 / -1; +} + +.filterFieldset label { + display: flex; + align-items: center; + gap: 0.35rem; + color: var(--muted); + font-size: 0.875rem; +} + +.filterFieldset input { + accent-color: var(--accent); +} + +.filterActions { + display: flex; + align-items: center; + justify-content: space-between; + gap: 0.75rem; + padding-top: 1rem; + border-top: 1px solid var(--line); +} + +.clearButton, +.applyButton { + min-height: 2.75rem; + padding: 0.5rem 0.75rem; + border: 1px solid var(--accent); + border-radius: 0; + font-weight: 700; +} + +.clearButton { + color: var(--ink); + background: transparent; + border-color: transparent; +} + +.applyButton { + color: var(--ink); + background: var(--accent-soft); +} + +.filterButton:focus-visible, +.filterClose:focus-visible, +.filterField input:focus-visible, +.filterField select:focus-visible, +.filterFieldset input:focus-visible, +.clearButton:focus-visible, +.applyButton:focus-visible { + outline: 3px solid #236e69; + outline-offset: 3px; +} + .controls button { font: inherit; color: var(--ink); @@ -41,6 +208,43 @@ opacity: 1; } +.activeFilters { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.5rem; + margin: -0.5rem 0 1.25rem; +} + +.filterChip, +.clearFiltersButton { + min-height: 2rem; + padding: 0.35rem 0.6rem; + border: 1px solid var(--line); + border-radius: 0; + color: var(--ink); + background: var(--canvas); + font: inherit; + font-size: 0.875rem; + cursor: pointer; +} + +.filterChip:hover, +.clearFiltersButton:hover { + background: var(--accent-soft); +} + +.clearFiltersButton { + border-color: var(--accent); + font-weight: 700; +} + +.filterChip:focus-visible, +.clearFiltersButton:focus-visible { + outline: 3px solid #236e69; + outline-offset: 3px; +} + .listViewport { border-top: 1px solid var(--ink); } diff --git a/generated/prisma/internal/class.ts b/generated/prisma/internal/class.ts index 9a2cdbd..014daa8 100644 --- a/generated/prisma/internal/class.ts +++ b/generated/prisma/internal/class.ts @@ -17,8 +17,8 @@ import type * as Prisma from "./prismaNamespace" const config: runtime.GetPrismaClientConfig = { "previewFeatures": [], - "clientVersion": "7.10.0", - "engineVersion": "0edf323efd1d98336f3f0a68684b56f689b900d3", + "clientVersion": "7.10.1", + "engineVersion": "d1b3f377ca835d73fd50954a5e22128b9ebdd6b8", "activeProvider": "postgresql", "inlineSchema": "generator client {\n provider = \"prisma-client\"\n output = \"../generated/prisma\"\n}\n\ndatasource db {\n provider = \"postgresql\"\n}\n\nmodel User {\n id String @id @default(cuid())\n email String @unique\n displayName String\n passwordHash String\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n postedBounties Bounty[] @relation(\"BountyPoster\")\n volunteerAttendances BountyVolunteer[]\n}\n\nenum BountyStatus {\n OPEN\n FULL\n FINISHED\n CANCELLED\n EXPIRED\n}\n\nenum BountyDifficulty {\n EASY\n MEDIUM\n NORMAL\n HARD\n EXTRA_HARD\n}\n\nenum RequirementLevel {\n REQUIRED\n RECOMMENDED\n}\n\nenum VolunteerAttendanceStatus {\n JOINED\n WITHDRAWN\n}\n\nmodel Bounty {\n id String @id @default(cuid())\n title String\n description String\n locationLabel String\n imageUrl String?\n latitude Decimal? @db.Decimal(9, 6)\n longitude Decimal? @db.Decimal(9, 6)\n scheduledAt DateTime\n deadline DateTime\n maxVolunteers Int\n payPerVolunteer Decimal @db.Decimal(10, 2)\n difficulty BountyDifficulty\n status BountyStatus @default(OPEN)\n posterId String\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n finishedAt DateTime?\n verifiedAt DateTime?\n cancellationReason String?\n poster User @relation(\"BountyPoster\", fields: [posterId], references: [id], onDelete: Restrict)\n volunteerAttendances BountyVolunteer[]\n skillRequirements BountySkillRequirement[]\n equipmentRequirements BountyEquipmentRequirement[]\n\n @@index([posterId])\n @@index([status, deadline])\n @@index([scheduledAt])\n}\n\nmodel BountyVolunteer {\n bountyId String\n volunteerId String\n status VolunteerAttendanceStatus @default(JOINED)\n joinedAt DateTime @default(now())\n withdrawnAt DateTime?\n bounty Bounty @relation(fields: [bountyId], references: [id], onDelete: Cascade)\n volunteer User @relation(fields: [volunteerId], references: [id], onDelete: Cascade)\n\n @@id([bountyId, volunteerId])\n @@index([volunteerId, status])\n @@index([bountyId, status])\n}\n\nmodel BountySkillRequirement {\n id String @id @default(cuid())\n bountyId String\n name String\n level RequirementLevel\n bounty Bounty @relation(fields: [bountyId], references: [id], onDelete: Cascade)\n\n @@unique([bountyId, name])\n}\n\nmodel BountyEquipmentRequirement {\n id String @id @default(cuid())\n bountyId String\n name String\n level RequirementLevel\n bounty Bounty @relation(fields: [bountyId], references: [id], onDelete: Cascade)\n\n @@unique([bountyId, name])\n}\n", "runtimeDataModel": { diff --git a/generated/prisma/internal/prismaNamespace.ts b/generated/prisma/internal/prismaNamespace.ts index 1be1111..f5a9bf1 100644 --- a/generated/prisma/internal/prismaNamespace.ts +++ b/generated/prisma/internal/prismaNamespace.ts @@ -80,12 +80,12 @@ export type PrismaVersion = { } /** - * Prisma Client JS version: 7.10.0 - * Query Engine version: 0edf323efd1d98336f3f0a68684b56f689b900d3 + * Prisma Client JS version: 7.10.1 + * Query Engine version: d1b3f377ca835d73fd50954a5e22128b9ebdd6b8 */ export const prismaVersion: PrismaVersion = { - client: "7.10.0", - engine: "0edf323efd1d98336f3f0a68684b56f689b900d3" + client: "7.10.1", + engine: "d1b3f377ca835d73fd50954a5e22128b9ebdd6b8" } /** @@ -988,14 +988,14 @@ export type ListIntFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, * Reference to a field of type 'BountyDifficulty' */ export type EnumBountyDifficultyFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'BountyDifficulty'> - + /** * Reference to a field of type 'BountyDifficulty[]' */ export type ListEnumBountyDifficultyFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'BountyDifficulty[]'> - + /** diff --git a/tests/unit/filter-popover.test.tsx b/tests/unit/filter-popover.test.tsx new file mode 100644 index 0000000..efdc9ca --- /dev/null +++ b/tests/unit/filter-popover.test.tsx @@ -0,0 +1,85 @@ +// @vitest-environment jsdom + +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { FilterPopover } from '../../app/posts/FilterPopover' +import { defaultPostFilters } from '../../app/posts/post-filters' + +afterEach(cleanup) + +describe('FilterPopover', () => { + it('opens the filter panel and exposes labeled controls', () => { + render( + undefined} + />, + ) + + fireEvent.click(screen.getByRole('button', { name: 'Filters' })) + + expect(screen.getByRole('dialog', { name: 'Filter posts' })).toBeTruthy() + expect(screen.getByLabelText('Location')).toBeTruthy() + expect(screen.getByLabelText('Search posts')).toBeTruthy() + expect(screen.getByLabelText('Availability')).toBeTruthy() + expect(screen.getByLabelText('Sort posts by')).toBeTruthy() + expect(screen.getByRole('button', { name: 'Apply filters' })).toBeTruthy() + }) + + it('closes after applying filters', () => { + render( + undefined} + />, + ) + + fireEvent.click(screen.getByRole('button', { name: 'Filters' })) + fireEvent.click(screen.getByRole('button', { name: 'Apply filters' })) + + expect(screen.queryByRole('dialog', { name: 'Filter posts' })).toBeNull() + }) + + it('passes a typed minimum availability to the filters', () => { + const onApplyFilters = vi.fn() + render( + , + ) + + fireEvent.click(screen.getByRole('button', { name: 'Filters' })) + fireEvent.change(screen.getByLabelText('Availability'), { + target: { value: '4' }, + }) + fireEvent.click(screen.getByRole('button', { name: 'Apply filters' })) + + expect(onApplyFilters).toHaveBeenCalledWith({ + ...defaultPostFilters, + availability: 4, + }) + }) + + it('passes the search query to the filters', () => { + const onApplyFilters = vi.fn() + render( + , + ) + + fireEvent.click(screen.getByRole('button', { name: 'Filters' })) + fireEvent.change(screen.getByLabelText('Search posts'), { + target: { value: ' Park ' }, + }) + fireEvent.click(screen.getByRole('button', { name: 'Apply filters' })) + + expect(onApplyFilters).toHaveBeenCalledWith({ + ...defaultPostFilters, + search: 'Park', + }) + }) +}) diff --git a/tests/unit/post-data.test.ts b/tests/unit/post-data.test.ts index dd083da..769607f 100644 --- a/tests/unit/post-data.test.ts +++ b/tests/unit/post-data.test.ts @@ -4,6 +4,8 @@ import { getPublicPostCards, type PostListingSource, } from '../../app/posts/post-data' +import { filterPosts, sortPosts } from '../../app/posts/post-filters' +import { defaultPostFilters } from '../../app/posts/post-filters' describe('getPublicPostCards', () => { it('omits full posts and returns only card-safe fields', async () => { @@ -13,18 +15,26 @@ describe('getPublicPostCards', () => { { id: 'open-task', title: 'Park cleanup', + description: 'Help neighbors restore a community park.', location: 'Bidwell Park', imageUrl: '/posts/park-cleanup.svg', + createdAt: new Date('2026-01-02T00:00:00.000Z'), + scheduledAt: new Date('2026-02-02T10:00:00.000Z'), maximumVolunteers: 5, currentVolunteers: 3, + difficulty: 'EASY', }, { id: 'full-task', title: 'Food drive', + description: 'Sort donated food for local families.', location: 'Downtown Chico', imageUrl: null, + createdAt: new Date('2026-01-01T00:00:00.000Z'), + scheduledAt: new Date('2026-02-01T10:00:00.000Z'), maximumVolunteers: 4, currentVolunteers: 4, + difficulty: 'HARD', }, ] }, @@ -34,8 +44,14 @@ describe('getPublicPostCards', () => { { id: 'open-task', title: 'Park cleanup', + description: 'Help neighbors restore a community park.', location: 'Bidwell Park', imageUrl: '/posts/park-cleanup.svg', + createdAt: '2026-01-02T00:00:00.000Z', + scheduledAt: '2026-02-02T10:00:00.000Z', + maximumVolunteers: 5, + currentVolunteers: 3, + difficulty: 'EASY', }, ]) }) @@ -47,10 +63,14 @@ describe('getPublicPostCards', () => { { id: 'task', title: 'Park cleanup', + description: 'Help neighbors restore a community park.', location: 'Bidwell Park', imageUrl: 'http://images.example.test/park.jpg', + createdAt: new Date('2026-01-02T00:00:00.000Z'), + scheduledAt: new Date('2026-02-02T10:00:00.000Z'), maximumVolunteers: 5, currentVolunteers: 0, + difficulty: 'MEDIUM', }, ] }, @@ -60,4 +80,110 @@ describe('getPublicPostCards', () => { { imageUrl: null }, ]) }) + + it('sorts cards from newest or oldest creation time', async () => { + const source: PostListingSource = { + async listPublicPosts() { + return [ + { + id: 'older-task', + title: 'Older task', + description: 'An older community task.', + location: 'Chico', + imageUrl: null, + createdAt: new Date('2026-01-01T00:00:00.000Z'), + scheduledAt: new Date('2026-02-01T10:00:00.000Z'), + maximumVolunteers: 5, + currentVolunteers: 0, + difficulty: 'HARD', + }, + { + id: 'newer-task', + title: 'Newer task', + description: 'A newer community task.', + location: 'Chico', + imageUrl: null, + createdAt: new Date('2026-01-02T00:00:00.000Z'), + scheduledAt: new Date('2026-02-03T10:00:00.000Z'), + maximumVolunteers: 5, + currentVolunteers: 0, + difficulty: 'EASY', + }, + ] + }, + } + + const posts = await getPublicPostCards(source) + + expect(sortPosts(posts, 'newest').map((post) => post.id)).toEqual([ + 'newer-task', + 'older-task', + ]) + expect(sortPosts(posts, 'oldest').map((post) => post.id)).toEqual([ + 'older-task', + 'newer-task', + ]) + expect(sortPosts(posts, 'earliest-event').map((post) => post.id)).toEqual([ + 'older-task', + 'newer-task', + ]) + expect(sortPosts(posts, 'latest-event').map((post) => post.id)).toEqual([ + 'newer-task', + 'older-task', + ]) + }) + + it('filters by location, available spots, and difficulty', () => { + const posts = [ + { + id: 'park', + title: 'Park cleanup', + description: 'Help neighbors restore a community park.', + location: 'Bidwell Park', + imageUrl: null, + createdAt: '2026-01-02T00:00:00.000Z', + scheduledAt: '2026-02-02T10:00:00.000Z', + maximumVolunteers: 5, + currentVolunteers: 3, + difficulty: 'EASY' as const, + }, + { + id: 'pantry', + title: 'Food pantry', + description: 'Sort donations for local families.', + location: 'Downtown Chico', + imageUrl: null, + createdAt: '2026-01-01T00:00:00.000Z', + scheduledAt: '2026-02-01T10:00:00.000Z', + maximumVolunteers: 5, + currentVolunteers: 1, + difficulty: 'HARD' as const, + }, + ] + + expect( + filterPosts(posts, { + ...defaultPostFilters, + location: 'park', + }).map((post) => post.id), + ).toEqual(['park']) + expect( + filterPosts(posts, { + ...defaultPostFilters, + availability: 3, + }).map((post) => post.id), + ).toEqual(['pantry']) + expect( + filterPosts(posts, { + ...defaultPostFilters, + search: 'LOCAL FAMILIES', + }).map((post) => post.id), + ).toEqual(['pantry']) + expect( + filterPosts(posts, { + ...defaultPostFilters, + difficulty: ['HARD'], + }).map((post) => post.id), + ).toEqual(['pantry']) + }) }) diff --git a/tests/unit/posts-browser.test.tsx b/tests/unit/posts-browser.test.tsx new file mode 100644 index 0000000..55ed4cf --- /dev/null +++ b/tests/unit/posts-browser.test.tsx @@ -0,0 +1,145 @@ +// @vitest-environment jsdom + +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, describe, expect, it } from 'vitest' + +import { PostsBrowser } from '../../app/posts/PostsBrowser' + +afterEach(cleanup) + +describe('PostsBrowser', () => { + it('reorders visible posts when oldest is applied', () => { + render( + , + ) + + fireEvent.click(screen.getByRole('button', { name: 'Filters' })) + fireEvent.change(screen.getByLabelText('Sort posts by'), { + target: { value: 'oldest' }, + }) + fireEvent.click(screen.getByRole('button', { name: 'Apply filters' })) + + const titles = screen.getAllByRole('heading', { level: 2 }) + expect(titles.map((title) => title.textContent)).toEqual([ + 'Older task', + 'Newer task', + ]) + }) + + it('reorders visible posts by latest event when selected', () => { + render( + , + ) + + fireEvent.click(screen.getByRole('button', { name: 'Filters' })) + fireEvent.change(screen.getByLabelText('Sort posts by'), { + target: { value: 'latest-event' }, + }) + fireEvent.click(screen.getByRole('button', { name: 'Apply filters' })) + + const titles = screen.getAllByRole('heading', { level: 2 }) + expect(titles.map((title) => title.textContent)).toEqual([ + 'Late event', + 'Early event', + ]) + }) + + it('shows active filters and clears them together', () => { + render( + , + ) + + fireEvent.click(screen.getByRole('button', { name: 'Filters' })) + fireEvent.change(screen.getByLabelText('Location'), { + target: { value: 'park' }, + }) + fireEvent.change(screen.getByLabelText('Availability'), { + target: { value: '4' }, + }) + fireEvent.change(screen.getByLabelText('Search posts'), { + target: { value: 'park' }, + }) + fireEvent.click(screen.getByRole('button', { name: 'Apply filters' })) + + expect(screen.getByRole('button', { name: 'Location: park' })).toBeTruthy() + expect( + screen.getByRole('button', { name: 'At least 4 spots' }), + ).toBeTruthy() + expect(screen.getByRole('button', { name: 'Search: park' })).toBeTruthy() + expect(screen.getByRole('button', { name: 'Clear filters' })).toBeTruthy() + + fireEvent.click(screen.getByRole('button', { name: 'Clear filters' })) + + expect(screen.queryByRole('button', { name: 'Location: park' })).toBeNull() + expect( + screen.queryByRole('button', { name: 'At least 4 spots' }), + ).toBeNull() + expect(screen.queryByRole('button', { name: 'Search: park' })).toBeNull() + expect(screen.getByRole('heading', { name: 'Park cleanup' })).toBeTruthy() + }) +}) diff --git a/tests/unit/posts-list.test.tsx b/tests/unit/posts-list.test.tsx index 0f6c6c8..fbe6032 100644 --- a/tests/unit/posts-list.test.tsx +++ b/tests/unit/posts-list.test.tsx @@ -15,12 +15,22 @@ describe('PostsList', () => { title: 'Park cleanup', location: 'Bidwell Park', imageUrl: null, + createdAt: '2026-01-02T00:00:00.000Z', + scheduledAt: '2026-02-02T10:00:00.000Z', + maximumVolunteers: 5, + currentVolunteers: 2, + difficulty: 'EASY', }, { id: 'food-drive', title: 'Food drive', location: 'Downtown Chico', imageUrl: null, + createdAt: '2026-01-01T00:00:00.000Z', + scheduledAt: '2026-02-01T10:00:00.000Z', + maximumVolunteers: 5, + currentVolunteers: 2, + difficulty: 'HARD', }, ]} />,