From cdc07f2220097d1d4af46c5b23c76809cc6406e6 Mon Sep 17 00:00:00 2001 From: Rachel Knutsen Stiansen Date: Fri, 13 Nov 2026 11:55:22 +0100 Subject: [PATCH 1/4] feat: #24 add search history schema and UI component --- client/src/components/RecentSearches.css | 51 ++++++++++++ client/src/components/RecentSearches.test.tsx | 82 +++++++++++++++++++ client/src/components/RecentSearches.tsx | 41 ++++++++++ schema.graphql | 21 +++++ 4 files changed, 195 insertions(+) create mode 100644 client/src/components/RecentSearches.css create mode 100644 client/src/components/RecentSearches.test.tsx create mode 100644 client/src/components/RecentSearches.tsx diff --git a/client/src/components/RecentSearches.css b/client/src/components/RecentSearches.css new file mode 100644 index 0000000..53a3b2d --- /dev/null +++ b/client/src/components/RecentSearches.css @@ -0,0 +1,51 @@ +.recent-searches { + max-width: 42.5rem; + min-width: 0; + margin-top: 1rem; + color: var(--text); +} +.recent-searches__header { + display: flex; + align-items: center; + justify-content: space-between; + flex-wrap: wrap; + gap: 0.5rem 1rem; +} +.recent-searches h2 { + margin: 0; + font-size: 1rem; +} +.recent-searches button { + max-width: 100%; + min-height: 2.75rem; + border: 1px solid var(--border-strong); + border-radius: 5px; + background: var(--surface); + color: var(--text); + text-align: left; + overflow-wrap: anywhere; +} +.recent-searches button:hover { + border-color: var(--accent); + color: var(--accent); +} +.recent-searches button:focus-visible { + outline: 3px solid var(--focus); + outline-offset: 4px; +} +.recent-searches__list { + display: flex; + flex-wrap: wrap; + gap: 0.75rem; + padding: 0; + margin: 0.75rem 0 0; + list-style: none; +} +.recent-searches__list li { + min-width: 0; + max-width: 100%; +} +.recent-searches__empty { + margin: 0.5rem 0 0; + color: var(--muted); +} diff --git a/client/src/components/RecentSearches.test.tsx b/client/src/components/RecentSearches.test.tsx new file mode 100644 index 0000000..0063d0c --- /dev/null +++ b/client/src/components/RecentSearches.test.tsx @@ -0,0 +1,82 @@ +import { describe, expect, it, vi } from 'vitest'; +import { fireEvent, render, screen, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; + +import RecentSearches from './RecentSearches.js'; + +const entries = [ + { query: 'Blue', lastSearchedAt: '2026-11-10T12:00:00Z' }, + { query: 'Abbey Road', lastSearchedAt: '2026-11-09T12:00:00Z' }, +]; + +describe('RecentSearches', () => { + it('displays queries in the newest-first order provided by the server', () => { + render(); + const region = screen.getByRole('region', { name: 'Recent searches' }); + expect(within(region).getByRole('heading', { level: 2 })).toHaveTextContent( + 'Recent searches', + ); + expect( + within(region) + .getAllByRole('listitem') + .map((item) => item.textContent), + ).toEqual(['Blue', 'Abbey Road']); + }); + + it('displays at most 10 entries', () => { + const manyEntries = Array.from({ length: 12 }, (_, index) => ({ + query: `Query ${index}`, + lastSearchedAt: entries[0]!.lastSearchedAt, + })); + render(); + expect(screen.getAllByRole('listitem')).toHaveLength(10); + expect(screen.queryByRole('button', { name: 'Query 10' })).not.toBeInTheDocument(); + }); + + it('reports a selected query without clearing history', () => { + const onSelect = vi.fn(); + const onClear = vi.fn(); + render(); + fireEvent.click(screen.getByRole('button', { name: 'Abbey Road' })); + expect(onSelect).toHaveBeenCalledExactlyOnceWith('Abbey Road'); + expect(onClear).not.toHaveBeenCalled(); + }); + + it('reports clearing and displays the empty state when its props change', () => { + const onSelect = vi.fn(); + const onClear = vi.fn(); + const { rerender } = render( + , + ); + fireEvent.click(screen.getByRole('button', { name: 'Clear recent searches' })); + expect(onClear).toHaveBeenCalledExactlyOnceWith(); + expect(onSelect).not.toHaveBeenCalled(); + rerender(); + expect(screen.getByText('No recent searches yet.')).toBeInTheDocument(); + expect(screen.queryByRole('list')).not.toBeInTheDocument(); + expect( + screen.queryByRole('button', { name: 'Clear recent searches' }), + ).not.toBeInTheDocument(); + }); + + it('supports keyboard selection and clearing without submitting a parent form', async () => { + const user = userEvent.setup(); + const onSelect = vi.fn(); + const onClear = vi.fn(); + const onSubmit = vi.fn((event) => event.preventDefault()); + render( +
+ + , + ); + await user.tab(); + expect(screen.getByRole('button', { name: 'Clear recent searches' })).toHaveFocus(); + await user.keyboard('{Enter}'); + expect(onClear).toHaveBeenCalledOnce(); + await user.tab(); + expect(screen.getByRole('button', { name: 'Blue' })).toHaveFocus(); + await user.keyboard(' '); + expect(onSelect).toHaveBeenCalledExactlyOnceWith('Blue'); + expect(onSubmit).not.toHaveBeenCalled(); + }); +}); diff --git a/client/src/components/RecentSearches.tsx b/client/src/components/RecentSearches.tsx new file mode 100644 index 0000000..4e6ad70 --- /dev/null +++ b/client/src/components/RecentSearches.tsx @@ -0,0 +1,41 @@ +import './RecentSearches.css'; + +import { useId } from 'react'; + +interface Props { + /** Distinct queries in newest-first order, as returned by the server. */ + entries: readonly { query: string; lastSearchedAt: string }[]; + onSelect: (query: string) => void; + onClear: () => void; +} + +export default function RecentSearches({ entries, onSelect, onClear }: Props) { + const headingId = useId(); + const recent = entries.slice(0, 10); + + return ( +
+
+

Recent searches

+ {recent.length > 0 && ( + + )} +
+ {recent.length > 0 ? ( +
    + {recent.map(({ query }) => ( +
  • + +
  • + ))} +
+ ) : ( +

No recent searches yet.

+ )} +
+ ); +} diff --git a/schema.graphql b/schema.graphql index be75e57..03ab862 100644 --- a/schema.graphql +++ b/schema.graphql @@ -4,6 +4,11 @@ type Query { searchAlbums(input: AlbumSearchInput!, first: Int!, after: String): AlbumConnection! album(id: ID!): Album myCrate(first: Int!, after: String): CrateConnection! + """ + The current user's 10 most recent distinct queries, newest first. + Identity comes from X-User-Id. Anonymous requests return an empty list. + """ + mySearchHistory: [SearchHistoryEntry!]! } type Mutation { @@ -11,6 +16,22 @@ type Mutation { deleteReview(id: ID!): DeleteReviewPayload! addToCrate(albumId: ID!): AddToCratePayload! removeFromCrate(albumId: ID!): RemoveFromCratePayload! + """ + Record a trimmed, nonempty query for the current user, refreshing its recency + if it already exists. Requires a valid X-User-Id header. + """ + recordSearch(query: String!): SearchHistoryEntry! + """ + Clear only the current user's search history. Returns true even if already + empty. Requires a valid X-User-Id header. + """ + clearSearchHistory: Boolean! +} + +type SearchHistoryEntry { + query: String! + "The time this query was most recently recorded." + lastSearchedAt: DateTime! } type Album { From 5ced4218866571be4af0a413ef143d14e9cac8fe Mon Sep 17 00:00:00 2001 From: Rachel Knutsen Stiansen Date: Fri, 13 Nov 2026 15:15:18 +0100 Subject: [PATCH 2/4] feat: #24 implement search history backend --- server/drizzle/0006_search-history.sql | 10 + server/drizzle/meta/0006_snapshot.json | 721 ++++++++++++++++++++++ server/drizzle/meta/_journal.json | 7 + server/scripts/assert-postgres-tests.mjs | 1 + server/src/db/schema.ts | 18 + server/src/resolvers.ts | 7 + server/src/searchHistory.postgres.test.ts | 217 +++++++ server/src/searchHistory.test.ts | 23 + server/src/searchHistory.ts | 73 +++ 9 files changed, 1077 insertions(+) create mode 100644 server/drizzle/0006_search-history.sql create mode 100644 server/drizzle/meta/0006_snapshot.json create mode 100644 server/src/searchHistory.postgres.test.ts create mode 100644 server/src/searchHistory.test.ts create mode 100644 server/src/searchHistory.ts diff --git a/server/drizzle/0006_search-history.sql b/server/drizzle/0006_search-history.sql new file mode 100644 index 0000000..40c8dfd --- /dev/null +++ b/server/drizzle/0006_search-history.sql @@ -0,0 +1,10 @@ +CREATE TABLE "search_history" ( + "user_id" uuid NOT NULL, + "query" text NOT NULL, + "last_searched_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "search_history_user_id_query_pk" PRIMARY KEY("user_id","query"), + CONSTRAINT "search_history_query_nonempty" CHECK (length(btrim("search_history"."query")) > 0) +); +--> statement-breakpoint +ALTER TABLE "search_history" ADD CONSTRAINT "search_history_user_id_app_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."app_user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +CREATE INDEX "search_history_user_recent_idx" ON "search_history" USING btree ("user_id","last_searched_at"); diff --git a/server/drizzle/meta/0006_snapshot.json b/server/drizzle/meta/0006_snapshot.json new file mode 100644 index 0000000..8edfccd --- /dev/null +++ b/server/drizzle/meta/0006_snapshot.json @@ -0,0 +1,721 @@ +{ + "id": "622a95de-bc54-4e41-97a8-37e9d52b3a3c", + "prevId": "a9e05b69-34a9-46b8-99d5-7468d1636e11", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.album": { + "name": "album", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "release_year": { + "name": "release_year", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "musicbrainz_release_group_id": { + "name": "musicbrainz_release_group_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "search_vector": { + "name": "search_vector", + "type": "tsvector", + "primaryKey": false, + "notNull": false + }, + "average_rating": { + "name": "average_rating", + "type": "double precision", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "album_search_vector_idx": { + "name": "album_search_vector_idx", + "columns": [ + { + "expression": "search_vector", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "gin", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "album_musicbrainz_release_group_id_unique": { + "name": "album_musicbrainz_release_group_id_unique", + "nullsNotDistinct": false, + "columns": ["musicbrainz_release_group_id"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.album_artist": { + "name": "album_artist", + "schema": "", + "columns": { + "album_id": { + "name": "album_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "artist_id": { + "name": "artist_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "position": { + "name": "position", + "type": "smallint", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": {}, + "foreignKeys": { + "album_artist_album_id_album_id_fk": { + "name": "album_artist_album_id_album_id_fk", + "tableFrom": "album_artist", + "tableTo": "album", + "columnsFrom": ["album_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "album_artist_artist_id_artist_id_fk": { + "name": "album_artist_artist_id_artist_id_fk", + "tableFrom": "album_artist", + "tableTo": "artist", + "columnsFrom": ["artist_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "album_artist_album_id_artist_id_pk": { + "name": "album_artist_album_id_artist_id_pk", + "columns": ["album_id", "artist_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.album_genre": { + "name": "album_genre", + "schema": "", + "columns": { + "album_id": { + "name": "album_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "genre_id": { + "name": "genre_id", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "album_genre_album_id_album_id_fk": { + "name": "album_genre_album_id_album_id_fk", + "tableFrom": "album_genre", + "tableTo": "album", + "columnsFrom": ["album_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "album_genre_genre_id_genre_id_fk": { + "name": "album_genre_genre_id_genre_id_fk", + "tableFrom": "album_genre", + "tableTo": "genre", + "columnsFrom": ["genre_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "album_genre_album_id_genre_id_pk": { + "name": "album_genre_album_id_genre_id_pk", + "columns": ["album_id", "genre_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.app_user": { + "name": "app_user", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.artist": { + "name": "artist", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "musicbrainz_artist_id": { + "name": "musicbrainz_artist_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "country": { + "name": "country", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "artist_musicbrainz_artist_id_unique": { + "name": "artist_musicbrainz_artist_id_unique", + "columns": [ + { + "expression": "musicbrainz_artist_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "artist_country_idx": { + "name": "artist_country_idx", + "columns": [ + { + "expression": "country", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.crate_item": { + "name": "crate_item", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "album_id": { + "name": "album_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "added_at": { + "name": "added_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "crate_item_user_album_unique": { + "name": "crate_item_user_album_unique", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "album_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "crate_item_user_added_at_idx": { + "name": "crate_item_user_added_at_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "added_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "crate_item_user_id_app_user_id_fk": { + "name": "crate_item_user_id_app_user_id_fk", + "tableFrom": "crate_item", + "tableTo": "app_user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "crate_item_album_id_album_id_fk": { + "name": "crate_item_album_id_album_id_fk", + "tableFrom": "crate_item", + "tableTo": "album", + "columnsFrom": ["album_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.genre": { + "name": "genre", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "genre_name_unique": { + "name": "genre_name_unique", + "nullsNotDistinct": false, + "columns": ["name"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.review": { + "name": "review", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "album_id": { + "name": "album_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "rating": { + "name": "rating", + "type": "smallint", + "primaryKey": false, + "notNull": true + }, + "comment": { + "name": "comment", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "review_user_album_unique": { + "name": "review_user_album_unique", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "album_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "review_album_idx": { + "name": "review_album_idx", + "columns": [ + { + "expression": "album_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "review_user_id_app_user_id_fk": { + "name": "review_user_id_app_user_id_fk", + "tableFrom": "review", + "tableTo": "app_user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "review_album_id_album_id_fk": { + "name": "review_album_id_album_id_fk", + "tableFrom": "review", + "tableTo": "album", + "columnsFrom": ["album_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "review_rating_range": { + "name": "review_rating_range", + "value": "\"review\".\"rating\" BETWEEN 1 AND 5" + } + }, + "isRLSEnabled": false + }, + "public.search_history": { + "name": "search_history", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "query": { + "name": "query", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "last_searched_at": { + "name": "last_searched_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "search_history_user_recent_idx": { + "name": "search_history_user_recent_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "last_searched_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "search_history_user_id_app_user_id_fk": { + "name": "search_history_user_id_app_user_id_fk", + "tableFrom": "search_history", + "tableTo": "app_user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "search_history_user_id_query_pk": { + "name": "search_history_user_id_query_pk", + "columns": ["user_id", "query"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "search_history_query_nonempty": { + "name": "search_history_query_nonempty", + "value": "length(btrim(\"search_history\".\"query\")) > 0" + } + }, + "isRLSEnabled": false + }, + "public.track": { + "name": "track", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "album_id": { + "name": "album_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "track_number": { + "name": "track_number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "duration_seconds": { + "name": "duration_seconds", + "type": "integer", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "track_album_track_number_unique": { + "name": "track_album_track_number_unique", + "columns": [ + { + "expression": "album_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "track_number", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "track_album_track_number_idx": { + "name": "track_album_track_number_idx", + "columns": [ + { + "expression": "album_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "track_number", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "track_album_id_album_id_fk": { + "name": "track_album_id_album_id_fk", + "tableFrom": "track", + "tableTo": "album", + "columnsFrom": ["album_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} diff --git a/server/drizzle/meta/_journal.json b/server/drizzle/meta/_journal.json index 236152c..29822c2 100644 --- a/server/drizzle/meta/_journal.json +++ b/server/drizzle/meta/_journal.json @@ -43,6 +43,13 @@ "when": 1794490198109, "tag": "0005_artist-country", "breakpoints": true + }, + { + "idx": 6, + "version": "7", + "when": 1794569205825, + "tag": "0006_search-history", + "breakpoints": true } ] } diff --git a/server/scripts/assert-postgres-tests.mjs b/server/scripts/assert-postgres-tests.mjs index 6f52bd4..798d9a6 100644 --- a/server/scripts/assert-postgres-tests.mjs +++ b/server/scripts/assert-postgres-tests.mjs @@ -20,6 +20,7 @@ import { pathToFileURL } from 'node:url'; // Files that cannot run without a database. Adding a new one here is deliberate: // the list is the guard, so it should grow with the suite. export const databaseBackedFiles = [ + 'src/searchHistory.postgres.test.ts', // Added with the crate query; not on main when this branch was cut. 'src/crate.postgres.test.ts', 'src/db/musicBrainzCatalog.test.ts', diff --git a/server/src/db/schema.ts b/server/src/db/schema.ts index da9e05b..2361134 100644 --- a/server/src/db/schema.ts +++ b/server/src/db/schema.ts @@ -108,6 +108,24 @@ export const appUser = pgTable('app_user', { createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(), }); +export const searchHistory = pgTable( + 'search_history', + { + userId: uuid('user_id') + .notNull() + .references(() => appUser.id, { onDelete: 'cascade' }), + query: text('query').notNull(), + lastSearchedAt: timestamp('last_searched_at', { withTimezone: true, mode: 'string' }) + .notNull() + .defaultNow(), + }, + (t) => [ + primaryKey({ columns: [t.userId, t.query] }), + index('search_history_user_recent_idx').on(t.userId, t.lastSearchedAt), + check('search_history_query_nonempty', sql`length(btrim(${t.query})) > 0`), + ], +); + export const review = pgTable( 'review', { diff --git a/server/src/resolvers.ts b/server/src/resolvers.ts index 9c1aab3..c17de7d 100644 --- a/server/src/resolvers.ts +++ b/server/src/resolvers.ts @@ -18,6 +18,7 @@ import { } from './search/search.js'; import { removeReview, saveReview, type UpsertReviewInput } from './reviews.js'; import { addToCrate, removeFromCrate } from './crate.js'; +import { clearSearchHistory, historyForUser, recordSearch } from './searchHistory.js'; export type Context = { db: Db; loaders: Loaders; userId: string | null }; @@ -283,6 +284,8 @@ async function searchAlbums(db: Db, { input, first, after }: SearchArgs) { // own issues. export const resolvers = { Query: { + mySearchHistory: (_: unknown, __: unknown, ctx: Context) => + historyForUser(ctx.db, ctx.userId), searchAlbums: (_: unknown, args: SearchArgs, ctx: Context) => searchAlbums(ctx.db, args), myCrate: (_: unknown, args: CrateArgs, ctx: Context) => crateForUser(ctx, args), @@ -329,6 +332,10 @@ export const resolvers = { }, }, Mutation: { + recordSearch: (_: unknown, { query }: { query: string }, ctx: Context) => + recordSearch(ctx.db, ctx.userId, query), + clearSearchHistory: (_: unknown, __: unknown, ctx: Context) => + clearSearchHistory(ctx.db, ctx.userId), upsertReview: (_: unknown, { input }: { input: UpsertReviewInput }, ctx: Context) => saveReview(ctx.db, ctx.userId, input), deleteReview: (_: unknown, { id }: { id: string }, ctx: Context) => diff --git a/server/src/searchHistory.postgres.test.ts b/server/src/searchHistory.postgres.test.ts new file mode 100644 index 0000000..2de3029 --- /dev/null +++ b/server/src/searchHistory.postgres.test.ts @@ -0,0 +1,217 @@ +import { randomUUID } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { drizzle } from 'drizzle-orm/node-postgres'; +import { eq, inArray } from 'drizzle-orm'; +import { createSchema, createYoga } from 'graphql-yoga'; +import pg from 'pg'; +import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { appUser, searchHistory } from './db/schema.js'; +import { createLoaders } from './loaders/index.js'; +import { resolvers, type Context } from './resolvers.js'; +import { parseUserId } from './userIdentity.js'; + +describe.skipIf(!process.env.TEST_DATABASE_URL)('PostgreSQL search history', () => { + const pool = new pg.Pool({ connectionString: process.env.TEST_DATABASE_URL }); + const db = drizzle(pool); + const owner = randomUUID(); + const stranger = randomUUID(); + const users = [owner, stranger]; + const context = (userId: string | null = owner): Context => ({ + db, + userId, + loaders: createLoaders(db, userId), + }); + const record = (query: string, userId = owner) => + resolvers.Mutation.recordSearch({}, { query }, context(userId)); + const history = (userId: string | null = owner) => + resolvers.Query.mySearchHistory({}, {}, context(userId)); + const clear = (userId = owner) => + resolvers.Mutation.clearSearchHistory({}, {}, context(userId)); + + beforeEach(async () => { + await db.delete(appUser).where(inArray(appUser.id, users)); + }); + afterAll(async () => { + await db.delete(appUser).where(inArray(appUser.id, users)); + await pool.end(); + }); + + it('creates the user, trims queries and persists across request contexts', async () => { + const entry = await record(' Abbey Road '); + expect(entry.query).toBe('Abbey Road'); + expect(Number.isNaN(Date.parse(entry.lastSearchedAt))).toBe(false); + expect(await history()).toEqual([entry]); + const user = await db.select().from(appUser).where(eq(appUser.id, owner)); + expect(user).toHaveLength(1); + }); + + it('refreshes repeated searches without storing duplicate rows', async () => { + await record('Blue'); + await db + .update(searchHistory) + .set({ lastSearchedAt: '2000-01-01T00:00:00Z' }) + .where(eq(searchHistory.userId, owner)); + await record('Abbey Road'); + const repeated = await record(' Blue '); + const entries = await history(); + expect(entries.map((entry) => entry.query)).toEqual(['Blue', 'Abbey Road']); + expect(entries[0]).toEqual(repeated); + expect(Date.parse(repeated.lastSearchedAt)).toBeGreaterThan(Date.parse('2000-01-01')); + }); + + it('deletes old entries and retains only the ten newest distinct searches', async () => { + for (let index = 0; index < 12; index++) await record(`Query ${index}`); + expect((await history()).map((entry) => entry.query)).toEqual( + Array.from({ length: 10 }, (_, index) => `Query ${11 - index}`), + ); + const stored = await db + .select() + .from(searchHistory) + .where(eq(searchHistory.userId, owner)); + expect(stored).toHaveLength(10); + }); + + it('keeps the limit during concurrent submissions', async () => { + await Promise.all( + Array.from({ length: 15 }, (_, index) => record(`Concurrent ${index}`)), + ); + const stored = await db + .select() + .from(searchHistory) + .where(eq(searchHistory.userId, owner)); + expect(stored).toHaveLength(10); + expect(await history()).toHaveLength(10); + }); + + it('isolates reading, retention and clearing between users', async () => { + const other = await record('Blue', stranger); + for (let index = 0; index < 11; index++) await record(`Mine ${index}`); + expect(await history(stranger)).toEqual([other]); + expect(await clear()).toBe(true); + expect(await history()).toEqual([]); + expect(await history(stranger)).toEqual([other]); + expect(await clear()).toBe(true); + }); + + it('clears an unused identity without creating a user', async () => { + expect(await clear()).toBe(true); + expect(await db.select().from(appUser).where(eq(appUser.id, owner))).toEqual([]); + expect(await history()).toEqual([]); + await record('First search'); + expect((await history()).map((entry) => entry.query)).toEqual(['First search']); + }); + + it('deduplicates concurrent repeats for a new user', async () => { + await Promise.all(Array.from({ length: 12 }, () => record(' Blue '))); + expect((await history()).map((entry) => entry.query)).toEqual(['Blue']); + expect(await db.select().from(appUser).where(eq(appUser.id, owner))).toHaveLength(1); + }); + + it.each(['record', 'clear'] as const)( + '%s waits for the user row lock', + async (action) => { + await record('Blue'); + const blocker = await pool.connect(); + let pending: Promise | undefined; + try { + await blocker.query('BEGIN'); + await blocker.query('SELECT id FROM app_user WHERE id = $1 FOR UPDATE', [owner]); + const pid = ( + await blocker.query<{ pid: number }>('SELECT pg_backend_pid() AS pid') + ).rows[0]!.pid; + pending = action === 'record' ? record('Abbey Road') : clear(); + await vi.waitFor( + async () => { + const waiting = await pool.query<{ count: string }>( + 'SELECT count(*) FROM pg_stat_activity WHERE $1 = ANY(pg_blocking_pids(pid))', + [pid], + ); + expect(Number(waiting.rows[0]!.count)).toBeGreaterThan(0); + }, + { timeout: 3000 }, + ); + expect((await history()).map((entry) => entry.query)).toEqual(['Blue']); + } finally { + await blocker.query('ROLLBACK'); + blocker.release(); + await pending; + } + expect((await history()).map((entry) => entry.query)).toEqual( + action === 'record' ? ['Abbey Road', 'Blue'] : [], + ); + }, + ); + + it('uses query text as a parameter, including SQL punctuation', async () => { + const query = "Blue'); DELETE FROM app_user; --"; + expect((await record(query)).query).toBe(query); + expect((await history())[0]?.query).toBe(query); + }); + + it('orders timestamp ties deterministically by query', async () => { + await record('Zulu'); + await record('Alpha'); + await db + .update(searchHistory) + .set({ lastSearchedAt: '2000-01-01T00:00:00Z' }) + .where(eq(searchHistory.userId, owner)); + expect((await history()).map((entry) => entry.query)).toEqual(['Alpha', 'Zulu']); + }); + + it('serves the GraphQL contract using per-request X-User-Id headers', async () => { + const yoga = createYoga({ + // Expose resolver validation messages in this test server. Vitest can + // load a separate GraphQLError constructor from Yoga's dependency copy. + maskedErrors: false, + schema: createSchema({ + typeDefs: readFileSync(new URL('../../schema.graphql', import.meta.url), 'utf8'), + resolvers, + }), + context: ({ request }) => context(parseUserId(request.headers.get('X-User-Id'))), + }); + async function request(query: string, userId?: string) { + const response = await yoga.fetch('http://localhost/graphql', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + ...(userId ? { 'X-User-Id': userId } : {}), + }, + body: JSON.stringify({ query }), + }); + return response.json(); + } + const saved = await request( + 'mutation { recordSearch(query: "Blue") { query lastSearchedAt } }', + owner, + ); + expect(saved.errors).toBeUndefined(); + expect(saved.data.recordSearch.query).toBe('Blue'); + expect(typeof saved.data.recordSearch.lastSearchedAt).toBe('string'); + const read = '{ mySearchHistory { query lastSearchedAt } }'; + expect((await request(read, owner)).data.mySearchHistory).toEqual([ + saved.data.recordSearch, + ]); + for (const userId of [stranger, undefined, 'invalid']) { + expect((await request(read, userId)).data.mySearchHistory).toEqual([]); + } + for (const userId of [undefined, 'invalid']) { + for (const mutation of [ + 'recordSearch(query: "Blue") { query }', + 'clearSearchHistory', + ]) { + expect( + (await request(`mutation { ${mutation} }`, userId)).errors[0].message, + ).toContain('X-User-Id'); + } + } + expect( + (await request('mutation { recordSearch(query: " ") { query } }', owner)) + .errors[0].message, + ).toContain('must not be empty'); + expect( + (await request('mutation { clearSearchHistory }', owner)).data.clearSearchHistory, + ).toBe(true); + expect((await request(read, owner)).data.mySearchHistory).toEqual([]); + }); +}); diff --git a/server/src/searchHistory.test.ts b/server/src/searchHistory.test.ts new file mode 100644 index 0000000..ffc41b7 --- /dev/null +++ b/server/src/searchHistory.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from 'vitest'; + +import { clearSearchHistory, historyForUser, recordSearch } from './searchHistory.js'; + +describe('search history validation', () => { + it('returns empty history for anonymous reads without accessing the database', async () => { + expect(await historyForUser({} as never, null)).toEqual([]); + }); + + it('requires identity for recording and clearing', async () => { + await expect(recordSearch({} as never, null, 'Blue')).rejects.toThrow('X-User-Id'); + await expect(clearSearchHistory({} as never, null)).rejects.toThrow('X-User-Id'); + }); + + it.each(['', ' ', '\t\n'])( + 'rejects empty query %j before accessing the database', + async (query) => { + await expect( + recordSearch({} as never, '550e8400-e29b-41d4-a716-446655440000', query), + ).rejects.toThrow('Search query must not be empty'); + }, + ); +}); diff --git a/server/src/searchHistory.ts b/server/src/searchHistory.ts new file mode 100644 index 0000000..c7c6937 --- /dev/null +++ b/server/src/searchHistory.ts @@ -0,0 +1,73 @@ +import { asc, desc, eq, sql } from 'drizzle-orm'; +import { GraphQLError } from 'graphql'; + +import type { Db } from './db/client.js'; +import { appUser, searchHistory } from './db/schema.js'; +import { ensureUser, requireUserId } from './userIdentity.js'; + +const HISTORY_LIMIT = 10; + +export async function historyForUser(db: Db, userId: string | null) { + if (!userId) return []; + + return db + .select({ query: searchHistory.query, lastSearchedAt: searchHistory.lastSearchedAt }) + .from(searchHistory) + .where(eq(searchHistory.userId, userId)) + .orderBy(desc(searchHistory.lastSearchedAt), asc(searchHistory.query)) + .limit(HISTORY_LIMIT); +} + +export async function recordSearch(db: Db, userId: string | null, value: string) { + const ownerId = requireUserId(userId); + const query = value.trim(); + if (!query) throw new GraphQLError('Search query must not be empty.'); + await ensureUser(db, ownerId); + + return db.transaction(async (tx) => { + // Serialize history writes for this user so concurrent submissions cannot + // leave more than ten entries. Clearing takes the same row lock. + await tx + .select({ id: appUser.id }) + .from(appUser) + .where(eq(appUser.id, ownerId)) + .for('update'); + const [entry] = await tx + .insert(searchHistory) + .values({ userId: ownerId, query, lastSearchedAt: sql`clock_timestamp()` }) + .onConflictDoUpdate({ + target: [searchHistory.userId, searchHistory.query], + set: { lastSearchedAt: sql`clock_timestamp()` }, + }) + .returning({ + query: searchHistory.query, + lastSearchedAt: searchHistory.lastSearchedAt, + }); + + await tx.execute(sql` + DELETE FROM search_history + WHERE user_id = ${ownerId} + AND query NOT IN ( + SELECT query FROM search_history WHERE user_id = ${ownerId} + ORDER BY last_searched_at DESC, query ASC LIMIT ${HISTORY_LIMIT} + ) + `); + if (!entry) throw new GraphQLError('Could not record search.'); + return entry; + }); +} + +export async function clearSearchHistory(db: Db, userId: string | null) { + const ownerId = requireUserId(userId); + await db.transaction(async (tx) => { + // No row means no history to clear. An overlapping first record may then + // run after this clear; clearing must not create an otherwise unused user. + await tx + .select({ id: appUser.id }) + .from(appUser) + .where(eq(appUser.id, ownerId)) + .for('update'); + await tx.delete(searchHistory).where(eq(searchHistory.userId, ownerId)); + }); + return true; +} From bd512addb1933dbdf8e07c26361fa059327c5037 Mon Sep 17 00:00:00 2001 From: Rachel Knutsen Stiansen Date: Fri, 13 Nov 2026 21:29:22 +0100 Subject: [PATCH 3/4] feat: #24 integrate search history into Discover --- client/src/App.css | 4 + client/src/App.test.tsx | 98 ++--- client/src/App.tsx | 11 +- client/src/a11y.test.tsx | 57 ++- client/src/api/client.test.ts | 35 +- client/src/api/client.ts | 3 + client/src/api/searchHistory.ts | 25 ++ client/src/components/RecentSearches.css | 103 +++-- client/src/components/RecentSearches.test.tsx | 26 +- client/src/components/RecentSearches.tsx | 125 +++++-- client/src/components/SearchForm.css | 11 + client/src/components/SearchForm.test.tsx | 27 ++ client/src/components/SearchForm.tsx | 222 ++++++++--- client/src/generated/gql.ts | 18 + client/src/generated/graphql.ts | 22 +- client/src/hooks/useSearchHistory.ts | 85 +++++ client/src/pagination.test.tsx | 53 ++- client/src/searchHistory.test.tsx | 353 ++++++++++++++++++ client/src/test/searchHistoryMocks.ts | 25 ++ e2e/tests/search.spec.ts | 4 +- 20 files changed, 1094 insertions(+), 213 deletions(-) create mode 100644 client/src/api/searchHistory.ts create mode 100644 client/src/hooks/useSearchHistory.ts create mode 100644 client/src/searchHistory.test.tsx create mode 100644 client/src/test/searchHistoryMocks.ts diff --git a/client/src/App.css b/client/src/App.css index 0287df9..9e6ae12 100644 --- a/client/src/App.css +++ b/client/src/App.css @@ -63,6 +63,8 @@ margin-inline: auto; } .search-section { + /* Keep the hero's suggestions above the catalogue's isolated album cards. */ + z-index: 1; --bg: var(--header-bg); --text: var(--header-text); --accent: var(--header-accent); @@ -147,6 +149,8 @@ text-underline-offset: 0.2em; } .catalogue-layout { + position: relative; + z-index: 0; border-top: 1px solid var(--border); padding-top: 1.25rem; } diff --git a/client/src/App.test.tsx b/client/src/App.test.tsx index fad99ab..9a39e8f 100644 --- a/client/src/App.test.tsx +++ b/client/src/App.test.tsx @@ -4,6 +4,7 @@ import { MockedProvider } from '@apollo/client/testing/react'; import type { MockLink } from '@apollo/client/testing'; import { GraphQLError } from 'graphql'; import App from './App.js'; +import { searchHistoryMocks } from './test/searchHistoryMocks.js'; import userEvent from '@testing-library/user-event'; import { SEARCH_ALBUMS } from './api/searchAlbums.js'; import type { @@ -13,6 +14,12 @@ import type { SearchAlbumsVariables, } from './api/searchAlbums.js'; +function resultStatus() { + return within( + screen.getByRole('region', { name: /^(Search results|Browse albums)$/ }), + ).getByRole('status'); +} + const album: AlbumSummary = { id: '1', title: 'Abbey Road', @@ -58,15 +65,16 @@ function renderApp( ) { return render( typeof mock.request.variables !== 'function' && mock.request.variables?.input.query === '', ) ? mocks - : [mockSearch('', []), ...mocks] - } + : [mockSearch('', []), ...mocks]), + ]} > , @@ -74,7 +82,9 @@ function renderApp( } function submitSearch(query: string) { - fireEvent.change(screen.getByRole('searchbox'), { target: { value: query } }); + fireEvent.change(screen.getByRole('combobox', { name: 'Search by album or artist' }), { + target: { value: query }, + }); fireEvent.submit(screen.getByRole('search')); } @@ -104,9 +114,7 @@ describe('App search', () => { target: { value: 'TITLE_DESC' }, }); await waitFor(() => - expect(screen.getByRole('status')).toHaveTextContent( - 'Showing 1 of 1 matching albums.', - ), + expect(resultStatus()).toHaveTextContent('Showing 1 of 1 matching albums.'), ); expect(window.location.search).toBe( '?sort=TITLE_DESC&genres=1&decades=1960&reviewed=1', @@ -205,11 +213,11 @@ describe('App search', () => { ).not.toBeInTheDocument(); expect(screen.getByRole('button', { name: 'Filters (2)' })).toHaveFocus(); await waitFor(() => - expect(screen.getByRole('status')).toHaveTextContent( - 'Showing 1 of 1 matching albums.', - ), + expect(resultStatus()).toHaveTextContent('Showing 1 of 1 matching albums.'), ); - expect(screen.getByRole('searchbox')).toHaveValue('Abbey'); + expect( + screen.getByRole('combobox', { name: 'Search by album or artist' }), + ).toHaveValue('Abbey'); expect(screen.getByRole('combobox', { name: 'Sort by' })).toHaveValue('TITLE_DESC'); }); @@ -221,9 +229,7 @@ describe('App search', () => { (mock.result as { data: SearchAlbumsData }).data.searchAlbums.totalCount = 100500; renderApp([mock]); await waitFor(() => - expect(screen.getByRole('status')).toHaveTextContent( - 'Showing 20 of 100,500 matching albums.', - ), + expect(resultStatus()).toHaveTextContent('Showing 20 of 100,500 matching albums.'), ); }); @@ -262,9 +268,7 @@ describe('App search', () => { expect(rock).toHaveFocus(); await user.keyboard(' '); await waitFor(() => - expect(screen.getByRole('status')).toHaveTextContent( - 'Showing 1 of 1 matching albums.', - ), + expect(resultStatus()).toHaveTextContent('Showing 1 of 1 matching albums.'), ); expect(window.location.search).toBe('?q=Abbey&genres=1'); expect(screen.getByRole('checkbox', { name: 'Rock 1 albums' })).toBeChecked(); @@ -280,9 +284,7 @@ describe('App search', () => { ).not.toBeInTheDocument(); await user.keyboard(' '); await waitFor(() => - expect(screen.getByRole('status')).toHaveTextContent( - 'Showing 2 of 2 matching albums.', - ), + expect(resultStatus()).toHaveTextContent('Showing 2 of 2 matching albums.'), ); expect(window.location.search).toBe('?q=Abbey'); expect(rock).toHaveFocus(); @@ -306,6 +308,7 @@ describe('App search', () => { it.each(['Enter', 'Search button'])( 'retries a failed query through %s', async (method) => { + const user = userEvent.setup(); const failed = { ...mockSearch('Abbey'), result: { errors: [new GraphQLError('Search failed')] }, @@ -315,15 +318,14 @@ describe('App search', () => { await screen.findByRole('alert'); if (method === 'Enter') { - const input = screen.getByRole('searchbox'); - input.focus(); - const defaultAllowed = fireEvent.keyDown(input, { key: 'Enter', code: 'Enter' }); - // jsdom needs the browser's implicit submission to be simulated explicitly. - if (defaultAllowed) act(() => input.form?.requestSubmit()); - fireEvent.keyUp(input, { key: 'Enter', code: 'Enter' }); + const input = screen.getByRole('combobox', { + name: 'Search by album or artist', + }); + await user.click(input); + await user.keyboard('{Enter}'); expect(input).toHaveFocus(); } else { - fireEvent.click(screen.getByRole('button', { name: 'Search' })); + await user.click(screen.getByRole('button', { name: 'Search' })); } expect( @@ -386,7 +388,7 @@ describe('App search', () => { expect(retry.parentElement).toBe(panel); expect(retry).toHaveFocus(); await waitFor(() => expect(retry).toHaveAttribute('aria-disabled', 'true')); - expect(screen.getByRole('status')).toHaveTextContent('Retrying search'); + expect(resultStatus()).toHaveTextContent('Retrying search'); expect(screen.getByRole('region', { name: 'Search results' })).toHaveAttribute( 'aria-busy', 'true', @@ -403,7 +405,7 @@ describe('App search', () => { it('loads albums initially with labelled search and accessible landmarks', async () => { renderApp([mockSearch('')]); expect( - screen.getByRole('searchbox', { name: 'Search by album or artist' }), + screen.getByRole('combobox', { name: 'Search by album or artist' }), ).toHaveValue(''); expect(screen.getByRole('main')).toHaveAttribute('id', 'main'); const hero = screen.getByRole('region', { name: 'Music worth holding onto.' }); @@ -417,7 +419,7 @@ describe('App search', () => { expect(screen.getByRole('combobox', { name: 'Sort by' })).toHaveValue( 'RELEASE_YEAR_DESC', ); - expect(screen.getByRole('status')).toHaveTextContent('Loading albums'); + expect(resultStatus()).toHaveTextContent('Loading albums'); expect(screen.getByRole('combobox', { name: 'Sort by' })).toBeInTheDocument(); expect(screen.queryByRole('checkbox')).not.toBeInTheDocument(); expect(screen.queryByRole('button', { name: 'Load more' })).not.toBeInTheDocument(); @@ -428,13 +430,21 @@ describe('App search', () => { it('writes the query to the URL on submission and not while typing', async () => { renderApp([mockSearch('Abbey')]); - fireEvent.change(screen.getByRole('searchbox'), { target: { value: 'Abb' } }); - fireEvent.change(screen.getByRole('searchbox'), { target: { value: 'Abbey' } }); + fireEvent.change( + screen.getByRole('combobox', { name: 'Search by album or artist' }), + { target: { value: 'Abb' } }, + ); + fireEvent.change( + screen.getByRole('combobox', { name: 'Search by album or artist' }), + { target: { value: 'Abbey' } }, + ); await act(() => new Promise((resolve) => setTimeout(resolve, 400))); // Typing alone touches neither the URL nor the network. expect(window.location.search).toBe(''); - expect(screen.getByRole('searchbox')).toHaveValue('Abbey'); + expect( + screen.getByRole('combobox', { name: 'Search by album or artist' }), + ).toHaveValue('Abbey'); fireEvent.submit(screen.getByRole('search')); await screen.findByRole('article', { name: 'Abbey Road' }); @@ -461,7 +471,9 @@ describe('App search', () => { it('treats a pasted whitespace-only query as no query at all', async () => { window.history.replaceState({}, '', '/?q=%20%20'); renderApp([mockSearch('')]); - expect(screen.getByRole('searchbox')).toHaveValue(''); + expect( + screen.getByRole('combobox', { name: 'Search by album or artist' }), + ).toHaveValue(''); await screen.findByRole('article', { name: 'Abbey Road' }); expect(screen.getByRole('region', { name: 'Browse albums' })).toBeInTheDocument(); }); @@ -469,7 +481,7 @@ describe('App search', () => { it('shows loading and then renders GraphQL result metadata after submission', async () => { renderApp([mockSearch('Abbey')]); submitSearch(' Abbey '); - expect(screen.getByRole('status')).toHaveTextContent('Searching albums'); + expect(resultStatus()).toHaveTextContent('Searching albums'); expect(screen.getAllByText('Searching albums…')).toHaveLength(1); expect( screen.queryByRole('button', { name: 'Retry search' }), @@ -482,9 +494,7 @@ describe('App search', () => { expect(within(card).getByText('Rock')).toBeInTheDocument(); expect(within(card).getByText('1,240 reviews')).toBeInTheDocument(); expect(card).toHaveTextContent('Average rating: 4.8 out of 5'); - expect(screen.getByRole('status')).toHaveTextContent( - 'Showing 1 of 1 matching albums.', - ); + expect(resultStatus()).toHaveTextContent('Showing 1 of 1 matching albums.'); }); it.each(['missing', ''])( @@ -510,7 +520,9 @@ describe('App search', () => { renderApp([empty, mockSearch('', [album], 'TITLE_DESC')]); await screen.findByRole('heading', { name: 'No albums found' }); fireEvent.click(screen.getByRole('button', { name: 'Reset search' })); - expect(screen.getByRole('searchbox')).toHaveValue(''); + expect( + screen.getByRole('combobox', { name: 'Search by album or artist' }), + ).toHaveValue(''); expect(window.location.search).toBe('?sort=TITLE_DESC'); expect(screen.getByRole('button', { name: 'Filters' })).toBeInTheDocument(); expect(screen.getByRole('combobox', { name: 'Sort by' })).toHaveValue('TITLE_DESC'); @@ -545,7 +557,7 @@ describe('App search', () => { submitSearch('Abbey'); expect(await screen.findByRole('alert')).toHaveTextContent('Could not load albums'); - expect(screen.getByRole('status')).toHaveTextContent('Search failed.'); + expect(resultStatus()).toHaveTextContent('Search failed.'); expect(screen.queryByText('No albums found')).not.toBeInTheDocument(); expect(screen.queryByRole('article')).not.toBeInTheDocument(); @@ -555,9 +567,7 @@ describe('App search', () => { await screen.findByRole('article', { name: 'Abbey Road' }), ).toBeInTheDocument(); expect(screen.queryByRole('alert')).not.toBeInTheDocument(); - expect(screen.getByRole('status')).toHaveTextContent( - 'Showing 1 of 1 matching albums.', - ); + expect(resultStatus()).toHaveTextContent('Showing 1 of 1 matching albums.'); }); it('re-queries the server when the sort changes and keeps it in the URL', async () => { diff --git a/client/src/App.tsx b/client/src/App.tsx index f6d7add..7c8ccbd 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -1,10 +1,11 @@ -import './App.css'; +import './App.css'; import SearchForm from './components/SearchForm.js'; import ResultsLayout from './components/ResultsLayout.js'; import { lazy, Suspense } from 'react'; import { useAlbumSearch } from './hooks/useAlbumSearch.js'; +import { useSearchHistory } from './hooks/useSearchHistory.js'; export default function App() { const basePath = import.meta.env.BASE_URL.replace(/\/$/, ''); @@ -69,6 +70,12 @@ export default function App() { function DiscoveryPage() { const search = useAlbumSearch(); + const history = useSearchHistory(); + + function submitSearch(query: string) { + search.search(query); + history.recordSearch(query); + } return (
@@ -82,7 +89,7 @@ function DiscoveryPage() {

Search, rate and collect albums you’ll want to return to.

- +

Photo by{' '} diff --git a/client/src/a11y.test.tsx b/client/src/a11y.test.tsx index a26fe2e..c2b81cd 100644 --- a/client/src/a11y.test.tsx +++ b/client/src/a11y.test.tsx @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { act, render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { MockedProvider } from '@apollo/client/testing/react'; import type { MockLink } from '@apollo/client/testing'; @@ -7,6 +7,7 @@ import { GraphQLError } from 'graphql'; import axe from 'axe-core'; import App from './App.js'; +import { searchHistoryMocks } from './test/searchHistoryMocks.js'; import { SEARCH_ALBUMS } from './api/searchAlbums.js'; import type { AlbumSummary, @@ -56,19 +57,39 @@ function mockSearch( }; } -function renderApp( +async function renderApp( mocks: MockLink.MockedResponse[] = [], ) { - return render( - + const view = render( + , ); + await waitForQueries(); + return view; } -function submitSearch(query: string) { - fireEvent.change(screen.getByRole('searchbox'), { target: { value: query } }); - fireEvent.submit(screen.getByRole('search')); +async function waitForQueries() { + // axe does not wrap React updates in act. Wait for album results and history, + // including the history refresh after a submitted search, before scanning. + await waitFor(() => { + expect( + screen.getByRole('region', { name: /^(Browse albums|Search results)$/ }), + ).toHaveAttribute('aria-busy', 'false'); + expect( + screen.getByRole('status', { name: 'Search history status' }), + ).not.toHaveTextContent('Loading recent searches'); + }); +} + +async function submitSearch(query: string) { + const user = userEvent.setup(); + await user.type( + screen.getByRole('combobox', { name: 'Search by album or artist' }), + query, + ); + await user.click(screen.getByRole('button', { name: 'Search' })); + await waitForQueries(); } /** @@ -100,13 +121,13 @@ async function expectNoViolations(container: HTMLElement) { describe('axe-core on the search page', () => { it('is clean before anything is searched', async () => { - const { container } = renderApp(); + const { container } = await renderApp(); await expectNoViolations(container); }); it('is clean with results rendered', async () => { - const { container } = renderApp([mockSearch('Abbey')]); - submitSearch('Abbey'); + const { container } = await renderApp([mockSearch('Abbey')]); + await submitSearch('Abbey'); await screen.findByRole('region', { name: 'Search results' }); await waitFor(() => @@ -117,8 +138,8 @@ describe('axe-core on the search page', () => { }); it('is clean with no results', async () => { - const { container } = renderApp([mockSearch('zzzz', [])]); - submitSearch('zzzz'); + const { container } = await renderApp([mockSearch('zzzz', [])]); + await submitSearch('zzzz'); await screen.findByRole('heading', { name: 'No albums found' }); await expectNoViolations(container); @@ -136,15 +157,15 @@ describe('axe-core on the search page', () => { }, result: { errors: [new GraphQLError('Something went wrong')] }, }; - const { container } = renderApp([failing]); - submitSearch('boom'); + const { container } = await renderApp([failing]); + await submitSearch('boom'); await screen.findByText('Could not load albums. Please try again.'); await expectNoViolations(container); }); it('is the first thing Tab reaches on the search page', async () => { - renderApp(); + await renderApp(); const user = userEvent.setup(); // One Tab from a fresh page has to land on the skip link. Checking that it @@ -155,8 +176,8 @@ describe('axe-core on the search page', () => { }); it('points the skip link at a target that exists and can take focus', async () => { - renderApp([mockSearch('Abbey')]); - submitSearch('Abbey'); + await renderApp([mockSearch('Abbey')]); + await submitSearch('Abbey'); await screen.findByRole('region', { name: 'Search results' }); const skipLink = screen.getByRole('link', { name: 'Skip to content' }); @@ -169,7 +190,7 @@ describe('axe-core on the search page', () => { // The target has to be programmatically focusable too, or the browser // scrolls to it and leaves focus stranded back in the navigation. - target!.focus(); + act(() => target!.focus()); expect(target).toHaveFocus(); }); }); diff --git a/client/src/api/client.test.ts b/client/src/api/client.test.ts index 0801752..7866446 100644 --- a/client/src/api/client.test.ts +++ b/client/src/api/client.test.ts @@ -1,9 +1,10 @@ import schemaSource from '../../../schema.graphql?raw'; import { buildSchema, validate } from 'graphql'; -import { beforeEach, describe, expect, it } from 'vitest'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; import { cache } from './client.js'; import { SEARCH_ALBUMS } from './searchAlbums.js'; +import { MY_SEARCH_HISTORY } from './searchHistory.js'; import type { AlbumSearchInput, SearchAlbumsData, @@ -65,6 +66,38 @@ it('validates the search operation against the repository schema', () => { expect(validate(schema, SEARCH_ALBUMS)).toEqual([]); }); +it('replaces complete history snapshots and clears them without affecting album results', () => { + const warn = vi.spyOn(console, 'warn'); + try { + write(result(['1'], 'cursor-1')); + const albumsBefore = read(); + const writeHistory = (queries: string[]) => + cache.writeQuery({ + query: MY_SEARCH_HISTORY, + data: { + mySearchHistory: queries.map((query) => ({ + __typename: 'SearchHistoryEntry' as const, + query, + lastSearchedAt: '2026-11-13T12:00:00Z', + })), + }, + }); + writeHistory(['Blue', 'Abbey Road']); + writeHistory(['Abbey Road']); + expect( + cache + .readQuery({ query: MY_SEARCH_HISTORY }) + ?.mySearchHistory.map((entry) => entry.query), + ).toEqual(['Abbey Road']); + writeHistory([]); + expect(cache.readQuery({ query: MY_SEARCH_HISTORY })?.mySearchHistory).toEqual([]); + expect(read()).toEqual(albumsBefore); + expect(warn).not.toHaveBeenCalled(); + } finally { + warn.mockRestore(); + } +}); + describe('searchAlbums cache policy', () => { it('appends cursor pages, deduplicates normalized albums and updates metadata', () => { write(result(['1', '2'], 'cursor-2')); diff --git a/client/src/api/client.ts b/client/src/api/client.ts index 8376513..2224901 100644 --- a/client/src/api/client.ts +++ b/client/src/api/client.ts @@ -23,6 +23,9 @@ export const cache = new InMemoryCache({ typePolicies: { Query: { fields: { + // Each response is the complete recent list, including [] after clear. + // Entries have no global IDs; replace this snapshot rather than merge it. + mySearchHistory: { merge: false }, searchAlbums: { // Each complete search input gets its own list; paging arguments do not. keyArgs: ['input'], diff --git a/client/src/api/searchHistory.ts b/client/src/api/searchHistory.ts new file mode 100644 index 0000000..a14796f --- /dev/null +++ b/client/src/api/searchHistory.ts @@ -0,0 +1,25 @@ +import { graphql } from '../generated/gql.js'; + +export const MY_SEARCH_HISTORY = graphql(` + query MySearchHistory { + mySearchHistory { + query + lastSearchedAt + } + } +`); + +export const RECORD_SEARCH = graphql(` + mutation RecordSearch($query: String!) { + recordSearch(query: $query) { + query + lastSearchedAt + } + } +`); + +export const CLEAR_SEARCH_HISTORY = graphql(` + mutation ClearSearchHistory { + clearSearchHistory + } +`); diff --git a/client/src/components/RecentSearches.css b/client/src/components/RecentSearches.css index 53a3b2d..52e48b3 100644 --- a/client/src/components/RecentSearches.css +++ b/client/src/components/RecentSearches.css @@ -1,51 +1,90 @@ -.recent-searches { - max-width: 42.5rem; - min-width: 0; - margin-top: 1rem; - color: var(--text); +.recent-searches__popover { + position: absolute; + top: calc(100% + 0.5rem); + inset-inline: 0; + z-index: 1; } -.recent-searches__header { +.recent-searches { display: flex; - align-items: center; - justify-content: space-between; - flex-wrap: wrap; - gap: 0.5rem 1rem; + flex-direction: column; + max-height: min(18rem, 45dvh); + padding: 0.25rem; + border: 1px solid var(--border-strong); + border-radius: 5px; + background: var(--surface); + color: var(--text); + box-shadow: 0 0.75rem 2rem rgb(0 0 0 / 25%); } .recent-searches h2 { margin: 0; - font-size: 1rem; + padding: 0.35rem 0.65rem; + font-size: 0.85rem; + color: var(--muted); } -.recent-searches button { - max-width: 100%; - min-height: 2.75rem; - border: 1px solid var(--border-strong); - border-radius: 5px; - background: var(--surface); +.recent-searches__list { + flex: 1 1 auto; + min-height: 0; + overflow-y: auto; + overscroll-behavior: contain; + padding: 0; + margin: 0; + list-style: none; +} +.recent-searches__header, +.search-form .recent-searches__clear { + flex-shrink: 0; +} +.recent-searches__list li { + margin: 0; +} +.search-form .recent-searches button { + display: flex; + align-items: center; + gap: 0.75rem; + width: 100%; + min-height: 2rem; + padding: 0.25rem 0.65rem; + border: 0; + background: transparent; color: var(--text); text-align: left; + white-space: normal; overflow-wrap: anywhere; + font-weight: 400; +} +.recent-searches button svg { + flex-shrink: 0; + color: var(--muted); } .recent-searches button:hover { - border-color: var(--accent); + background: var(--bg); + color: var(--accent); +} +.recent-searches [aria-selected='true'] { + background: var(--bg); color: var(--accent); + box-shadow: inset 3px 0 var(--accent); } .recent-searches button:focus-visible { outline: 3px solid var(--focus); - outline-offset: 4px; + outline-offset: -3px; } -.recent-searches__list { - display: flex; - flex-wrap: wrap; - gap: 0.75rem; - padding: 0; - margin: 0.75rem 0 0; - list-style: none; +.search-form .recent-searches__clear { + margin-top: 0.25rem; + border-top: 1px solid var(--border-strong); + border-radius: 0; + color: var(--accent); + font-size: 0.85rem; } -.recent-searches__list li { - min-width: 0; - max-width: 100%; +.recent-searches__error { + padding: 0.75rem; + border: 1px solid var(--border-strong); + border-radius: 5px; + background: var(--surface); + color: var(--text); } -.recent-searches__empty { - margin: 0.5rem 0 0; - color: var(--muted); +@media (pointer: coarse) { + .search-form .recent-searches button { + min-height: 2.75rem; + } } diff --git a/client/src/components/RecentSearches.test.tsx b/client/src/components/RecentSearches.test.tsx index 0063d0c..33d984a 100644 --- a/client/src/components/RecentSearches.test.tsx +++ b/client/src/components/RecentSearches.test.tsx @@ -18,7 +18,7 @@ describe('RecentSearches', () => { ); expect( within(region) - .getAllByRole('listitem') + .getAllByRole('option') .map((item) => item.textContent), ).toEqual(['Blue', 'Abbey Road']); }); @@ -29,20 +29,20 @@ describe('RecentSearches', () => { lastSearchedAt: entries[0]!.lastSearchedAt, })); render(); - expect(screen.getAllByRole('listitem')).toHaveLength(10); - expect(screen.queryByRole('button', { name: 'Query 10' })).not.toBeInTheDocument(); + expect(screen.getAllByRole('option')).toHaveLength(10); + expect(screen.queryByRole('option', { name: 'Query 10' })).not.toBeInTheDocument(); }); it('reports a selected query without clearing history', () => { const onSelect = vi.fn(); const onClear = vi.fn(); render(); - fireEvent.click(screen.getByRole('button', { name: 'Abbey Road' })); + fireEvent.click(screen.getByRole('option', { name: 'Abbey Road' })); expect(onSelect).toHaveBeenCalledExactlyOnceWith('Abbey Road'); expect(onClear).not.toHaveBeenCalled(); }); - it('reports clearing and displays the empty state when its props change', () => { + it('reports clearing and hides the dropdown when history becomes empty', () => { const onSelect = vi.fn(); const onClear = vi.fn(); const { rerender } = render( @@ -52,14 +52,17 @@ describe('RecentSearches', () => { expect(onClear).toHaveBeenCalledExactlyOnceWith(); expect(onSelect).not.toHaveBeenCalled(); rerender(); - expect(screen.getByText('No recent searches yet.')).toBeInTheDocument(); - expect(screen.queryByRole('list')).not.toBeInTheDocument(); + expect(screen.queryByText('No recent searches yet.')).not.toBeInTheDocument(); + expect( + screen.queryByRole('region', { name: 'Recent searches' }), + ).not.toBeInTheDocument(); + expect(screen.queryByRole('listbox')).not.toBeInTheDocument(); expect( screen.queryByRole('button', { name: 'Clear recent searches' }), ).not.toBeInTheDocument(); }); - it('supports keyboard selection and clearing without submitting a parent form', async () => { + it('keeps suggestions out of the tab order while clear remains keyboard accessible', async () => { const user = userEvent.setup(); const onSelect = vi.fn(); const onClear = vi.fn(); @@ -71,12 +74,9 @@ describe('RecentSearches', () => { ); await user.tab(); expect(screen.getByRole('button', { name: 'Clear recent searches' })).toHaveFocus(); - await user.keyboard('{Enter}'); - expect(onClear).toHaveBeenCalledOnce(); - await user.tab(); - expect(screen.getByRole('button', { name: 'Blue' })).toHaveFocus(); await user.keyboard(' '); - expect(onSelect).toHaveBeenCalledExactlyOnceWith('Blue'); + expect(onClear).toHaveBeenCalledOnce(); + expect(onSelect).not.toHaveBeenCalled(); expect(onSubmit).not.toHaveBeenCalled(); }); }); diff --git a/client/src/components/RecentSearches.tsx b/client/src/components/RecentSearches.tsx index 4e6ad70..dea8419 100644 --- a/client/src/components/RecentSearches.tsx +++ b/client/src/components/RecentSearches.tsx @@ -1,41 +1,122 @@ import './RecentSearches.css'; -import { useId } from 'react'; +import { useId, useEffect } from 'react'; interface Props { /** Distinct queries in newest-first order, as returned by the server. */ entries: readonly { query: string; lastSearchedAt: string }[]; onSelect: (query: string) => void; onClear: () => void; + loading?: boolean; + clearing?: boolean; + error?: string | null; + message?: string; + onRetry?: () => void; + id?: string; + open?: boolean; + activeIndex?: number; } -export default function RecentSearches({ entries, onSelect, onClear }: Props) { +export default function RecentSearches({ + entries, + onSelect, + onClear, + loading = false, + clearing = false, + error, + message = '', + onRetry, + id, + open = true, + activeIndex = -1, +}: Props) { const headingId = useId(); const recent = entries.slice(0, 10); + const listId = id ?? headingId + '-list'; + + useEffect(() => { + if (open && activeIndex >= 0) + document + .getElementById(`${listId}-option-${activeIndex}`) + ?.scrollIntoView?.({ block: 'nearest' }); + }, [open, activeIndex, listId]); return ( -

-
-

Recent searches

- {recent.length > 0 && ( - + + ))} + + - )} -
- {recent.length > 0 ? ( -
    - {recent.map(({ query }) => ( -
  • - -
  • - ))} -
- ) : ( -

No recent searches yet.

+
+ )} +

+ {error ?? + (clearing + ? 'Clearing recent searches…' + : loading + ? 'Loading recent searches…' + : open && recent.length > 0 + ? `${recent.length} recent searches available. Use the Up and Down arrow keys to choose, then Enter to search.` + : message)} +

+ {error && onRetry && ( + )} - + ); } diff --git a/client/src/components/SearchForm.css b/client/src/components/SearchForm.css index 967b3e8..7be5961 100644 --- a/client/src/components/SearchForm.css +++ b/client/src/components/SearchForm.css @@ -1,3 +1,7 @@ +.search-area { + max-width: 42.5rem; + min-width: 0; +} .search-form { display: flex; align-items: center; @@ -11,6 +15,13 @@ box-shadow: 0 1.125rem 3.75rem rgb(0 0 0 / 32%); } /* Input focus belongs to the whole field; the button keeps its own focus ring. */ +.search-form__field { + position: relative; + display: flex; + align-items: center; + flex: 1; + min-width: 0; +} .search-form:has(input:focus-visible) { outline: 3px solid var(--focus); outline-offset: 4px; diff --git a/client/src/components/SearchForm.test.tsx b/client/src/components/SearchForm.test.tsx index 67688b3..73e8c1f 100644 --- a/client/src/components/SearchForm.test.tsx +++ b/client/src/components/SearchForm.test.tsx @@ -18,6 +18,33 @@ function advance(milliseconds: number) { } describe('SearchForm', () => { + it('restores the selected current query over a draft without losing focus', () => { + const onSearch = vi.fn(); + render( + true, + }} + />, + ); + const input = screen.getByRole('combobox', { name: 'Search by album or artist' }); + act(() => input.focus()); + fireEvent.change(input, { target: { value: 'Unsubmitted' } }); + fireEvent.keyDown(input, { key: 'ArrowDown' }); + fireEvent.keyDown(input, { key: 'Enter' }); + expect(onSearch).toHaveBeenCalledExactlyOnceWith('Blue'); + expect(input).toHaveValue('Blue'); + expect(input).toHaveFocus(); + expect(input).toHaveAttribute('aria-expanded', 'false'); + }); + it('does not submit while typing', () => { const onSearch = vi.fn(); render(); diff --git a/client/src/components/SearchForm.tsx b/client/src/components/SearchForm.tsx index d0e148e..192a35b 100644 --- a/client/src/components/SearchForm.tsx +++ b/client/src/components/SearchForm.tsx @@ -1,71 +1,195 @@ -import './SearchForm.css'; +import './SearchForm.css'; -import { useState } from 'react'; +import { useEffect, useId, useRef, useState, type KeyboardEvent } from 'react'; +import RecentSearches from './RecentSearches.js'; interface Props { query: string; onSearch: (query: string) => void; + history?: { + entries: readonly { query: string; lastSearchedAt: string }[]; + loading: boolean; + clearing: boolean; + error: string | null; + message: string; + retry?: () => void; + clearHistory: () => Promise; + }; } -/** - * The text box and the Search button. Typing only edits a local draft: - * nothing is committed and nothing is requested until the form is submitted, - * by the button or by Enter. That keeps the URL stable while someone is - * mid-word and avoids a request per keystroke. - */ -export default function SearchForm({ query, onSearch }: Props) { +/** Keeps the editable draft and suggestion interaction local; only explicit + * submissions reach the URL and history through onSearch. */ +export default function SearchForm({ query, onSearch, history }: Props) { const [draft, setDraft] = useState(query); const [previousQuery, setPreviousQuery] = useState(query); const [composing, setComposing] = useState(false); + const [historyOpen, setHistoryOpen] = useState(false); + const [activeQuery, setActiveQuery] = useState(null); + const input = useRef(null); + const area = useRef(null); + const historyId = useId(); + const recent = history?.entries.slice(0, 10) ?? []; + const expanded = historyOpen && recent.length > 0; + const activeIndex = expanded + ? recent.findIndex((entry) => entry.query === activeQuery) + : -1; + const hasHistory = Boolean(history); - // The committed query can change without this form causing it: back/forward - // and a pasted link both move the URL. Mirror those into the input. Typing - // never commits on its own, so this cannot clobber text that is mid-edit. + // Back/forward and shared URLs update the draft without committing keystrokes. if (query !== previousQuery) { setPreviousQuery(query); setDraft(query); } + useEffect(() => { + if (!hasHistory) return; + function dismiss(event: PointerEvent) { + if (event.target instanceof Node && !area.current?.contains(event.target)) + setHistoryOpen(false); + } + document.addEventListener('pointerdown', dismiss); + return () => document.removeEventListener('pointerdown', dismiss); + }, [hasHistory]); + + function openHistory() { + setHistoryOpen(true); + setActiveQuery(null); + } + + function closeHistory() { + setHistoryOpen(false); + setActiveQuery(null); + } + + function submit(text: string) { + onSearch(text.trim()); + closeHistory(); + } + + function select(query: string) { + // Reset even when the selected query already matches the URL. + setDraft(query); + input.current?.focus(); + submit(query); + } + + function navigate(event: KeyboardEvent) { + if (composing || event.nativeEvent.isComposing || event.keyCode === 229) return; + if ((event.key === 'ArrowDown' || event.key === 'ArrowUp') && recent.length > 0) { + event.preventDefault(); + setHistoryOpen(true); + const direction = event.key === 'ArrowDown' ? 1 : -1; + const start = activeIndex < 0 ? (direction === 1 ? -1 : 0) : activeIndex; + setActiveQuery(recent[(start + direction + recent.length) % recent.length]!.query); + } else if (event.key === 'Enter' && activeIndex >= 0) { + event.preventDefault(); + select(recent[activeIndex]!.query); + } + } + + async function clearHistory() { + const previousFocus = document.activeElement; + if (await history?.clearHistory()) { + // Restore focus without taking it back from someone who moved elsewhere. + if ( + document.activeElement === previousFocus || + document.activeElement === document.body + ) + input.current?.focus(); + closeHistory(); + } + } + return ( -
{ - event.preventDefault(); - // Enter during a composition belongs to the IME, not to the form. - if (composing) return; - onSearch(draft.trim()); +
{ + if (!event.currentTarget.contains(event.relatedTarget)) closeHistory(); }} > - - - setDraft(event.target.value)} - onCompositionStart={() => setComposing(true)} - onCompositionEnd={() => setComposing(false)} - placeholder="Search by album or artist…" - /> - - +
+ + + = 0 ? `${historyId}-option-${activeIndex}` : undefined + } + onFocus={history ? openHistory : undefined} + onClick={history ? openHistory : undefined} + onKeyDown={navigate} + onChange={(event) => { + setDraft(event.target.value); + if (history) openHistory(); + }} + onCompositionStart={() => setComposing(true)} + onCompositionEnd={() => setComposing(false)} + placeholder="Search by album or artist�" + /> + {history && ( + void clearHistory()} + loading={history.loading} + clearing={history.clearing} + error={history.error} + message={history.message} + onRetry={history.retry} + /> + )} +
+ + +
); } diff --git a/client/src/generated/gql.ts b/client/src/generated/gql.ts index 8cdd9ab..a641b0f 100644 --- a/client/src/generated/gql.ts +++ b/client/src/generated/gql.ts @@ -21,6 +21,9 @@ type Documents = { "\n mutation UpsertReview($input: UpsertReviewInput!) {\n upsertReview(input: $input) {\n review {\n id\n rating\n comment\n }\n album {\n id\n }\n }\n }\n": typeof types.UpsertReviewDocument, "\n mutation DeleteReview($id: ID!) {\n deleteReview(id: $id) {\n deletedReviewId\n album {\n id\n }\n }\n }\n": typeof types.DeleteReviewDocument, "\n query SearchAlbums($input: AlbumSearchInput!, $first: Int!, $after: String) {\n searchAlbums(input: $input, first: $first, after: $after) {\n edges {\n cursor\n node {\n id\n title\n releaseYear\n musicBrainzReleaseGroupId\n artists {\n id\n name\n }\n genres {\n id\n name\n }\n averageRating\n reviewCount\n isInCrate\n }\n }\n totalCount\n genreFacets {\n genre {\n id\n name\n }\n count\n }\n decadeFacets {\n decade\n count\n }\n countryFacets {\n countryCode\n countryName\n count\n }\n reviewedCount\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n": typeof types.SearchAlbumsDocument, + "\n query MySearchHistory {\n mySearchHistory {\n query\n lastSearchedAt\n }\n }\n": typeof types.MySearchHistoryDocument, + "\n mutation RecordSearch($query: String!) {\n recordSearch(query: $query) {\n query\n lastSearchedAt\n }\n }\n": typeof types.RecordSearchDocument, + "\n mutation ClearSearchHistory {\n clearSearchHistory\n }\n": typeof types.ClearSearchHistoryDocument, }; const documents: Documents = { "\n query AlbumDetail($id: ID!, $reviewFirst: Int!, $reviewAfter: String) {\n album(id: $id) {\n id\n title\n releaseYear\n musicBrainzReleaseGroupId\n artists {\n id\n name\n }\n genres {\n id\n name\n }\n tracks {\n id\n title\n trackNumber\n durationSeconds\n }\n averageRating\n reviewCount\n isInCrate\n myReview {\n id\n rating\n comment\n }\n reviews(first: $reviewFirst, after: $reviewAfter) {\n edges {\n cursor\n node {\n id\n rating\n comment\n createdAt\n user {\n id\n displayName\n }\n }\n }\n totalCount\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n }\n": types.AlbumDetailDocument, @@ -30,6 +33,9 @@ const documents: Documents = { "\n mutation UpsertReview($input: UpsertReviewInput!) {\n upsertReview(input: $input) {\n review {\n id\n rating\n comment\n }\n album {\n id\n }\n }\n }\n": types.UpsertReviewDocument, "\n mutation DeleteReview($id: ID!) {\n deleteReview(id: $id) {\n deletedReviewId\n album {\n id\n }\n }\n }\n": types.DeleteReviewDocument, "\n query SearchAlbums($input: AlbumSearchInput!, $first: Int!, $after: String) {\n searchAlbums(input: $input, first: $first, after: $after) {\n edges {\n cursor\n node {\n id\n title\n releaseYear\n musicBrainzReleaseGroupId\n artists {\n id\n name\n }\n genres {\n id\n name\n }\n averageRating\n reviewCount\n isInCrate\n }\n }\n totalCount\n genreFacets {\n genre {\n id\n name\n }\n count\n }\n decadeFacets {\n decade\n count\n }\n countryFacets {\n countryCode\n countryName\n count\n }\n reviewedCount\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n": types.SearchAlbumsDocument, + "\n query MySearchHistory {\n mySearchHistory {\n query\n lastSearchedAt\n }\n }\n": types.MySearchHistoryDocument, + "\n mutation RecordSearch($query: String!) {\n recordSearch(query: $query) {\n query\n lastSearchedAt\n }\n }\n": types.RecordSearchDocument, + "\n mutation ClearSearchHistory {\n clearSearchHistory\n }\n": types.ClearSearchHistoryDocument, }; /** @@ -74,6 +80,18 @@ export function graphql(source: "\n mutation DeleteReview($id: ID!) {\n dele * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients. */ export function graphql(source: "\n query SearchAlbums($input: AlbumSearchInput!, $first: Int!, $after: String) {\n searchAlbums(input: $input, first: $first, after: $after) {\n edges {\n cursor\n node {\n id\n title\n releaseYear\n musicBrainzReleaseGroupId\n artists {\n id\n name\n }\n genres {\n id\n name\n }\n averageRating\n reviewCount\n isInCrate\n }\n }\n totalCount\n genreFacets {\n genre {\n id\n name\n }\n count\n }\n decadeFacets {\n decade\n count\n }\n countryFacets {\n countryCode\n countryName\n count\n }\n reviewedCount\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n"): (typeof documents)["\n query SearchAlbums($input: AlbumSearchInput!, $first: Int!, $after: String) {\n searchAlbums(input: $input, first: $first, after: $after) {\n edges {\n cursor\n node {\n id\n title\n releaseYear\n musicBrainzReleaseGroupId\n artists {\n id\n name\n }\n genres {\n id\n name\n }\n averageRating\n reviewCount\n isInCrate\n }\n }\n totalCount\n genreFacets {\n genre {\n id\n name\n }\n count\n }\n decadeFacets {\n decade\n count\n }\n countryFacets {\n countryCode\n countryName\n count\n }\n reviewedCount\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n"]; +/** + * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients. + */ +export function graphql(source: "\n query MySearchHistory {\n mySearchHistory {\n query\n lastSearchedAt\n }\n }\n"): (typeof documents)["\n query MySearchHistory {\n mySearchHistory {\n query\n lastSearchedAt\n }\n }\n"]; +/** + * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients. + */ +export function graphql(source: "\n mutation RecordSearch($query: String!) {\n recordSearch(query: $query) {\n query\n lastSearchedAt\n }\n }\n"): (typeof documents)["\n mutation RecordSearch($query: String!) {\n recordSearch(query: $query) {\n query\n lastSearchedAt\n }\n }\n"]; +/** + * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients. + */ +export function graphql(source: "\n mutation ClearSearchHistory {\n clearSearchHistory\n }\n"): (typeof documents)["\n mutation ClearSearchHistory {\n clearSearchHistory\n }\n"]; export function graphql(source: string) { return (documents as any)[source] ?? {}; diff --git a/client/src/generated/graphql.ts b/client/src/generated/graphql.ts index 38d3e0e..8bb9849 100644 --- a/client/src/generated/graphql.ts +++ b/client/src/generated/graphql.ts @@ -82,6 +82,23 @@ export type SearchAlbumsQueryVariables = Exact<{ export type SearchAlbumsQuery = { searchAlbums: { totalCount: number, reviewedCount: number, edges: Array<{ cursor: string, node: { id: string, title: string, releaseYear: number | null, musicBrainzReleaseGroupId: string | null, averageRating: number | null, reviewCount: number, isInCrate: boolean, artists: Array<{ id: string, name: string }>, genres: Array<{ id: string, name: string }> } }>, genreFacets: Array<{ count: number, genre: { id: string, name: string } }>, decadeFacets: Array<{ decade: number, count: number }>, countryFacets: Array<{ countryCode: string, countryName: string, count: number }>, pageInfo: { hasNextPage: boolean, endCursor: string | null } } }; +export type MySearchHistoryQueryVariables = Exact<{ [key: string]: never; }>; + + +export type MySearchHistoryQuery = { mySearchHistory: Array<{ query: string, lastSearchedAt: string }> }; + +export type RecordSearchMutationVariables = Exact<{ + query: string; +}>; + + +export type RecordSearchMutation = { recordSearch: { query: string, lastSearchedAt: string } }; + +export type ClearSearchHistoryMutationVariables = Exact<{ [key: string]: never; }>; + + +export type ClearSearchHistoryMutation = { clearSearchHistory: boolean }; + export const AlbumDetailDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"AlbumDetail"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"id"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"ID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"reviewFirst"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"reviewAfter"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"album"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"id"},"value":{"kind":"Variable","name":{"kind":"Name","value":"id"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"title"}},{"kind":"Field","name":{"kind":"Name","value":"releaseYear"}},{"kind":"Field","name":{"kind":"Name","value":"musicBrainzReleaseGroupId"}},{"kind":"Field","name":{"kind":"Name","value":"artists"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}},{"kind":"Field","name":{"kind":"Name","value":"genres"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}},{"kind":"Field","name":{"kind":"Name","value":"tracks"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"title"}},{"kind":"Field","name":{"kind":"Name","value":"trackNumber"}},{"kind":"Field","name":{"kind":"Name","value":"durationSeconds"}}]}},{"kind":"Field","name":{"kind":"Name","value":"averageRating"}},{"kind":"Field","name":{"kind":"Name","value":"reviewCount"}},{"kind":"Field","name":{"kind":"Name","value":"isInCrate"}},{"kind":"Field","name":{"kind":"Name","value":"myReview"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"rating"}},{"kind":"Field","name":{"kind":"Name","value":"comment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"reviews"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"first"},"value":{"kind":"Variable","name":{"kind":"Name","value":"reviewFirst"}}},{"kind":"Argument","name":{"kind":"Name","value":"after"},"value":{"kind":"Variable","name":{"kind":"Name","value":"reviewAfter"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"edges"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"cursor"}},{"kind":"Field","name":{"kind":"Name","value":"node"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"rating"}},{"kind":"Field","name":{"kind":"Name","value":"comment"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"user"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}}]}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"totalCount"}},{"kind":"Field","name":{"kind":"Name","value":"pageInfo"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"hasNextPage"}},{"kind":"Field","name":{"kind":"Name","value":"endCursor"}}]}}]}}]}}]}}]} as unknown as DocumentNode; export const AddToCrateDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"AddToCrate"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"albumId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"ID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"addToCrate"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"albumId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"albumId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"item"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}}]}},{"kind":"Field","name":{"kind":"Name","value":"album"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"isInCrate"}}]}}]}}]}}]} as unknown as DocumentNode; @@ -89,4 +106,7 @@ export const RemoveFromCrateDocument = {"kind":"Document","definitions":[{"kind" export const MyCrateDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"MyCrate"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"first"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"after"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"myCrate"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"first"},"value":{"kind":"Variable","name":{"kind":"Name","value":"first"}}},{"kind":"Argument","name":{"kind":"Name","value":"after"},"value":{"kind":"Variable","name":{"kind":"Name","value":"after"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"edges"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"cursor"}},{"kind":"Field","name":{"kind":"Name","value":"node"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"addedAt"}},{"kind":"Field","name":{"kind":"Name","value":"album"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"title"}},{"kind":"Field","name":{"kind":"Name","value":"releaseYear"}},{"kind":"Field","name":{"kind":"Name","value":"musicBrainzReleaseGroupId"}},{"kind":"Field","name":{"kind":"Name","value":"averageRating"}},{"kind":"Field","name":{"kind":"Name","value":"reviewCount"}},{"kind":"Field","name":{"kind":"Name","value":"isInCrate"}},{"kind":"Field","name":{"kind":"Name","value":"artists"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}},{"kind":"Field","name":{"kind":"Name","value":"genres"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}}]}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"pageInfo"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"hasNextPage"}},{"kind":"Field","name":{"kind":"Name","value":"endCursor"}}]}},{"kind":"Field","name":{"kind":"Name","value":"totalCount"}}]}}]}}]} as unknown as DocumentNode; export const UpsertReviewDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpsertReview"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpsertReviewInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"upsertReview"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"review"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"rating"}},{"kind":"Field","name":{"kind":"Name","value":"comment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"album"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}}]}}]}}]}}]} as unknown as DocumentNode; export const DeleteReviewDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"DeleteReview"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"id"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"ID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"deleteReview"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"id"},"value":{"kind":"Variable","name":{"kind":"Name","value":"id"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"deletedReviewId"}},{"kind":"Field","name":{"kind":"Name","value":"album"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}}]}}]}}]}}]} as unknown as DocumentNode; -export const SearchAlbumsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"SearchAlbums"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"AlbumSearchInput"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"first"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"after"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"searchAlbums"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}},{"kind":"Argument","name":{"kind":"Name","value":"first"},"value":{"kind":"Variable","name":{"kind":"Name","value":"first"}}},{"kind":"Argument","name":{"kind":"Name","value":"after"},"value":{"kind":"Variable","name":{"kind":"Name","value":"after"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"edges"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"cursor"}},{"kind":"Field","name":{"kind":"Name","value":"node"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"title"}},{"kind":"Field","name":{"kind":"Name","value":"releaseYear"}},{"kind":"Field","name":{"kind":"Name","value":"musicBrainzReleaseGroupId"}},{"kind":"Field","name":{"kind":"Name","value":"artists"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}},{"kind":"Field","name":{"kind":"Name","value":"genres"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}},{"kind":"Field","name":{"kind":"Name","value":"averageRating"}},{"kind":"Field","name":{"kind":"Name","value":"reviewCount"}},{"kind":"Field","name":{"kind":"Name","value":"isInCrate"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"totalCount"}},{"kind":"Field","name":{"kind":"Name","value":"genreFacets"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"genre"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}},{"kind":"Field","name":{"kind":"Name","value":"count"}}]}},{"kind":"Field","name":{"kind":"Name","value":"decadeFacets"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"decade"}},{"kind":"Field","name":{"kind":"Name","value":"count"}}]}},{"kind":"Field","name":{"kind":"Name","value":"countryFacets"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"countryCode"}},{"kind":"Field","name":{"kind":"Name","value":"countryName"}},{"kind":"Field","name":{"kind":"Name","value":"count"}}]}},{"kind":"Field","name":{"kind":"Name","value":"reviewedCount"}},{"kind":"Field","name":{"kind":"Name","value":"pageInfo"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"hasNextPage"}},{"kind":"Field","name":{"kind":"Name","value":"endCursor"}}]}}]}}]}}]} as unknown as DocumentNode; \ No newline at end of file +export const SearchAlbumsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"SearchAlbums"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"AlbumSearchInput"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"first"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"after"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"searchAlbums"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}},{"kind":"Argument","name":{"kind":"Name","value":"first"},"value":{"kind":"Variable","name":{"kind":"Name","value":"first"}}},{"kind":"Argument","name":{"kind":"Name","value":"after"},"value":{"kind":"Variable","name":{"kind":"Name","value":"after"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"edges"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"cursor"}},{"kind":"Field","name":{"kind":"Name","value":"node"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"title"}},{"kind":"Field","name":{"kind":"Name","value":"releaseYear"}},{"kind":"Field","name":{"kind":"Name","value":"musicBrainzReleaseGroupId"}},{"kind":"Field","name":{"kind":"Name","value":"artists"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}},{"kind":"Field","name":{"kind":"Name","value":"genres"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}},{"kind":"Field","name":{"kind":"Name","value":"averageRating"}},{"kind":"Field","name":{"kind":"Name","value":"reviewCount"}},{"kind":"Field","name":{"kind":"Name","value":"isInCrate"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"totalCount"}},{"kind":"Field","name":{"kind":"Name","value":"genreFacets"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"genre"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}},{"kind":"Field","name":{"kind":"Name","value":"count"}}]}},{"kind":"Field","name":{"kind":"Name","value":"decadeFacets"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"decade"}},{"kind":"Field","name":{"kind":"Name","value":"count"}}]}},{"kind":"Field","name":{"kind":"Name","value":"countryFacets"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"countryCode"}},{"kind":"Field","name":{"kind":"Name","value":"countryName"}},{"kind":"Field","name":{"kind":"Name","value":"count"}}]}},{"kind":"Field","name":{"kind":"Name","value":"reviewedCount"}},{"kind":"Field","name":{"kind":"Name","value":"pageInfo"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"hasNextPage"}},{"kind":"Field","name":{"kind":"Name","value":"endCursor"}}]}}]}}]}}]} as unknown as DocumentNode; +export const MySearchHistoryDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"MySearchHistory"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"mySearchHistory"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"query"}},{"kind":"Field","name":{"kind":"Name","value":"lastSearchedAt"}}]}}]}}]} as unknown as DocumentNode; +export const RecordSearchDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"RecordSearch"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"query"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"recordSearch"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"query"},"value":{"kind":"Variable","name":{"kind":"Name","value":"query"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"query"}},{"kind":"Field","name":{"kind":"Name","value":"lastSearchedAt"}}]}}]}}]} as unknown as DocumentNode; +export const ClearSearchHistoryDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"ClearSearchHistory"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"clearSearchHistory"}}]}}]} as unknown as DocumentNode; \ No newline at end of file diff --git a/client/src/hooks/useSearchHistory.ts b/client/src/hooks/useSearchHistory.ts new file mode 100644 index 0000000..3e3e07e --- /dev/null +++ b/client/src/hooks/useSearchHistory.ts @@ -0,0 +1,85 @@ +import { useRef, useState } from 'react'; +import { useMutation, useQuery } from '@apollo/client/react'; + +import { + CLEAR_SEARCH_HISTORY, + MY_SEARCH_HISTORY, + RECORD_SEARCH, +} from '../api/searchHistory.js'; + +export function useSearchHistory() { + const { + data, + loading, + error: loadError, + refetch, + } = useQuery(MY_SEARCH_HISTORY, { + fetchPolicy: 'network-only', + }); + const [record] = useMutation(RECORD_SEARCH); + const [clear, { client }] = useMutation(CLEAR_SEARCH_HISTORY); + const [clearing, setClearing] = useState(false); + const [error, setError] = useState(null); + const [message, setMessage] = useState(''); + // Preserve explicit action order, including a clear while a record is in flight. + const pending = useRef>(Promise.resolve()); + const clearPending = useRef(false); + + function recordSearch(value: string) { + const query = value.trim(); + if (!query) return; + pending.current = pending.current.then(async () => { + setError(null); + setMessage(''); + try { + await record({ variables: { query } }); + } catch { + setError('Could not save recent search. Submit it again to retry.'); + return; + } + // A failed refresh is a read error, not a failed save. useQuery exposes + // it with the load-history retry, without resubmitting the mutation. + await refetch().catch(() => {}); + }); + } + + async function clearHistory() { + if (clearPending.current) return false; + clearPending.current = true; + setClearing(true); + const task = pending.current.then(async () => { + setError(null); + setMessage(''); + try { + const result = await clear(); + if (!result.data?.clearSearchHistory) throw new Error('History was not cleared'); + client.writeQuery({ query: MY_SEARCH_HISTORY, data: { mySearchHistory: [] } }); + setMessage('Recent searches cleared.'); + return true; + } catch { + setError('Could not clear recent searches. Please try again.'); + return false; + } finally { + clearPending.current = false; + setClearing(false); + } + }); + pending.current = task; + return task; + } + + return { + entries: data?.mySearchHistory ?? [], + loading, + clearing, + error: error ?? (loadError ? 'Could not load recent searches.' : null), + message, + retry: loadError + ? () => { + void refetch().catch(() => {}); + } + : undefined, + recordSearch, + clearHistory, + }; +} diff --git a/client/src/pagination.test.tsx b/client/src/pagination.test.tsx index fe7f1e8..727ceb8 100644 --- a/client/src/pagination.test.tsx +++ b/client/src/pagination.test.tsx @@ -6,11 +6,13 @@ import { renderHook, screen, waitFor, + within, } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { MockedProvider } from '@apollo/client/testing/react'; import type { MockLink } from '@apollo/client/testing'; import App from './App.js'; +import { searchHistoryMocks } from './test/searchHistoryMocks.js'; import { cache } from './api/client.js'; import { useAlbumSearch } from './hooks/useAlbumSearch.js'; import { @@ -20,6 +22,12 @@ import { type SearchAlbumsVariables, } from './api/searchAlbums.js'; +function resultStatus() { + return within( + screen.getByRole('region', { name: /^(Search results|Browse albums)$/ }), + ).getByRole('status'); +} + const input: AlbumSearchInput = { query: 'record', sort: 'RELEVANCE' }; const searchChanges: [string, AlbumSearchInput][] = [ ['/', { ...input, query: '', sort: 'RELEASE_YEAR_DESC' }], @@ -79,7 +87,7 @@ function start( window.history.replaceState({}, '', url); // Reuse the production policies, clearing cached results for each test. render( - + , ); @@ -194,13 +202,11 @@ describe('cursor pagination', () => { await navigate(url); await findAlbum('Album other'); await navigate('?q=record'); - expect(screen.getByRole('status')).toHaveTextContent( - 'Showing 20 of 100 matching albums.', - ); + expect(resultStatus()).toHaveTextContent('Showing 20 of 100 matching albums.'); expect(screen.getAllByRole('article')).toHaveLength(20); for (const count of [40, 60]) { intersect(); - expect(screen.getByRole('status')).toHaveTextContent( + expect(resultStatus()).toHaveTextContent( `Showing ${count} of 100 matching albums.`, ); } @@ -212,9 +218,7 @@ describe('cursor pagination', () => { fireEvent.click(button); fireEvent.click(button); }); - expect(screen.getByRole('status')).toHaveTextContent( - 'Showing 80 of 100 matching albums.', - ); + expect(resultStatus()).toHaveTextContent('Showing 80 of 100 matching albums.'); for (const request of requests.slice(0, 4)) { expect(request.result).toHaveBeenCalledTimes(1); } @@ -270,17 +274,13 @@ describe('cursor pagination', () => { intersect(); await findAlbum('Album 60'); intersect(); - expect(screen.getByRole('status')).toHaveTextContent( - 'Showing 60 of 100 matching albums.', - ); + expect(resultStatus()).toHaveTextContent('Showing 60 of 100 matching albums.'); const button = screen.getByRole('button', { name: 'Load more' }); expect(button).toHaveAttribute('aria-disabled', 'false'); fireEvent.click(button); await findAlbum('Album 80'); intersect(); - expect(screen.getByRole('status')).toHaveTextContent( - 'Showing 80 of 100 matching albums.', - ); + expect(resultStatus()).toHaveTextContent('Showing 80 of 100 matching albums.'); fireEvent.click(button); await findAlbum('Album 100'); }, @@ -304,9 +304,7 @@ describe('cursor pagination', () => { intersect(); await findAlbum('Album 3'); intersect(); - expect(screen.getByRole('status')).toHaveTextContent( - 'Showing 3 of 40 matching albums.', - ); + expect(resultStatus()).toHaveTextContent('Showing 3 of 40 matching albums.'); await navigate(url); await findAlbum('Album 4'); intersect(); @@ -314,9 +312,7 @@ describe('cursor pagination', () => { intersect(); await findAlbum('Album 6'); intersect(); - expect(screen.getByRole('status')).toHaveTextContent( - 'Showing 3 of 40 matching albums.', - ); + expect(resultStatus()).toHaveTextContent('Showing 3 of 40 matching albums.'); }, ); @@ -326,7 +322,7 @@ describe('cursor pagination', () => { button.focus(); await userEvent.setup().keyboard('{Enter}'); expect(screen.getByRole('article', { name: 'Album 1' })).toBeInTheDocument(); - expect(screen.getByRole('status')).toHaveTextContent('Loading more albums'); + expect(resultStatus()).toHaveTextContent('Loading more albums'); expect(button).toHaveFocus(); await findAlbum('Album 2'); expect(screen.getAllByRole('article')).toHaveLength(2); @@ -368,21 +364,17 @@ describe('cursor pagination', () => { // Browsers scroll a newly focused button into view, notifying the observer. intersect(); expect(button).toHaveAttribute('aria-disabled', 'false'); - expect(screen.getByRole('status')).toHaveTextContent( - 'Showing 1 of 40 matching albums.', - ); + expect(resultStatus()).toHaveTextContent('Showing 1 of 40 matching albums.'); expect(result).not.toHaveBeenCalled(); await user.keyboard(key); - expect(screen.getByRole('status')).toHaveTextContent('Loading more albums'); + expect(resultStatus()).toHaveTextContent('Loading more albums'); await findAlbum('Album 2'); expect(result).toHaveBeenCalledTimes(1); expect(button).toHaveFocus(); intersect(); expect(button).toHaveAttribute('aria-disabled', 'false'); - expect(screen.getByRole('status')).toHaveTextContent( - 'Showing 2 of 40 matching albums.', - ); + expect(resultStatus()).toHaveTextContent('Showing 2 of 40 matching albums.'); }, ); @@ -412,7 +404,10 @@ describe('cursor pagination', () => { const mocks = [fullPage(20), fullPage(40), failedPage, fullPage(60)]; const { result } = renderHook(() => useAlbumSearch(), { wrapper: ({ children }) => ( - + {children} ), diff --git a/client/src/searchHistory.test.tsx b/client/src/searchHistory.test.tsx new file mode 100644 index 0000000..bba8296 --- /dev/null +++ b/client/src/searchHistory.test.tsx @@ -0,0 +1,353 @@ +import { describe, expect, it, vi } from 'vitest'; +import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import axe from 'axe-core'; +import { MockedProvider } from '@apollo/client/testing/react'; +import type { MockLink } from '@apollo/client/testing'; + +import App from './App.js'; +import { cache } from './api/client.js'; +import { + MY_SEARCH_HISTORY, + RECORD_SEARCH, + CLEAR_SEARCH_HISTORY, +} from './api/searchHistory.js'; +import { SEARCH_ALBUMS, type AlbumSearchInput } from './api/searchAlbums.js'; + +const blue = { query: 'Blue', lastSearchedAt: '2026-11-13T12:00:00Z' }; +const abbey = { query: 'Abbey Road', lastSearchedAt: '2026-11-12T12:00:00Z' }; +const input = () => screen.getByRole('combobox', { name: 'Search by album or artist' }); +const status = () => screen.getByRole('status', { name: 'Search history status' }); +const clearButton = () => screen.getByRole('button', { name: 'Clear recent searches' }); + +function history( + entries: (typeof blue)[] | Error = [blue, abbey], + delay = 0, +): MockLink.MockedResponse { + return { + request: { query: MY_SEARCH_HISTORY }, + ...(entries instanceof Error + ? { error: entries } + : { result: { data: { mySearchHistory: entries } } }), + delay, + }; +} + +function albums(query: string | AlbumSearchInput = ''): MockLink.MockedResponse { + const input = + typeof query === 'string' + ? { query, sort: query ? 'RELEVANCE' : 'RELEASE_YEAR_DESC' } + : query; + return { + request: { query: SEARCH_ALBUMS, variables: { input, first: 20, after: null } }, + result: { + data: { + searchAlbums: { + edges: [], + totalCount: 0, + genreFacets: [], + decadeFacets: [], + countryFacets: [], + reviewedCount: 0, + pageInfo: { hasNextPage: false, endCursor: null }, + }, + }, + }, + delay: 0, + }; +} + +function record(query: string, delay = 0) { + return { + request: { query: RECORD_SEARCH, variables: { query } }, + result: vi.fn(() => ({ data: { recordSearch: { ...blue, query } } })), + delay, + }; +} + +function clear(delay = 0) { + return { + request: { query: CLEAR_SEARCH_HISTORY }, + result: vi.fn(() => ({ data: { clearSearchHistory: true } })), + delay, + }; +} + +function start(mocks: MockLink.MockedResponse[], focus = true) { + const view = render( + + + , + ); + if (focus) fireEvent.focus(input()); + return view; +} + +function submit(query: string) { + fireEvent.change(input(), { target: { value: query } }); + fireEvent.submit(screen.getByRole('search')); +} + +const waitForHistory = () => + waitFor(() => expect(status()).not.toHaveTextContent('Loading')); +const waitForClear = () => + waitFor(() => expect(status()).toHaveTextContent('Recent searches cleared.')); + +describe('Discover search history', () => { + it('loads server history on fresh mounts without recording the URL query', async () => { + window.history.replaceState({}, '', '/?q=Blue'); + const saved = record('Blue'); + const view = start([albums('Blue'), history([blue], 20), saved]); + expect(status()).toHaveTextContent('Loading recent searches'); + expect(await screen.findByRole('option', { name: 'Blue' })).toBeVisible(); + expect(saved.result).not.toHaveBeenCalled(); + view.unmount(); + start([albums('Blue'), history([blue])]); + expect(await screen.findByRole('option', { name: 'Blue' })).toBeVisible(); + }); + + it('records trimmed explicit submissions, including repeats, but not typing or whitespace', async () => { + const saved = record('Blue'); + const repeated = record('Blue'); + const empty = record(''); + start([ + albums(), + history([]), + albums('Blue'), + saved, + history([blue]), + repeated, + history([blue]), + empty, + ]); + await waitForHistory(); + fireEvent.change(input(), { target: { value: 'Blue' } }); + submit(' '); + // Flush the async action queue before asserting that no mutation was sent. + await act(async () => {}); + expect(saved.result).not.toHaveBeenCalled(); + expect(empty.result).not.toHaveBeenCalled(); + expect(window.location.search).toBe(''); + submit(' Blue '); + await waitFor(() => expect(saved.result).toHaveBeenCalledOnce()); + fireEvent.focus(input()); + await screen.findByRole('option', { name: 'Blue' }); + submit('Blue'); + await waitFor(() => expect(repeated.result).toHaveBeenCalledOnce()); + }); + + it('selects history with the keyboard while preserving filters and sort', async () => { + const user = userEvent.setup(); + window.history.replaceState( + {}, + '', + '/?q=Abbey&sort=TITLE_ASC&genres=1&decades=1960&countries=GB&reviewed=1', + ); + const filters: AlbumSearchInput = { + query: 'Abbey', + sort: 'TITLE_ASC', + genreIds: ['1'], + decades: [1960], + countries: ['GB'], + hasReviews: true, + }; + start([ + albums(filters), + history([blue]), + albums({ ...filters, query: 'Blue' }), + record('Blue'), + history([blue]), + ]); + await screen.findByRole('option', { name: 'Blue' }); + await user.click(input()); + await user.keyboard('{ArrowDown}{Enter}'); + expect(Object.fromEntries(new URLSearchParams(window.location.search))).toEqual({ + q: 'Blue', + sort: 'TITLE_ASC', + genres: '1', + decades: '1960', + countries: 'GB', + reviewed: '1', + }); + expect(input()).toHaveValue('Blue'); + expect(input()).toHaveFocus(); + expect(input()).toHaveAttribute('aria-expanded', 'false'); + }); + + it('clears after an in-flight record, guards double clicks and restores focus', async () => { + const saved = record('Abbey Road', 50); + const cleared = clear(); + start([ + albums(), + history([blue]), + albums('Abbey Road'), + saved, + history([abbey, blue]), + cleared, + ]); + await screen.findByRole('option', { name: 'Blue' }); + submit('Abbey Road'); + fireEvent.focus(input()); + clearButton().focus(); + fireEvent.click(clearButton()); + fireEvent.click(clearButton()); + expect(clearButton()).toHaveAttribute('aria-disabled', 'true'); + expect(cleared.result).not.toHaveBeenCalled(); + await waitForClear(); + expect(saved.result).toHaveBeenCalledOnce(); + expect(cleared.result).toHaveBeenCalledOnce(); + expect(input()).toHaveFocus(); + expect(input()).toHaveAttribute('aria-expanded', 'false'); + expect(window.location.search).toBe('?q=Abbey+Road'); + expect(status()).toHaveClass('visually-hidden'); + }); + + it('preserves a new search submitted while clearing is in flight', async () => { + const cleared = clear(50); + const saved = record('Abbey Road'); + start([ + albums(), + history([blue]), + cleared, + albums('Abbey Road'), + saved, + history([abbey]), + ]); + await screen.findByRole('option', { name: 'Blue' }); + fireEvent.click(clearButton()); + submit('Abbey Road'); + await waitFor(() => expect(saved.result).toHaveBeenCalledOnce()); + expect(saved.result.mock.invocationCallOrder[0]).toBeGreaterThan( + cleared.result.mock.invocationCallOrder[0]!, + ); + fireEvent.focus(input()); + expect(await screen.findByRole('option', { name: 'Abbey Road' })).toBeVisible(); + expect(screen.queryByRole('option', { name: 'Blue' })).not.toBeInTheDocument(); + }); + + it('does not steal focus if the user moves away while clearing', async () => { + const user = userEvent.setup(); + start([albums(), history([blue]), clear(100)]); + await screen.findByRole('option', { name: 'Blue' }); + await user.click(clearButton()); + await user.tab(); + const search = screen.getByRole('button', { name: 'Search' }); + expect(search).toHaveFocus(); + await waitForClear(); + expect(search).toHaveFocus(); + }); + + it('keeps history and focus after a failed clear, then allows retry', async () => { + const user = userEvent.setup(); + start([ + albums(), + history([blue]), + { ...clear(), result: undefined, error: new Error('Offline') }, + clear(), + ]); + await screen.findByRole('option', { name: 'Blue' }); + await user.click(clearButton()); + await screen.findByText('Could not clear recent searches. Please try again.'); + expect(clearButton()).toHaveFocus(); + expect(screen.getByRole('option', { name: 'Blue' })).toBeVisible(); + await user.click(clearButton()); + await waitForClear(); + }); + + it.each(['initial load', 'post-save refresh'])( + 'retries a failed %s without resaving', + async (stage) => { + const user = userEvent.setup(); + const saved = record('Blue'); + const beforeFailure = + stage === 'initial load' ? [] : [history([]), albums('Blue'), saved]; + start([albums(), ...beforeFailure, history(new Error('Offline')), history([blue])]); + if (stage === 'post-save refresh') { + await waitForHistory(); + submit('Blue'); + } + await screen.findByText('Could not load recent searches.'); + expect(input()).toBeEnabled(); + await user.click(screen.getByRole('button', { name: 'Retry recent searches' })); + await waitForHistory(); + await user.click(input()); + expect(await screen.findByRole('option', { name: 'Blue' })).toBeVisible(); + expect(saved.result).toHaveBeenCalledTimes(stage === 'initial load' ? 0 : 1); + }, + ); + + it('reports save errors without losing the active search', async () => { + start([ + albums(), + history([]), + albums('Blue'), + { ...record('Blue'), result: undefined, error: new Error('Offline') }, + ]); + await waitForHistory(); + submit('Blue'); + await screen.findByText('Could not save recent search. Submit it again to retry.'); + expect(window.location.search).toBe('?q=Blue'); + expect(input()).toHaveValue('Blue'); + }); + + it('opens on focus and closes on Escape, outside clicks or focus leaving', async () => { + const user = userEvent.setup(); + start([albums(), history()], false); + await waitForHistory(); + expect(input()).toHaveAttribute('aria-expanded', 'false'); + await user.click(input()); + expect(input()).toHaveAttribute('aria-expanded', 'true'); + await user.keyboard('{Escape}'); + expect(input()).toHaveFocus(); + expect(input()).toHaveAttribute('aria-expanded', 'false'); + await user.click(input()); + fireEvent.pointerDown(document.body); + expect(input()).toHaveAttribute('aria-expanded', 'false'); + fireEvent.focus(input()); + fireEvent.blur(input(), { + relatedTarget: screen.getByRole('link', { name: 'Your crate' }), + }); + expect(input()).toHaveAttribute('aria-expanded', 'false'); + }); + + it('supports accessible arrow navigation, wrapping, Enter and mouse selection with input focus', async () => { + const user = userEvent.setup(); + const view = start([ + albums(), + history(), + albums('Abbey Road'), + record('Abbey Road'), + history([abbey, blue]), + albums('Blue'), + record('Blue'), + history(), + ]); + await screen.findByRole('option', { name: 'Blue' }); + await user.click(input()); + expect(input()).toHaveAttribute('autocomplete', 'off'); + expect(input()).toHaveAttribute('aria-controls', screen.getByRole('listbox').id); + expect( + (await axe.run(view.container, { rules: { 'color-contrast': { enabled: false } } })) + .violations, + ).toEqual([]); + await user.keyboard('{ArrowUp}'); + expect(screen.getByRole('option', { name: 'Abbey Road' })).toHaveAttribute( + 'aria-selected', + 'true', + ); + await user.keyboard('{ArrowDown}'); + const first = screen.getByRole('option', { name: 'Blue' }); + expect(first).toHaveAttribute('aria-selected', 'true'); + expect(input()).toHaveAttribute('aria-activedescendant', first.id); + await user.keyboard('{ArrowDown}{Enter}'); + expect(input()).toHaveValue('Abbey Road'); + expect(input()).toHaveFocus(); + expect(input()).not.toHaveAttribute('aria-activedescendant'); + await user.keyboard('{ArrowDown}'); + expect(input()).toHaveFocus(); + await user.click(screen.getByRole('option', { name: 'Blue' })); + expect(input()).toHaveValue('Blue'); + expect(input()).toHaveFocus(); + expect(input()).toHaveAttribute('aria-expanded', 'false'); + }); +}); diff --git a/client/src/test/searchHistoryMocks.ts b/client/src/test/searchHistoryMocks.ts new file mode 100644 index 0000000..8bd2553 --- /dev/null +++ b/client/src/test/searchHistoryMocks.ts @@ -0,0 +1,25 @@ +import type { MockLink } from '@apollo/client/testing'; +import { MY_SEARCH_HISTORY, RECORD_SEARCH } from '../api/searchHistory.js'; + +/** Default history responses for tests concerned with album results. */ +export const searchHistoryMocks: MockLink.MockedResponse[] = [ + { + request: { query: MY_SEARCH_HISTORY }, + result: { data: { mySearchHistory: [] } }, + maxUsageCount: Number.POSITIVE_INFINITY, + delay: 0, + }, + { + request: { query: RECORD_SEARCH, variables: () => true }, + result: (variables) => ({ + data: { + recordSearch: { + query: variables.query, + lastSearchedAt: '2026-11-13T12:00:00Z', + }, + }, + }), + maxUsageCount: Number.POSITIVE_INFINITY, + delay: 0, + }, +]; diff --git a/e2e/tests/search.spec.ts b/e2e/tests/search.spec.ts index 8220b37..e0d37e4 100644 --- a/e2e/tests/search.spec.ts +++ b/e2e/tests/search.spec.ts @@ -16,7 +16,7 @@ const USER_ID_STORAGE_KEY = 'crate.user-id'; const E2E_USER_ID = '00000000-0000-4000-8000-000000000e2e'; async function search(page: Page, query: string) { - await page.getByRole('searchbox', { name: 'Search by album or artist' }).fill(query); + await page.getByRole('combobox', { name: 'Search by album or artist' }).fill(query); await page.getByRole('button', { name: 'Search' }).click(); } @@ -134,7 +134,7 @@ test('keyboard only: skip link, search and open a result', async ({ page }) => { // Following it skips the header navigation and lands on the search box. await page.keyboard.press('Enter'); await page.keyboard.press('Tab'); - const searchBox = page.getByRole('searchbox', { name: 'Search by album or artist' }); + const searchBox = page.getByRole('combobox', { name: 'Search by album or artist' }); await expect(searchBox).toBeFocused(); await page.keyboard.type('abbey'); From b321c0dda9f874ef913b40cd654d2d37e4a7c60c Mon Sep 17 00:00:00 2001 From: Rachel Knutsen Stiansen Date: Fri, 13 Nov 2026 21:45:56 +0100 Subject: [PATCH 4/4] docs: #24 document search history and AI usage --- README.md | 2 ++ docs/AI-USAGE.md | 2 ++ 2 files changed, 4 insertions(+) diff --git a/README.md b/README.md index bc4b2ef..1a029dd 100644 --- a/README.md +++ b/README.md @@ -323,6 +323,8 @@ The two `AlbumDetailPage` rows represent the separate chunks for the album detai **Search and filtering:** Users can search for albums by title or artist using Search or Enter. Results can be sorted by relevance, title, release year or average rating, and filtered by genre, decade, artist country or whether an album has reviews. Search terms, sorting and filters are preserved in the URL. +**Search history:** The ten most recent distinct searches are saved per simulated user across page reloads. Users can select a recent search from the search dropdown or clear their full saved history. + **Results and pagination:** Searches initially display up to 20 albums. Additional results load automatically as the user scrolls, up to 60 albums. Load more is also available before this limit; further pages require the button. The interface provides loading, error and no-results feedback. **Album details and reviews:** Album pages display tracks, average ratings and reviews. Users can write, edit and delete their own reviews. diff --git a/docs/AI-USAGE.md b/docs/AI-USAGE.md index 00dcd09..b07b510 100644 --- a/docs/AI-USAGE.md +++ b/docs/AI-USAGE.md @@ -99,6 +99,8 @@ the part that matters most. | 2026-11-10 | rachelks | Codex (ChatGPT) | Assisted with reviewing PR #86 and implementing and testing album cover images for issue #23, including responsive images and fallback behavior. | | 2026-11-11 | rachelks | Codex (ChatGPT) | Assisted with investigating Lighthouse results for issue #23 after Roberts comment on the PR. This included improving album detail loading performance, reviewing changes and documenting the test results. | | 2026-11-12 | robertky | Codex (ChatGPT) | Helped preserve the original 500-album MusicBrainz catalog while adding country metadata to the 70 release groups missing from the regenerated snapshot. I reviewed the selected IDs and imported metadata. | +| 2026-11-12 | rachelks | Codex (ChatGPT) | Assisted with implementing search history (#24), including the GraphQL schema, database migration, backend logic and PostgreSQL tests. The implementation and test results were thoroughly reviewed throughout the process. | +| 2026-11-13 | rachelks | Codex (ChatGPT) | Assisted with #24 frontend integration, dropdown keyboard navigation, accessibility and tests, as well as debugging React/Apollo warnings and simplifying the SearchForm/DiscoveryPage responsibilities. All changes were thoroughly reviewed and tested before committing. | ## Notes