Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ Repository for team IT2810-H26-T19 in IT2810-H26.

**Crate** is an album catalog where users can search for music, sort and page
through the results, open an album for detail, rate and review it, and add it to
a personal wantlist ("crate"). The GraphQL API also supports genre and decade
filters; the frontend filter controls are planned.
a personal wantlist ("crate"). Results can be filtered by genre, decade and
whether an album has reviews.

IT2810 (NTNU) Project 2. Group T19: `erikhfj`, `robertky`, `evenkkl`, `rachelks`.

Expand Down Expand Up @@ -228,15 +228,15 @@ The two `AlbumDetailPage` rows represent the separate chunks for the album detai
| `schema.graphql` | GraphQL schema |
| `docs/` | Architecture, data model, UI, workflow, AI log and VM guide |

**Implemented:** The PostgreSQL database includes albums, artists, genres, tracks, users, reviews and crate items, with a real catalog imported from MusicBrainz. The GraphQL backend supports album and artist search, genre and decade filters, sorting, cursor-based pagination, album details, reviews and adding or removing albums from the crate. Users are simulated: the client sends an `X-User-Id` header on every request and the server reads it into the request context. Supported sorts are `RELEVANCE`, `TITLE_ASC`, `TITLE_DESC`, `RELEASE_YEAR_ASC`, `RELEASE_YEAR_DESC`, `AVERAGE_RATING_ASC` and `AVERAGE_RATING_DESC`, chosen from the sort control above the results.
**Implemented:** The PostgreSQL database includes albums, artists, genres, tracks, users, reviews and crate items, with a real catalog imported from MusicBrainz. The GraphQL backend supports album and artist search, genre, decade and has-reviews filters with facet counts, sorting, cursor-based pagination, album details, reviews and adding or removing albums from the crate. Users are simulated: the client sends an `X-User-Id` header on every request and the server reads it into the request context. Supported sorts are `RELEVANCE`, `TITLE_ASC`, `TITLE_DESC`, `RELEASE_YEAR_ASC`, `RELEASE_YEAR_DESC`, `AVERAGE_RATING_ASC` and `AVERAGE_RATING_DESC`, chosen from the sort control above the results.

The frontend supports searching by album title or artist, committed on Search or Enter rather than while typing, with loading and error feedback, and a no-results message. Searches start with 20 visible matches ordered by relevance, and the sort control re-queries the server so the new order covers the whole result set. The sort is kept in the URL with the query. Infinite scroll reveals up to 60 matches, then Load more reveals subsequent pages. Returning to a search starts with 20 visible matches and reuses cached pages before requesting more. Opening an album shows its tracks, average rating and reviews, and lets the user write, edit or delete their own review. Albums can be added to or removed from the crate from the results and the album page.
The frontend supports searching by album title or artist, committed on Search or Enter rather than while typing, with loading and error feedback, and a no-results message. Searches start with 20 visible matches ordered by relevance, and the sort control re-queries the server so the new order covers the whole result set. The sort is kept in the URL with the query. Infinite scroll reveals up to 60 matches, then Load more reveals subsequent pages. Returning to a search starts with 20 visible matches and reuses cached pages before requesting more. A Filters button above the results opens a panel that narrows them by genre, decade and whether an album has reviews. Genres combine with AND, so a genre's count is how many albums would remain after ticking it. Decades combine with OR, so a decade's count is how many matching albums that decade has, and ticking another decade adds them to the selection. Options with no matches are hidden, but selected ones always stay so they can be removed. Changing a filter starts again from the first page. Opening an album shows its tracks, average rating and reviews, and lets the user write, edit or delete their own review. Albums can be added to or removed from the crate from the results and the album page.

**Planned:** Frontend filter controls (#13), a page listing the user's crate (`myCrate`), and Playwright end-to-end tests (M4). Accessibility and sustainability are M3 work and are covered under [Sustainability measures](#sustainability-measures) and the accessibility pass in the issue tracker.
**Planned:** A page listing the user's crate (`myCrate`), and Playwright end-to-end tests (M4). Accessibility and sustainability are M3 work and are covered under [Sustainability measures](#sustainability-measures) and the accessibility pass in the issue tracker.

### Backend search behavior

The API uses PostgreSQL full-text search for album titles and artist names, with prefix matching to support partial words (e.g. `radi` matches `Radiohead`). It supports genre and decade filters, relevance/title/release-year/rating sorting, facet counts and cursor-based pagination. Everything except the filters and facet counts is exposed in the frontend.
The API uses PostgreSQL full-text search for album titles and artist names, with prefix matching to support partial words (e.g. `radi` matches `Radiohead`). It supports genre, decade and has-reviews filters, relevance/title/release-year/rating sorting, facet counts and cursor-based pagination. All of it is exposed in the frontend.

## Try the application

Expand Down
38 changes: 38 additions & 0 deletions client/src/App.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ function mockSearch(
searchAlbums: {
edges: albums.map((node) => ({ cursor: node.id, node })),
totalCount: albums.length,
genreFacets: [],
decadeFacets: [],
reviewedCount: 0,
pageInfo: { hasNextPage: false, endCursor: null },
},
},
Expand Down Expand Up @@ -97,6 +100,9 @@ describe('App search', () => {
searchAlbums: {
edges: [],
totalCount: 0,
genreFacets: [],
decadeFacets: [],
reviewedCount: 0,
pageInfo: { hasNextPage: false, endCursor: null },
},
},
Expand All @@ -121,6 +127,9 @@ describe('App search', () => {
searchAlbums: {
edges: [{ cursor: '1', node: album }],
totalCount: 1,
genreFacets: [],
decadeFacets: [],
reviewedCount: 0,
pageInfo: { hasNextPage: false, endCursor: '1' },
},
},
Expand Down Expand Up @@ -182,6 +191,35 @@ describe('App search', () => {
expect(window.location.search).toBe('?q=Abbey');
});

it('filters by a genre from its facet and restarts on the first page', async () => {
const rock = { genre: { id: '1', name: 'Rock' }, count: 1 };
const unfiltered = mockSearch('Abbey');
const filtered = mockSearch('Abbey');
filtered.request.variables = {
input: { query: 'Abbey', sort: 'RELEVANCE', genreIds: ['1'] },
first: 20,
after: null,
};
for (const mock of [unfiltered, filtered]) {
const data = (mock.result as { data: SearchAlbumsData }).data;
data.searchAlbums.genreFacets = [rock];
}
renderApp([unfiltered, filtered]);
submitSearch('Abbey');

fireEvent.click(await screen.findByRole('button', { name: 'Filters' }));
const checkbox = await screen.findByRole('checkbox', { name: 'Rock 1 albums' });
fireEvent.click(checkbox);

expect(window.location.search).toBe('?q=Abbey&genres=1');
await waitFor(() =>
expect(screen.getByRole('checkbox', { name: 'Rock 1 albums' })).toBeChecked(),
);
expect(
await screen.findByRole('article', { name: 'Abbey Road' }),
).toBeInTheDocument();
});

it('returns to an empty discovery page from the main navigation', async () => {
window.history.replaceState({}, '', '/?q=Abbey&sort=TITLE_ASC');
const mock = mockSearch('Abbey');
Expand Down
15 changes: 15 additions & 0 deletions client/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import SearchForm from './components/SearchForm.js';
import ResultsLayout from './components/ResultsLayout.js';
import FilterPanel from './components/FilterPanel.js';
import { lazy, Suspense } from 'react';

import { useAlbumSearch } from './hooks/useAlbumSearch.js';
Expand Down Expand Up @@ -60,6 +61,20 @@ function DiscoveryPage() {
<SearchForm query={search.query} onSearch={search.search} />
</section>
<div id="catalogue" className="catalogue-layout">
{search.hasQuery && (
<FilterPanel
genres={search.filters.genres}
decades={search.filters.decades}
reviewed={search.filters.reviewed}
genreFacets={search.facets.genres}
decadeFacets={search.facets.decades}
reviewedCount={search.facets.reviewedCount}
onGenresChange={search.setGenres}
onDecadesChange={search.setDecades}
onReviewedChange={search.setReviewed}
onClear={search.clearFilters}
/>
)}
<ResultsLayout
albums={search.albums}
totalCount={search.totalCount}
Expand Down
3 changes: 3 additions & 0 deletions client/src/a11y.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ function mockSearch(
searchAlbums: {
edges: albums.map((node) => ({ cursor: node.id, node })),
totalCount: albums.length,
genreFacets: [],
decadeFacets: [],
reviewedCount: 0,
pageInfo: { hasNextPage: false, endCursor: null },
},
},
Expand Down
3 changes: 3 additions & 0 deletions client/src/api/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ function result(ids: string[], endCursor: string, hasNextPage = true): SearchAlb
})),
pageInfo: { endCursor, hasNextPage },
totalCount: 4,
genreFacets: [],
decadeFacets: [],
reviewedCount: 0,
},
};
}
Expand Down
28 changes: 27 additions & 1 deletion client/src/api/searchAlbums.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export interface AlbumSearchInput {
query: string;
genreIds?: string[] | null;
decades?: number[] | null;
hasReviews?: boolean | null;
sort: AlbumSort;
}

Expand All @@ -37,6 +38,19 @@ export interface AlbumConnection {
edges: { cursor: string; node: AlbumSummary }[];
pageInfo: { hasNextPage: boolean; endCursor: string | null };
totalCount: number;
genreFacets: GenreFacet[];
decadeFacets: DecadeFacet[];
reviewedCount: number;
}

export interface GenreFacet {
genre: { id: string; name: string };
count: number;
}

export interface DecadeFacet {
decade: number;
count: number;
}

export interface SearchAlbumsData {
Expand All @@ -50,7 +64,7 @@ export interface SearchAlbumsVariables {
}

// gql parses the operation; TypedDocumentNode describes its variables and selected result fields.
// Only the search-page projection is requested; details and facets belong to later work.
// Only the search-page projection is requested; details belong to the album page.
export const SEARCH_ALBUMS: TypedDocumentNode<SearchAlbumsData, SearchAlbumsVariables> =
gql`
query SearchAlbums($input: AlbumSearchInput!, $first: Int!, $after: String) {
Expand All @@ -75,6 +89,18 @@ export const SEARCH_ALBUMS: TypedDocumentNode<SearchAlbumsData, SearchAlbumsVari
}
}
totalCount
genreFacets {
genre {
id
name
}
count
}
decadeFacets {
decade
count
}
reviewedCount
pageInfo {
hasNextPage
endCursor
Expand Down
63 changes: 63 additions & 0 deletions client/src/components/FilterPanel.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
.filter-panel {
margin-bottom: 1.25rem;
}
.filter-panel fieldset {
border: 0;
margin: 0;
padding: 0.5rem 0;
}
.filter-panel legend {
padding: 0;
font-size: 0.75rem;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.1em;
color: var(--muted);
}
.filter-panel label {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.25rem 0;
}
.filter-count {
margin-left: auto;
font-size: 0.8rem;
color: var(--chip-text);
background: var(--chip-bg);
border-radius: 999px;
padding: 0 0.5rem;
}
.clear-filters {
background: var(--surface);
color: var(--text);
border: 1px solid var(--border-strong);
}
.filter-toggle {
background: var(--surface);
color: var(--text);
border: 1px solid var(--border-strong);
}
.filter-toggle[aria-expanded='true'] {
border-color: var(--accent);
}
.filter-options:not(.open) {
display: none;
}
.filter-options.open {
display: flex;
flex-wrap: wrap;
align-items: flex-start;
gap: 0 2rem;
margin-top: 0.75rem;
padding: 0.75rem 1rem;
border: 1px solid var(--border);
border-radius: 8px;
background: var(--surface);
}
.filter-options fieldset {
min-width: 11rem;
}
.filter-options .clear-filters {
align-self: center;
}
105 changes: 105 additions & 0 deletions client/src/components/FilterPanel.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import { describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen } from '@testing-library/react';
import axe from 'axe-core';
import FilterPanel from './FilterPanel.js';

type Props = Parameters<typeof FilterPanel>[0];

function renderPanel(over: Partial<Props> = {}) {
const props: Props = {
genres: [],
decades: [],
reviewed: false,
genreFacets: [
{ genre: { id: '4', name: 'Rock' }, count: 7 },
{ genre: { id: '2', name: 'Jazz' }, count: 0 },
],
decadeFacets: [
{ decade: 1970, count: 3 },
{ decade: 1990, count: 0 },
],
reviewedCount: 2,
onGenresChange: vi.fn(),
onDecadesChange: vi.fn(),
onReviewedChange: vi.fn(),
onClear: vi.fn(),
...over,
};
return { props, ...render(<FilterPanel {...props} />) };
}

describe('FilterPanel', () => {
it('shows each option with its count', () => {
renderPanel();
expect(screen.getByRole('checkbox', { name: 'Rock 7 albums' })).toBeInTheDocument();
expect(screen.getByRole('checkbox', { name: '1970s 3 albums' })).toBeInTheDocument();
expect(
screen.getByRole('checkbox', { name: 'Has reviews 2 albums' }),
).toBeInTheDocument();
});

it('hides options that would return nothing', () => {
renderPanel({ reviewedCount: 0 });
expect(screen.queryByRole('checkbox', { name: /Jazz/ })).not.toBeInTheDocument();
expect(screen.queryByRole('checkbox', { name: /1990s/ })).not.toBeInTheDocument();
expect(screen.queryByRole('group', { name: 'Reviews' })).not.toBeInTheDocument();
});

it('keeps a selected option visible so it can be unticked', () => {
renderPanel({ decades: [1990] });
expect(screen.getByRole('checkbox', { name: /1990s/ })).toBeChecked();
});

it('adds and removes values from the selection', () => {
const { props } = renderPanel({ genres: ['4'] });
fireEvent.click(screen.getByRole('checkbox', { name: /Rock/ }));
expect(props.onGenresChange).toHaveBeenCalledWith([]);
fireEvent.click(screen.getByRole('checkbox', { name: /1970s/ }));
expect(props.onDecadesChange).toHaveBeenCalledWith([1970]);
fireEvent.click(screen.getByRole('checkbox', { name: /Has reviews/ }));
expect(props.onReviewedChange).toHaveBeenCalledWith(true);
});

it('offers Clear filters only while a filter is active', () => {
renderPanel();
expect(screen.queryByRole('button', { name: 'Clear filters' })).toBeNull();
});

it('clears every filter', () => {
const { props } = renderPanel({ reviewed: true });
fireEvent.click(screen.getByRole('button', { name: 'Clear filters' }));
expect(props.onClear).toHaveBeenCalled();
});

it('toggles the options from the Filters button and counts active filters', () => {
renderPanel({ genres: ['4'], reviewed: true });
const button = screen.getByRole('button', { name: 'Filters (2)' });
expect(button).toHaveAttribute('aria-expanded', 'false');
expect(button).toHaveAttribute('aria-controls', 'filter-options');
fireEvent.click(button);
expect(button).toHaveAttribute('aria-expanded', 'true');
});

it('closes on Escape and returns focus to the Filters button', () => {
renderPanel();
const button = screen.getByRole('button', { name: 'Filters' });
fireEvent.click(button);
fireEvent.keyDown(screen.getByRole('checkbox', { name: /Rock/ }), { key: 'Escape' });
expect(button).toHaveAttribute('aria-expanded', 'false');
expect(button).toHaveFocus();
});

it('keeps a selected genre the server reports with no matches', () => {
// After a new search term, the server lists selected genres with a count of 0.
renderPanel({ genres: ['2'] });
expect(screen.getByRole('checkbox', { name: 'Jazz 0 albums' })).toBeChecked();
});

it('has no axe violations', async () => {
const { container } = renderPanel({ genres: ['4'] });
const results = await axe.run(container, {
rules: { 'color-contrast': { enabled: false } },
});
expect(results.violations.map((violation) => violation.id)).toEqual([]);
});
});
Loading