diff --git a/README.md b/README.md
index f34cf8e..2d353ce 100644
--- a/README.md
+++ b/README.md
@@ -1,7 +1,6 @@
# Kork & Krone
-**Last updated:** 24 November 2026
-**Last updated:** 24 November 2026
+**Last updated:** 26 November 2026
**Submission:** 4 (working system, ready for feedback on every aspect)
**Status:** In progress. See [Status for submission 4](#status-for-submission-4).
@@ -135,7 +134,7 @@ This section describes what users can do. "Backend" means the API supports the f
| Shared average and distribution | Done | Done | Student reviews count in the average together with X-Wines, also when sorting and filtering. The wine page shows how many gave each score |
| Wine lists: favourite, «Vil prøve» and «Har prøvd» | Done | Done | Stored per user and public, so they follow the user between browsers. Heart and bookmark on the wine cards, all three on the wine page, and each list on «Min side». The buttons change at once and go back with a message if saving fails. Visitors are sent to log in and back. «Har prøvd» takes a wine off «Vil prøve», and a saved review marks the wine as tried. A tried wine can still go back on «Vil prøve», and is then on both, as explained behind «Slik virker listene» on the wine page. See [«Vil prøve» and «Har prøvd»](#vil-prøve-and-har-prøvd). A «Vil prøve» list from before login moves to the user once. See [API](docs/api.md#wine-lists) |
| Top 4 favourites | Done | Done | Shown in its own frame on «Min side», with four numbered places. «Endre topp 4» chooses and orders them with buttons that work with the keyboard and a screen reader, without drag and drop |
-| «Min side» | Done | Done | `/mine` with the top 4, the lists and the reviews, a page for each list at `/mine/favoritter`, `/mine/vil-prove` and `/mine/har-provd`, and `/mine/dommer`, newest or oldest first. Behind login |
+| «Min side» | Done | Done | `/mine` with the top 4, the lists and the reviews, a page for each list at `/mine/favoritter`, `/mine/vil-prove` and `/mine/har-provd`, and `/mine/dommer`, newest or oldest first, with a search in the wine names and the comments. Behind login |
| User accounts | Done | Done | Register, log in and log out at `/konto`. Errors are shown next to the field they are about, in Norwegian. Sessions in PostgreSQL with an `httpOnly` cookie |
| Reviews with login | Done | Done | Only logged-in users can write, change or delete a review, and only their own. Visitors see the reviews and a link to log in, which brings them back to the wine. `User.reviews` lists a user's reviews for the profile page |
@@ -346,7 +345,7 @@ compress files at the time and the test was run over VPN. Turning on compression
| Level | Tools | What we test | Number of tests |
|---|---|---|---|
| Unit and components (frontend) | Vitest, React Testing Library, user-event, vitest-axe | URL parameters, formatting, mapping of API data, data hooks, components, the landing page, the wine page with reviews, the list buttons, «Min side», the list pages, the reviews page and «Endre topp 4», the cache rules for the lists, an expired session, loading, empty and error states, and axe on each component | 421 in 46 files |
-| Unit (backend) | Vitest | Parsing of X-Wines CSV files, building SQL for search, filtering and sorting, review validation, and passwords, sessions and rate limiting | 147 in 17 files (42 tests, 4 files skipped: they need a test database) |
+| Unit (backend) | Vitest | Parsing of X-Wines CSV files, building SQL for search, filtering and sorting and for the search in a user's reviews, review validation, and passwords, sessions and rate limiting | 147 in 17 files (42 tests, 4 files skipped: they need a test database) |
| End-to-end | Playwright with axe-core, desktop and mobile | Landing, search and detail pages with a stubbed API: one request per page load, debounce, search, filters, sorting, load more, reload, back button, from search to wine and back, the filter dialog on mobile, no hits, wine not found, API errors, keyboard use, reflow at 320 px, the wine lists (also after a reload, with login on the way, and the move of an old list), «Min side» from login to logout with the top 4 chosen with the keyboard, click targets of at least 44 × 44 px and visible focus on the main pages, and no axe violations (WCAG 2.1 AA) | 110 (6 skipped) |
| API | Vitest with Apollo Server (`executeOperation`) | Login, reviews, wine lists, the top 4 and the demo user through real GraphQL requests, with a fake browser per user that keeps the cookie. The review tests run against a separate test database (`TEST_DATABASE_URL`), see [API](docs/api.md#database-tests) | Count again |
| End-to-end with the backend | Playwright, desktop | The same pages against the real backend and a PostgreSQL test database (`TEST_DATABASE_URL`), with nothing stubbed: search, filter, sorting and «Last inn flere» on the 100 test wines, a new user with login, logout and a wrong password, a review from search to «Min side», a favourite that follows the user to another browser, and two users who review the same wine. See [API](docs/api.md#end-to-end-tests-with-the-backend) | 11 in 5 files |
diff --git a/backend/src/lists/list-query.ts b/backend/src/lists/list-query.ts
index ecc070c..e15101c 100644
--- a/backend/src/lists/list-query.ts
+++ b/backend/src/lists/list-query.ts
@@ -2,6 +2,7 @@
// like wine-query.ts, so the sort orders and the cursor can be tested without PostgreSQL.
import { GraphQLError } from 'graphql';
import { decodeIdCursor, encodeIdCursor, MAX_INTEGER } from '../connection';
+import { addParam } from '../wine-query';
import type { WineRow } from '../loaders';
import type { WineList } from './wine-lists';
@@ -100,12 +101,6 @@ export function decodeListCursor(
return { id, value };
}
-/** Adds a value to params and returns its placeholder ($1, $2, ...). Never put user input in the SQL string. */
-function addParam(params: unknown[], value: unknown): string {
- params.push(value);
- return `$${params.length}`;
-}
-
/** The parts of a query on their own lines, leaving out the ones that are false. */
const lines = (...parts: (string | false)[]) => parts.filter(Boolean).join('\n');
diff --git a/backend/src/resolvers.ts b/backend/src/resolvers.ts
index 72e08a6..a996daf 100644
--- a/backend/src/resolvers.ts
+++ b/backend/src/resolvers.ts
@@ -8,6 +8,7 @@ import type { Context } from './context';
import { setWineInList } from './lists/wine-lists';
import { type ReviewRow, type WineRow } from './loaders';
import { validateReviewInput, validateWineId, type ReviewInput } from './review-input';
+import { buildUserReviewsQuery, type ReviewOrder } from './review-query';
import {
buildFilterOptionsQueries,
buildWinesQuery,
@@ -206,34 +207,29 @@ export const resolvers = {
// User comes from auth/resolvers.ts. Fields that belong to other features are added here.
User: {
- // By when the review was given, newest or oldest first. The order is by id, which an edit
- // does not change, so editing a review while someone pages through the list neither skips
- // nor repeats one. The cursor is the id of the last review on the page, in both orders.
+ // By when the review was given, newest or oldest first, optionally only those that match a
+ // search. The SQL is built in review-query.ts. The cursor is the id of the last review on
+ // the page, in both orders.
async reviews(
user: { id: string },
- args: { first?: number | null; after?: string | null; order?: 'NEWEST' | 'OLDEST' | null },
+ args: {
+ first?: number | null;
+ after?: string | null;
+ order?: ReviewOrder | null;
+ search?: string | null;
+ },
) {
- const userId = Number(user.id);
const first = limitReviews(args.first, 10);
- const afterId = decodeIdCursor(args.after);
- // Fixed SQL for each order, never text from the request. The index review_user_id
- // (user_id, id DESC) covers both, read forwards or backwards.
- const page =
- args.order === 'OLDEST'
- ? `SELECT * FROM review
- WHERE user_id = $1 AND ($2::integer IS NULL OR id > $2)
- ORDER BY id ASC
- LIMIT $3`
- : `SELECT * FROM review
- WHERE user_id = $1 AND ($2::integer IS NULL OR id < $2)
- ORDER BY id DESC
- LIMIT $3`;
+ const query = buildUserReviewsQuery({
+ userId: Number(user.id),
+ order: args.order,
+ search: args.search,
+ first,
+ afterId: decodeIdCursor(args.after),
+ });
const [list, count] = await Promise.all([
- pool.query(page, [userId, afterId, first + 1]),
- pool.query<{ total: number }>(
- 'SELECT count(*)::int AS total FROM review WHERE user_id = $1',
- [userId],
- ),
+ pool.query(query.listSql, query.listParams),
+ pool.query<{ total: number }>(query.countSql, query.countParams),
]);
return toConnection({
rows: list.rows,
diff --git a/backend/src/review-api.db.test.ts b/backend/src/review-api.db.test.ts
index 8cd870a..9478d4a 100644
--- a/backend/src/review-api.db.test.ts
+++ b/backend/src/review-api.db.test.ts
@@ -21,8 +21,8 @@ const url = process.env.TEST_DATABASE_URL;
const SAVE = `mutation Save($input: ReviewInput!) { saveReview(input: $input) { id rating comment author } }`;
const DELETE = `mutation Delete($wineId: ID!) { deleteReview(wineId: $wineId) }`;
const MINE = `query Mine($wineId: ID!) { myReview(wineId: $wineId) { id rating comment author } }`;
-const MY_REVIEWS = `query MyReviews($first: Int, $after: String, $order: ReviewOrder) {
- me { reviews(first: $first, after: $after, order: $order) {
+const MY_REVIEWS = `query MyReviews($first: Int, $after: String, $order: ReviewOrder, $search: String) {
+ me { reviews(first: $first, after: $after, order: $order, search: $search) {
totalCount
edges { node { rating wine { id } } }
pageInfo { hasNextPage endCursor }
@@ -44,20 +44,23 @@ describe.skipIf(!url)('reviews API (PostgreSQL)', () => {
// A wine of our own with an id far above the X-Wines ids, so the tests never touch real data.
const wineId = String(900_000_000 + Math.floor(Math.random() * 1_000_000));
const otherWineId = String(Number(wineId) + 1);
+ // A name with accents, for the search.
+ const accentWineId = String(Number(wineId) + 2);
const userIds: number[] = [];
const studentIds: number[] = [];
beforeAll(async () => {
await pool.query(
`INSERT INTO wine (id, name, type, search_text)
- VALUES ($1, 'Testvin', 'Red', 'testvin'), ($2, 'Testvin 2', 'White', 'testvin 2')`,
- [wineId, otherWineId],
+ VALUES ($1, 'Testvin', 'Red', 'testvin'), ($2, 'Testvin 2', 'White', 'testvin 2'),
+ ($3, 'Château Rosé', 'Rosé', 'chateau rose')`,
+ [wineId, otherWineId, accentWineId],
);
});
// Reviews go with the wine and the users (ON DELETE CASCADE).
afterAll(async () => {
- await pool.query('DELETE FROM wine WHERE id = ANY($1)', [[wineId, otherWineId]]);
+ await pool.query('DELETE FROM wine WHERE id = ANY($1)', [[wineId, otherWineId, accentWineId]]);
await pool.query('DELETE FROM app_user WHERE id = ANY($1)', [userIds]);
await pool.query('DELETE FROM student WHERE id = ANY($1)', [studentIds]);
await pool.end();
@@ -273,6 +276,98 @@ describe.skipIf(!url)('reviews API (PostgreSQL)', () => {
expect(codeOf(await per.request(MY_REVIEWS, { order: 'BEST' }))).toBe('BAD_USER_INPUT');
});
+ describe('with a search', () => {
+ /** Three reviews by a new user, oldest first: one per wine, two with a comment. */
+ async function threeReviews(as: string) {
+ const browser = await createBrowser(as);
+ await browser.request(SAVE, save(4, 'Fyldig og rund, perfekt til LAM.'));
+ await browser.request(SAVE, {
+ input: { wineId: otherWineId, rating: 3, comment: '100% verdt det, til fisk' },
+ });
+ await browser.request(SAVE, { input: { wineId: accentWineId, rating: 5 } });
+ return browser;
+ }
+ const wineIdsOf = (page: Page) => page.edges.map((edge) => edge.node.wine.id);
+
+ it('finds a review by a word in its comment, ignoring case', async () => {
+ const kim = await threeReviews('kim');
+ const page = pageOf(await kim.request(MY_REVIEWS, { search: 'lam' }));
+ expect(wineIdsOf(page)).toEqual([wineId]);
+ expect(page.totalCount).toBe(1);
+ });
+
+ it('finds a review by the wine name, ignoring accents both ways', async () => {
+ const liv = await threeReviews('liv');
+ for (const search of ['chateau rose', 'CHÂTEAU', 'rosé']) {
+ expect(wineIdsOf(pageOf(await liv.request(MY_REVIEWS, { search })))).toEqual([
+ accentWineId,
+ ]);
+ }
+ });
+
+ it('needs every word, in the name or the comment, in any order', async () => {
+ const mia = await threeReviews('mia');
+ const ids = async (search: string) =>
+ wineIdsOf(pageOf(await mia.request(MY_REVIEWS, { search })));
+
+ expect(await ids('rund fyldig')).toEqual([wineId]);
+ // One word in the name («Testvin 2»), one in the comment.
+ expect(await ids('testvin fisk')).toEqual([otherWineId]);
+ expect(await ids('lam fisk')).toEqual([]);
+ // Both «til» comments, newest first.
+ expect(await ids('til')).toEqual([otherWineId, wineId]);
+ });
+
+ it('matches % and _ literally', async () => {
+ const nils = await threeReviews('nils');
+ expect(wineIdsOf(pageOf(await nils.request(MY_REVIEWS, { search: '100%' })))).toEqual([
+ otherWineId,
+ ]);
+ expect(pageOf(await nils.request(MY_REVIEWS, { search: '_' })).totalCount).toBe(0);
+ });
+
+ it('lists every review for a blank search', async () => {
+ const oda = await threeReviews('oda');
+ expect(pageOf(await oda.request(MY_REVIEWS, { search: ' ' })).totalCount).toBe(3);
+ });
+
+ it('never finds the reviews of another user', async () => {
+ await threeReviews('pia');
+ const rolf = await createBrowser('rolf');
+ await rolf.request(SAVE, { input: { wineId: otherWineId, rating: 2 } });
+
+ const page = pageOf(await rolf.request(MY_REVIEWS, { search: 'lam' }));
+ expect(page).toEqual({
+ totalCount: 0,
+ edges: [],
+ pageInfo: { hasNextPage: false, endCursor: null },
+ });
+ });
+
+ it('pages through the hits in both orders, and counts only hits', async () => {
+ const sol = await threeReviews('sol');
+
+ for (const [order, expected] of [
+ ['NEWEST', [otherWineId, wineId]],
+ ['OLDEST', [wineId, otherWineId]],
+ ] as const) {
+ const first = pageOf(await sol.request(MY_REVIEWS, { search: 'til', order, first: 1 }));
+ expect(first.totalCount).toBe(2);
+ expect(first.pageInfo.hasNextPage).toBe(true);
+ const second = pageOf(
+ await sol.request(MY_REVIEWS, {
+ search: 'til',
+ order,
+ first: 1,
+ after: first.pageInfo.endCursor,
+ }),
+ );
+ expect([...wineIdsOf(first), ...wineIdsOf(second)]).toEqual(expected);
+ expect(second.pageInfo.hasNextPage).toBe(false);
+ }
+ });
+ });
+
it('rejects a cursor that was not made by the API', async () => {
const ina = await createBrowser('ina');
expect(codeOf(await ina.request(MY_REVIEWS, { after: 'not-a-cursor' }))).toBe(
diff --git a/backend/src/review-query.test.ts b/backend/src/review-query.test.ts
new file mode 100644
index 0000000..ad75596
--- /dev/null
+++ b/backend/src/review-query.test.ts
@@ -0,0 +1,71 @@
+import { describe, expect, it } from 'vitest';
+import { buildUserReviewsQuery } from './review-query';
+import { MAX_SEARCH_WORDS } from './wine-query';
+
+// Which reviews a search finds is tested against PostgreSQL in review-api.db.test.ts. These tests
+// cover what can be checked without a database: the SQL that is built and its parameters.
+
+const base = { userId: 7, first: 10, afterId: null };
+
+describe('buildUserReviewsQuery', () => {
+ it('lists every review of the user, newest first, without a search', () => {
+ const query = buildUserReviewsQuery(base);
+ expect(query.listSql).toContain('WHERE review.user_id = $1');
+ expect(query.listSql).toContain('ORDER BY review.id DESC');
+ expect(query.listSql).not.toContain('JOIN');
+ expect(query.listParams).toEqual([7, 11]);
+ expect(query.countParams).toEqual([7]);
+ });
+
+ it('pages after the cursor in either order, and the count ignores the cursor', () => {
+ const newest = buildUserReviewsQuery({ ...base, afterId: 40 });
+ expect(newest.listSql).toContain('review.id < $2');
+ const oldest = buildUserReviewsQuery({ ...base, order: 'OLDEST', afterId: 40 });
+ expect(oldest.listSql).toContain('review.id > $2');
+ expect(oldest.listSql).toContain('ORDER BY review.id ASC');
+ expect(oldest.countSql).not.toContain('review.id');
+ });
+
+ it('treats a blank search as no search', () => {
+ expect(buildUserReviewsQuery({ ...base, search: ' ' })).toEqual(buildUserReviewsQuery(base));
+ });
+
+ it('needs every word in the wine name or the comment, folded like the search words', () => {
+ const query = buildUserReviewsQuery({ ...base, search: 'Chianti LAM' });
+ expect(query.listParams).toEqual([7, '%chianti%', '%lam%', 11]);
+ expect(query.listSql).toContain('(folded.wine_name LIKE $2 OR folded.comment LIKE $2)');
+ expect(query.listSql).toContain('(folded.wine_name LIKE $3 OR folded.comment LIKE $3)');
+ // The page and the count filter the same way.
+ expect(query.countSql).toContain('folded.comment LIKE $3');
+ expect(query.countParams).toEqual([7, '%chianti%', '%lam%']);
+ });
+
+ it('folds the search words: no accents, lowercase, each word once', () => {
+ expect(buildUserReviewsQuery({ ...base, search: 'Rosé ROSE rosé' }).listParams).toEqual([
+ 7,
+ '%rose%',
+ 11,
+ ]);
+ });
+
+ it('matches % and _ in the search literally', () => {
+ expect(buildUserReviewsQuery({ ...base, search: '100% a_b' }).listParams).toEqual([
+ 7,
+ '%100\\%%',
+ '%a\\_b%',
+ 11,
+ ]);
+ });
+
+ it('never puts the search text in the SQL itself', () => {
+ const query = buildUserReviewsQuery({ ...base, search: "x'; DROP TABLE review; --" });
+ expect(query.listSql).not.toContain('DROP');
+ expect(query.countSql).not.toContain('DROP');
+ });
+
+ it('uses at most MAX_SEARCH_WORDS words', () => {
+ const search = Array.from({ length: MAX_SEARCH_WORDS + 5 }, (_, i) => `ord${i}`).join(' ');
+ const { countParams } = buildUserReviewsQuery({ ...base, search });
+ expect(countParams).toHaveLength(1 + MAX_SEARCH_WORDS);
+ });
+});
diff --git a/backend/src/review-query.ts b/backend/src/review-query.ts
new file mode 100644
index 0000000..fd7dd73
--- /dev/null
+++ b/backend/src/review-query.ts
@@ -0,0 +1,69 @@
+// Builds the SQL for one page of a user's reviews (User.reviews). Kept apart from the database,
+// like wine-query.ts and lists/list-query.ts, so it can be tested without PostgreSQL.
+import { addParam, escapeLike, toSearchWords } from './wine-query';
+
+/** The same values as the GraphQL enum ReviewOrder. */
+export type ReviewOrder = 'NEWEST' | 'OLDEST';
+
+/**
+ * Text folded in SQL the same way as toSearchText in xwines-parse.ts folds it in JavaScript:
+ * split into letters and accents (NFD), without the accents, lowercase. «Rosé» and «ROSE» both
+ * become «rose», and so match the search words, which toSearchWords folds in JavaScript. As in
+ * the wine search, «å» becomes «a», while «æ» and «ø» are letters of their own and stay.
+ */
+const fold = (column: string) =>
+ `lower(regexp_replace(normalize(${column}, NFD), '[\\u0300-\\u036f]', '', 'g'))`;
+
+/** The wine's name and the comment, folded once per review, for the search to compare with. */
+const FROM_WITH_FOLDED_TEXT = `review
+ JOIN wine ON wine.id = review.wine_id
+ CROSS JOIN LATERAL (
+ SELECT ${fold('wine.name')} AS wine_name, ${fold('review.comment')} AS comment
+ ) AS folded`;
+
+export interface UserReviewsArgs {
+ userId: number;
+ order?: ReviewOrder | null;
+ /** Every word must be in the wine's name or in the comment. Blank: every review. */
+ search?: string | null;
+ first: number;
+ /** The id of the last review on the page before, from the cursor. */
+ afterId: number | null;
+}
+
+/**
+ * The SQL for one page of the user's reviews (one row more than `first`, to know if there is a
+ * next page), and for the number of matching reviews in all.
+ *
+ * The order is by id, which an edit does not change, so editing a review while someone pages
+ * neither skips nor repeats one. The index review_user_id (user_id, id DESC) finds the user's
+ * reviews, read forwards or backwards. With a search, those few reviews are then folded and
+ * compared, which needs no index of its own.
+ */
+export function buildUserReviewsQuery({ userId, order, search, first, afterId }: UserReviewsArgs) {
+ const oldestFirst = order === 'OLDEST';
+ const params: unknown[] = [];
+ const where = [`review.user_id = ${addParam(params, userId)}`];
+
+ // One condition per word, so the words can come in any order, as in the wine search. A word
+ // may be in the name and another in the comment: «chianti lam» finds Chianti «perfekt til lam».
+ const words = toSearchWords(search);
+ for (const word of words) {
+ const pattern = addParam(params, `%${escapeLike(word)}%`);
+ where.push(`(folded.wine_name LIKE ${pattern} OR folded.comment LIKE ${pattern})`);
+ }
+ const from = words.length > 0 ? FROM_WITH_FOLDED_TEXT : 'review';
+
+ const countSql = `SELECT count(*)::int AS total FROM ${from} WHERE ${where.join(' AND ')}`;
+ const countParams = [...params];
+
+ if (afterId !== null) {
+ where.push(`review.id ${oldestFirst ? '>' : '<'} ${addParam(params, afterId)}`);
+ }
+ const listSql = `SELECT review.* FROM ${from}
+ WHERE ${where.join(' AND ')}
+ ORDER BY review.id ${oldestFirst ? 'ASC' : 'DESC'}
+ LIMIT ${addParam(params, first + 1)}`;
+
+ return { listSql, listParams: params, countSql, countParams };
+}
diff --git a/backend/src/schema.ts b/backend/src/schema.ts
index 7d0048b..0f1fc3f 100644
--- a/backend/src/schema.ts
+++ b/backend/src/schema.ts
@@ -125,10 +125,12 @@ export const typeDefs = `#graphql
# User is defined in auth/schema.ts. Reviews are public, so this works for any user.
extend type User {
"""
- The user's reviews, by when they were given: newest first, or oldest first. Use
- pageInfo.endCursor as 'after' to load more, with the same order.
+ The user's reviews, by when they were given: newest first, or oldest first. 'search' keeps
+ only the reviews where every word is in the wine's name or in the comment, ignoring case and
+ accents; totalCount follows it. Use pageInfo.endCursor as 'after' to load more, with the same
+ order and search.
"""
- reviews(first: Int = 10, after: String, order: ReviewOrder = NEWEST): ReviewConnection!
+ reviews(first: Int = 10, after: String, order: ReviewOrder = NEWEST, search: String): ReviewConnection!
}
"The author is always the logged-in user, so it is not part of the input."
diff --git a/backend/src/wine-query.ts b/backend/src/wine-query.ts
index 52189f4..bd7329f 100644
--- a/backend/src/wine-query.ts
+++ b/backend/src/wine-query.ts
@@ -67,8 +67,8 @@ export function decodeCursor(cursor: string | null | undefined): number {
return offset;
}
-/** Escapes % and _ so the user's text is matched literally by ILIKE. */
-function escapeLike(text: string): string {
+/** Escapes % and _ so the user's text is matched literally by LIKE and ILIKE. */
+export function escapeLike(text: string): string {
return text.replace(/[\\%_]/g, (char) => `\\${char}`);
}
@@ -76,7 +76,7 @@ function escapeLike(text: string): string {
export const MAX_SEARCH_WORDS = 10;
/** The words of the search text, lowercase and without accents. A word is listed once. */
-function toSearchWords(search: string | null | undefined): string[] {
+export function toSearchWords(search: string | null | undefined): string[] {
const words = toSearchText(search ?? '')
.split(' ')
.filter(Boolean);
@@ -84,7 +84,7 @@ function toSearchWords(search: string | null | undefined): string[] {
}
/** Adds a value to params and returns its placeholder ($1, $2, ...). Never put user input in the SQL string. */
-function addParam(params: unknown[], value: unknown): string {
+export function addParam(params: unknown[], value: unknown): string {
params.push(value);
return `$${params.length}`;
}
diff --git a/docs/api.md b/docs/api.md
index 4708921..703f2f9 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -109,12 +109,18 @@ A user's reviews are a field on `User`. Reviews are public, so the field is mean
profiles as well. `order` is `NEWEST` (the default) or `OLDEST`, by when each review was *given*:
an edit does not move a review, so a review edited while someone pages through the list is neither
skipped nor shown twice. The cursor is the id of the last review on the page, in both orders; pass
-the same `order` with `after`.
+the same `order` and `search` with `after`.
+
+`search` keeps only the reviews where every word is in the wine's name or in the comment, in any
+order: «chianti lam» finds a Chianti with «perfekt til lam». Like the wine search, it ignores case
+and accents («rose» finds «Rosé», and «rosé» finds «rose»), and `%` and `_` are plain characters.
+«å» counts as «a», while «æ» and «ø» are letters of their own. At most 10 words are used, and a
+blank search lists every review. `totalCount` counts only the reviews that match.
```graphql
-query MyReviews($after: String, $order: ReviewOrder!) {
+query MyReviews($after: String, $order: ReviewOrder!, $search: String) {
me {
- reviews(first: 10, after: $after, order: $order) {
+ reviews(first: 10, after: $after, order: $order, search: $search) {
totalCount
edges { node { rating comment createdAt updatedAt wine { id name } } }
pageInfo { hasNextPage endCursor }
@@ -123,6 +129,15 @@ query MyReviews($after: String, $order: ReviewOrder!) {
}
```
+With the variables `{ "order": "NEWEST", "search": "lam" }`, this gives the user's reviews with
+«lam» in the wine's name or the comment, newest first.
+
+The SQL is built in `backend/src/review-query.ts`, like the wine search in `wine-query.ts`, and
+uses the same search words (`toSearchWords`). The wine's name and the comment are folded in SQL
+the same way as the words are folded in JavaScript (`normalize(…, NFD)`, the accents removed,
+lowercase), once per review. The index `review_user_id` finds the user's reviews, so the search
+only compares those few, and needs no index of its own.
+
| Error code | When |
|---|---|
| `UNAUTHENTICATED` | `saveReview` or `deleteReview` without a valid session |
@@ -216,7 +231,7 @@ In the frontend, put the page under `` in `App.tsx`, and read the u
| `auth/auth-service.test.ts` | Register, login, logout and session expiry with an in-memory store |
| `auth/auth-api.test.ts` | Real GraphQL requests through Apollo Server, with a fake browser that keeps the cookie: two browsers, logout, forged cookies, error codes, and that no field exposes the password hash |
| `auth/user-store.db.test.ts` | The SQL against PostgreSQL. Skipped unless `TEST_DATABASE_URL` is set |
-| `review-api.db.test.ts` | Reviews through Apollo Server against PostgreSQL, with one fake browser per user: login required, one review per user and wine, users cannot see or delete each other's reviews, the average follows at once, old anonymous reviews, and `User.reviews` newest or oldest first, with pages that neither skip nor repeat a review edited meanwhile. Skipped unless `TEST_DATABASE_URL` is set |
+| `review-api.db.test.ts` | Reviews through Apollo Server against PostgreSQL, with one fake browser per user: login required, one review per user and wine, users cannot see or delete each other's reviews, the average follows at once, old anonymous reviews, and `User.reviews` newest or oldest first, with pages that neither skip nor repeat a review edited meanwhile, and its search: a word in the comment, the wine's name with and without accents, every word in any order, `%` and `_` as plain characters, a blank search, never another user's reviews, and pages and counts of hits in both orders. `review-query.test.ts` checks the SQL without a database. Skipped unless `TEST_DATABASE_URL` is set |
## Wine lists
@@ -377,11 +392,12 @@ The code is in `frontend/src/features/my/`. Every page is behind `RequireAuth`.
|---|---|
| `/mine` | «Min side»: the username and «Medlem siden …», the top 4, the four newest wines on each list with «Se alle», and the four newest reviews. All in one request (`MyProfile`) |
| `/mine/favoritter`, `/mine/vil-prove`, `/mine/har-provd` | One whole list, 24 at a time with «Last inn flere». «Sorter etter»: «Sist lagt til» (the default), «Din dom», «Best vurdert» or «Navn A–Å», in the URL as `?sortering=din-dom`, `best-vurdert` or `navn`. An unknown list shows «Fant ikke listen» |
-| `/mine/dommer` | All the user's reviews, «Nyeste først» or «Eldste først» (`?sortering=eldste` in the URL), 10 at a time |
+| `/mine/dommer` | All the user's reviews, «Nyeste først» or «Eldste først» (`?sortering=eldste` in the URL), 10 at a time. «Søk i dommene dine» finds reviews by the wine's name or a word in the comment (`?q=` in the URL, as on the search page), and the live region says how many it found |
| Part | What it does |
|---|---|
| `useMyProfile` | The `MyProfile` query. The lists in it are stored by name (`User.wines` with `keyArgs: ['list', 'sort', 'minRating']`, without a sort), so they are the same ones the list pages show in the default order, and a button on a card updates both. While a list is fetched again, the page keeps what it had (`previousData`) |
+| `useDebouncedUrlText` | The search field on `/mine/dommer` and on the search page: the text is in state while the user types, and goes to the URL (with `replace`) after a 300 ms pause, or at once on Enter. The query reads only the URL. Each page says where in the URL its text goes, and keeps its other params. When the URL changes from outside (a link, the back button), the field follows it; when the hook's own change arrives late, the field keeps what the user has typed since |
| `listSort.ts` | The orders of the list pages, their labels and their values in `?sortering=`. A missing or unknown value is «Sist lagt til». `useMyWineList` leaves out `NEWEST`, the API's default, so that order shares the cache with «Min side». A change of order replaces the history entry, so the back button leaves the page, as on `/mine/dommer`. `updateListPages` changes every order of a list: a wine taken off goes from all of them, and a list a wine joined is fetched again in every order |
| `TopFavourites` | The top 4 in its own frame: always four numbered places, «Ledig plass» for a free one, and «Endre topp 4» when the user has favourites |
| `TopFavouritesEditor` | Choosing the top 4 with buttons only (no drag and drop): «Flytt opp», «Flytt ned», «Ta ut» and «Legg til», named with the wine («Flytt opp Origem Merlot»). Each change is read out in a live region, and focus stays on the button or moves to the nearest one when it is gone. Nothing is saved before «Lagre topp 4». The answer from `setTopFavourites` is the user, so «Min side» updates from it without a new request |
diff --git a/docs/manual-testing.md b/docs/manual-testing.md
index c211c5b..d9f5d8f 100644
--- a/docs/manual-testing.md
+++ b/docs/manual-testing.md
@@ -169,6 +169,11 @@ Log in as `demo` (see section 8), which has favourites, a top 4, both other list
| A list page sorted by «Din dom» | The wines you have reviewed, highest first, then the others |
| A wine on a list page sorted by name, then «Tilbake til listen» | The list, still sorted by name |
| `/mine/dommer`: «Eldste først», then reload | The oldest first, `?sortering=eldste` in the URL, and the same order after the reload |
+| `/mine/dommer`: type a word from a comment in «Søk i dommene dine» | After a short pause, only the reviews with that word, `?q=` in the URL, focus still in the field, and «Viser … for «…»» is read |
+| `/mine/dommer`: search for a wine name without accents (`chateau` for «Château») | The review of that wine |
+| `/mine/dommer`: search for a word no review has | «Ingen dommer for «…»», with the search field and the order still there |
+| `/mine/dommer` with a search: «Eldste først», then reload | The search and the order are both kept |
+| `/mine/dommer` with a search: open a wine, then «Tilbake til Mine dommer» | The same search and order as before |
| Edit an old review on its wine page, back to `/mine/dommer` | It keeps its place, with «Gitt … · endret …» |
| `/mine/noe-annet` | «Fant ikke listen», with a link to «Min side» |
diff --git a/frontend/e2e/profile.spec.ts b/frontend/e2e/profile.spec.ts
index 5655c88..cb91535 100644
--- a/frontend/e2e/profile.spec.ts
+++ b/frontend/e2e/profile.spec.ts
@@ -147,4 +147,31 @@ test.describe('Min side', () => {
await expect(myReviews(page)).toHaveText(['Rødvin 1', 'Rødvin 2']);
await expect(order).toBeFocused();
});
+
+ test('søket på «Mine dommer» står i URL-en, beholdes ved ny lasting, og følger med tilbake fra vinen', async ({
+ page,
+ }) => {
+ await openMyReviews(page);
+ const search = page.getByRole('searchbox', { name: 'Søk i dommene dine' });
+
+ // fill sets the whole word at once. The page searches after a short pause, and the
+ // assertions below wait for it, however long the machine takes.
+ await search.fill('LAM');
+ await expect(page).toHaveURL(/\/mine\/dommer\?q=LAM$/);
+ await expect(myReviews(page)).toHaveText(['Rødvin 2']);
+ await expect(page.getByRole('main').getByRole('status')).toHaveText(
+ 'Viser 1 av 1 dom for «LAM», nyeste først',
+ );
+ await expect(search).toBeFocused();
+ await expectNoAxeViolations(page);
+
+ await page.reload();
+ await expect(search).toHaveValue('LAM');
+ await expect(myReviews(page)).toHaveText(['Rødvin 2']);
+
+ await myReviews(page).first().click();
+ await page.getByRole('link', { name: 'Tilbake til Mine dommer' }).click();
+ await expect(page).toHaveURL(/\/mine\/dommer\?q=LAM$/);
+ await expect(myReviews(page)).toHaveText(['Rødvin 2']);
+ });
});
diff --git a/frontend/e2e/search.spec.ts b/frontend/e2e/search.spec.ts
index 2759cc5..5195e1a 100644
--- a/frontend/e2e/search.spec.ts
+++ b/frontend/e2e/search.spec.ts
@@ -94,11 +94,18 @@ test.describe('Søkesiden', () => {
});
test('sender bare ett søk når brukeren skriver et helt ord', async ({ page }) => {
+ await page.clock.install();
const searches = await stubApi(page);
await page.goto('./sok');
await expect(results(page).getByRole('article')).toHaveCount(24);
- await searchbox(page).pressSequentially('riesling', { delay: 30 });
+ // The page's clock stands still while the user types, so no pause between two keys can
+ // run out, however slow the machine is. Then it runs past the 300 ms pause, once.
+ await page.clock.pauseAt(await page.evaluate(() => Date.now() + 1000));
+ await searchbox(page).pressSequentially('riesling');
+ await page.clock.runFor(300);
+ await page.clock.resume();
+
await expect(page).toHaveURL(/\/sok\?q=riesling$/);
await expect(searchStatus(page)).toContainText('riesling');
diff --git a/frontend/e2e/support/fakeApi.ts b/frontend/e2e/support/fakeApi.ts
index 90579d2..8075e4d 100644
--- a/frontend/e2e/support/fakeApi.ts
+++ b/frontend/e2e/support/fakeApi.ts
@@ -47,18 +47,28 @@ const connection = (nodes: object[], type = 'Wine') => ({
pageInfo: { __typename: 'PageInfo', hasNextPage: false, endCursor: null },
});
-const myReview = (wineId: string, givenAt: string) => ({
+const myReview = (wineId: string, givenAt: string, comment: string | null = null) => ({
__typename: 'Review',
id: `r${wineId}`,
rating: 4,
- comment: null,
+ comment,
createdAt: givenAt,
updatedAt: givenAt,
wine: { __typename: 'Wine', id: wineId, name: `Rødvin ${wineId}`, type: 'Red' },
});
/** Kari's reviews on «Mine dommer», newest first. */
-const MY_REVIEWS = [myReview('2', '2026-11-20T12:00:00Z'), myReview('1', '2026-11-18T12:00:00Z')];
+const MY_REVIEWS = [
+ myReview('2', '2026-11-20T12:00:00Z', 'Perfekt til lam'),
+ myReview('1', '2026-11-18T12:00:00Z'),
+];
+
+/** A simple stand-in for the API's search: every word in the wine's name or the comment. */
+const matches = (review: (typeof MY_REVIEWS)[number], search: string) =>
+ search
+ .toLowerCase()
+ .split(' ')
+ .every((word) => `${review.wine.name} ${review.comment ?? ''}`.toLowerCase().includes(word));
const emptyReviews = {
__typename: 'ReviewConnection',
@@ -129,8 +139,9 @@ export async function fakeApi(page: Page, { loggedIn = true } = {}) {
};
},
// Two fixed reviews for «Mine dommer», newest or oldest first.
- MyReviews: ({ order }: { order: 'NEWEST' | 'OLDEST' }) => {
- const reviews = order === 'OLDEST' ? [...MY_REVIEWS].reverse() : MY_REVIEWS;
+ MyReviews: ({ order, search }: { order: 'NEWEST' | 'OLDEST'; search?: string }) => {
+ const found = MY_REVIEWS.filter((review) => !search || matches(review, search));
+ const reviews = order === 'OLDEST' ? [...found].reverse() : found;
return { data: { me: me && { ...me, reviews: connection(reviews, 'Review') } } };
},
SearchWines: () => ({ data: { wines: connection(ids.map(wine)) } }),
diff --git a/frontend/src/features/my/MyReviewsPage.test.tsx b/frontend/src/features/my/MyReviewsPage.test.tsx
index c2a48c4..254427b 100644
--- a/frontend/src/features/my/MyReviewsPage.test.tsx
+++ b/frontend/src/features/my/MyReviewsPage.test.tsx
@@ -1,12 +1,14 @@
-import { describe, expect, it } from 'vitest';
-import { render, screen, waitFor, within } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { act, render, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { MockLink } from '@apollo/client/testing';
import { MockedProvider } from '@apollo/client/testing/react';
import { MemoryRouter, Route, Routes } from 'react-router';
import { axe } from 'vitest-axe';
+import { SEARCH_DEBOUNCE_MS } from '../../hooks/useDebouncedUrlText';
import { createApolloCache } from '../../lib/apollo';
import { meMock, TEST_USER } from '../../test/authMocks';
+import { HELD_BACK } from '../../test/heldBack';
import { LocationProbe } from '../../test/LocationProbe';
import { AuthProvider } from '../auth/AuthProvider';
import { MY_REVIEWS_QUERY, REVIEWS_PAGE_SIZE, type ReviewOrder } from './api/myReviewsQuery';
@@ -16,26 +18,32 @@ const review = (id: string) => ({
__typename: 'Review',
id: `r${id}`,
rating: 4,
- comment: null,
+ comment: id === '2' ? 'Perfekt til lam' : null,
createdAt: '2026-11-18T12:00:00Z',
updatedAt: '2026-11-18T12:00:00Z',
wine: { __typename: 'Wine', id, name: `Vin ${id}`, type: 'Red' },
});
-/** One page of reviews in one order, as the API sends it. */
+/** One page of reviews in one order, and for one search, as the API sends it. */
function reviews(
order: ReviewOrder,
ids: string[],
{
totalCount = ids.length,
+ search,
after,
next,
- }: { totalCount?: number; after?: string; next?: string } = {},
+ }: { totalCount?: number; search?: string; after?: string; next?: string } = {},
): MockLink.MockedResponse {
return {
request: {
query: MY_REVIEWS_QUERY,
- variables: { first: REVIEWS_PAGE_SIZE, order, ...(after ? { after } : {}) },
+ variables: {
+ first: REVIEWS_PAGE_SIZE,
+ order,
+ ...(search ? { search } : {}),
+ ...(after ? { after } : {}),
+ },
},
result: {
data: {
@@ -62,8 +70,12 @@ function reviews(
};
}
-function renderPage(mocks: MockLink.MockedResponse[], path = '/mine/dommer') {
- const user = userEvent.setup();
+function renderPage(
+ mocks: MockLink.MockedResponse[],
+ path = '/mine/dommer',
+ userOptions: Parameters[0] = {},
+) {
+ const user = userEvent.setup(userOptions);
const result = render(
@@ -85,6 +97,8 @@ const wines = (element: HTMLElement) =>
.getAllByRole('link')
.map((link) => link.textContent);
const orderField = () => screen.getByRole('combobox', { name: 'Rekkefølge' });
+const searchField = () => screen.getByRole('searchbox', { name: 'Søk i dommene dine' });
+const location = () => screen.getByTestId('location');
describe('MyReviewsPage', () => {
it('shows the newest first, and says what the order is by', async () => {
@@ -140,6 +154,7 @@ describe('MyReviewsPage', () => {
renderPage([reviews('NEWEST', [])]);
expect(await screen.findByText(/Du har ikke gitt noen dommer ennå/)).toBeInTheDocument();
expect(screen.queryByRole('combobox')).not.toBeInTheDocument();
+ expect(screen.queryByRole('searchbox')).not.toBeInTheDocument();
});
it('has no axe violations', async () => {
@@ -148,3 +163,135 @@ describe('MyReviewsPage', () => {
expect(await axe(container)).toHaveNoViolations();
});
});
+
+describe('MyReviewsPage – searching', () => {
+ it('opens with the search from the URL, as after a reload, and says how many it found', async () => {
+ renderPage([reviews('NEWEST', ['2'], { search: 'lam' })], '/mine/dommer?q=lam');
+
+ expect(wines(await list())).toEqual(['Vin 2']);
+ expect(searchField()).toHaveValue('lam');
+ expect(screen.getByRole('status')).toHaveTextContent(
+ 'Viser 1 av 1 dom for «lam», nyeste først',
+ );
+ });
+
+ it('says so when nothing matches, and keeps the search field and the order', async () => {
+ renderPage([reviews('NEWEST', [], { search: 'ukjent' })], '/mine/dommer?q=ukjent');
+
+ expect(await screen.findByText('Ingen dommer for «ukjent»')).toHaveAttribute('role', 'status');
+ expect(searchField()).toHaveValue('ukjent');
+ expect(orderField()).toBeInTheDocument();
+ // Not the text for a user who has never given a review.
+ expect(screen.queryByText(/Du har ikke gitt noen dommer ennå/)).not.toBeInTheDocument();
+ });
+
+ it('keeps the search when the order changes', async () => {
+ const { user } = renderPage(
+ [
+ reviews('NEWEST', ['3', '2'], { search: 'vin' }),
+ reviews('OLDEST', ['2', '3'], { search: 'vin' }),
+ ],
+ '/mine/dommer?q=vin',
+ );
+ await list();
+
+ await user.selectOptions(orderField(), 'Eldste først');
+
+ await waitFor(() => expect(wines(screen.getByRole('list'))).toEqual(['Vin 2', 'Vin 3']));
+ expect(location()).toHaveTextContent('/mine/dommer?q=vin&sortering=eldste');
+ });
+
+ it('loads more within the search', async () => {
+ const { user } = renderPage(
+ [
+ reviews('NEWEST', ['3'], { search: 'vin', totalCount: 2, next: 'c3' }),
+ reviews('NEWEST', ['2'], { search: 'vin', totalCount: 2, after: 'c3' }),
+ ],
+ '/mine/dommer?q=vin',
+ );
+ await list();
+
+ await user.click(screen.getByRole('button', { name: 'Last inn flere' }));
+
+ await waitFor(() => expect(screen.getByRole('link', { name: 'Vin 2' })).toHaveFocus());
+ expect(wines(screen.getByRole('list'))).toEqual(['Vin 3', 'Vin 2']);
+ });
+
+ it('has no axe violations with a search that finds nothing', async () => {
+ const { container } = renderPage(
+ [reviews('NEWEST', [], { search: 'ukjent' })],
+ '/mine/dommer?q=ukjent',
+ );
+ await screen.findByText('Ingen dommer for «ukjent»');
+ expect(await axe(container)).toHaveNoViolations();
+ });
+
+ describe('typing', () => {
+ /*
+ * The field waits SEARCH_DEBOUNCE_MS after the last key press, as on the search page, and
+ * these tests use the same setup as SearchPage.test.tsx, so they never depend on how fast
+ * the machine is: fake timers, so the pause only ends when the test moves the clock;
+ * shouldAdvanceTime, so Testing Library and Apollo's mocks still get their time; and
+ * delay: null, so user-event types a whole word without a pause the clock could use.
+ * Each mock answers once, so a search for «l» or «la» on the way would fail the test.
+ */
+ beforeEach(() => vi.useFakeTimers({ shouldAdvanceTime: true }));
+ afterEach(() => vi.useRealTimers());
+
+ const renderTyping = (mocks: MockLink.MockedResponse[]) =>
+ renderPage(mocks, '/mine/dommer', { delay: null });
+
+ /** The user stops typing: the pause runs out and the URL is updated. */
+ const pause = () => act(() => vi.advanceTimersByTimeAsync(SEARCH_DEBOUNCE_MS));
+
+ it('searches once the user has finished typing, and keeps focus in the field', async () => {
+ const { user } = renderTyping([
+ reviews('NEWEST', ['3', '2', '1']),
+ reviews('NEWEST', ['2'], { search: 'lam' }),
+ ]);
+ await list();
+
+ await user.type(searchField(), 'lam');
+ expect(location()).toHaveTextContent(/^\/mine\/dommer$/);
+ await pause();
+
+ expect(location()).toHaveTextContent('/mine/dommer?q=lam');
+ await waitFor(() => expect(wines(screen.getByRole('list'))).toEqual(['Vin 2']));
+ expect(screen.getByRole('status')).toHaveTextContent('Viser 1 av 1 dom for «lam»');
+ expect(searchField()).toHaveFocus();
+ });
+
+ it('searches at once on Enter', async () => {
+ const { user } = renderTyping([
+ reviews('NEWEST', ['3', '2', '1']),
+ reviews('NEWEST', ['2'], { search: 'lam' }),
+ ]);
+ await list();
+
+ await user.type(searchField(), 'lam{Enter}');
+
+ expect(location()).toHaveTextContent('/mine/dommer?q=lam');
+ await waitFor(() => expect(wines(screen.getByRole('list'))).toEqual(['Vin 2']));
+ });
+
+ it('shows every review again when the field is emptied, from the cache', async () => {
+ const { user } = renderTyping([
+ reviews('NEWEST', ['3', '2', '1']),
+ reviews('NEWEST', ['2'], { search: 'lam' }),
+ // Held back: the reviews can only come from the cache.
+ { ...reviews('NEWEST', ['3', '2', '1']), delay: HELD_BACK },
+ ]);
+ await list();
+ await user.type(searchField(), 'lam{Enter}');
+ await waitFor(() => expect(wines(screen.getByRole('list'))).toEqual(['Vin 2']));
+
+ await user.clear(searchField());
+ await pause();
+
+ expect(location()).toHaveTextContent(/^\/mine\/dommer$/);
+ await waitFor(() =>
+ expect(wines(screen.getByRole('list'))).toEqual(['Vin 3', 'Vin 2', 'Vin 1']),
+ );
+ });
+ });
+});
diff --git a/frontend/src/features/my/MyReviewsPage.tsx b/frontend/src/features/my/MyReviewsPage.tsx
index ff049dc..9a3237e 100644
--- a/frontend/src/features/my/MyReviewsPage.tsx
+++ b/frontend/src/features/my/MyReviewsPage.tsx
@@ -1,6 +1,11 @@
import { useState } from 'react';
import { useSearchParams } from 'react-router';
import { useDocumentTitle } from '../../hooks/useDocumentTitle';
+import {
+ normalizeSearchText,
+ useDebouncedUrlText,
+ type UrlText,
+} from '../../hooks/useDebouncedUrlText';
import type { ReviewOrder } from './api/myReviewsQuery';
import { useMyReviews } from './api/useMyReviews';
import { MyReviewsView } from './MyReviewsView';
@@ -8,8 +13,26 @@ import { MyReviewsView } from './MyReviewsView';
/** The order in the URL: `?sortering=eldste`, or nothing for the newest first. */
const ORDER_PARAM = 'sortering';
const OLDEST = 'eldste';
+/** The search in the URL: `?q=lam`, the same name as on the search page. */
+const SEARCH_PARAM = 'q';
-/** Route component for `/mine/dommer`, behind RequireAuth. The order lives in the URL. */
+/** The params with one value set, or taken out when it is empty. The others stay. */
+function withParam(params: URLSearchParams, name: string, value: string) {
+ const next = new URLSearchParams(params);
+ if (value) next.set(name, value);
+ else next.delete(name);
+ return next;
+}
+
+const REVIEW_SEARCH: UrlText = {
+ read: (params) => normalizeSearchText(params.get(SEARCH_PARAM) ?? ''),
+ write: (params, text) => withParam(params, SEARCH_PARAM, normalizeSearchText(text)),
+};
+
+/**
+ * Route component for `/mine/dommer`, behind RequireAuth. The order and the search live in the
+ * URL, so both survive a reload and the back link from a wine.
+ */
export default function MyReviewsPage() {
useDocumentTitle('Mine dommer');
const [params, setParams] = useSearchParams();
@@ -18,12 +41,26 @@ export default function MyReviewsPage() {
const [order, setOrder] = useState(() =>
params.get(ORDER_PARAM) === OLDEST ? 'OLDEST' : 'NEWEST',
);
+ const search = useDebouncedUrlText(REVIEW_SEARCH);
function changeOrder(next: ReviewOrder) {
setOrder(next);
// Replace, not push: the back button leaves the page instead of stepping through the orders.
- setParams(next === 'OLDEST' ? { [ORDER_PARAM]: OLDEST } : {}, { replace: true });
+ // From the current URL, so a search typed meanwhile is kept.
+ setParams((current) => withParam(current, ORDER_PARAM, next === 'OLDEST' ? OLDEST : ''), {
+ replace: true,
+ });
}
- return ;
+ return (
+
+ );
}
diff --git a/frontend/src/features/my/MyReviewsView.tsx b/frontend/src/features/my/MyReviewsView.tsx
index 01a3724..5868dd3 100644
--- a/frontend/src/features/my/MyReviewsView.tsx
+++ b/frontend/src/features/my/MyReviewsView.tsx
@@ -1,6 +1,7 @@
import { useEffect, useId, useRef } from 'react';
import { Link } from 'react-router';
import { ErrorNotice } from '../../components/ui/ErrorNotice';
+import { SearchForm } from '../../components/ui/SearchForm';
import { Skeleton } from '../../components/ui/Skeleton';
import { formatCount, pluralize } from '../../lib/format';
import { buildSearchUrl } from '../../lib/searchParams';
@@ -17,26 +18,54 @@ const ORDER_LABELS: Record = {
interface MyReviewsViewProps {
order: ReviewOrder;
onChangeOrder: (order: ReviewOrder) => void;
+ /** What is in the search field right now. */
+ searchText: string;
+ onSearchTextChange: (text: string) => void;
+ /** Search at once, on Enter or «Søk». */
+ onSearch: () => void;
+ /** The search the reviews are shown for: the one in the URL. Empty for every review. */
+ search: string;
result: MyReviewsResult;
/** Can be set in tests for stable relative times. */
now?: Date;
}
-/** The text in the live region, which screen readers read when it changes. */
+/**
+ * The text in the live region, which screen readers read when it changes: also the number of
+ * hits after a search, like on the search page.
+ */
function describeStatus(
{ reviews, totalCount, loading, loadingMore }: MyReviewsResult,
order: ReviewOrder,
+ search: string,
) {
if (loading) return 'Laster dommene …';
if (loadingMore) return 'Laster flere dommer …';
+ if (totalCount === 0 && search) return `Ingen dommer for «${search}»`;
if (!totalCount) return '';
- return `Viser ${formatCount(reviews.length)} av ${pluralize(totalCount, 'dom', 'dommer')}, ${ORDER_LABELS[order].toLowerCase()}`;
+ const forSearch = search ? ` for «${search}»` : '';
+ return `Viser ${formatCount(reviews.length)} av ${pluralize(totalCount, 'dom', 'dommer')}${forSearch}, ${ORDER_LABELS[order].toLowerCase()}`;
}
-/** All the user's reviews, by when they were given, newest or oldest first. */
-export function MyReviewsView({ order, onChangeOrder, result, now }: MyReviewsViewProps) {
+/**
+ * All the user's reviews, by when they were given, newest or oldest first, with a search in the
+ * wine names and the comments.
+ */
+export function MyReviewsView({
+ order,
+ onChangeOrder,
+ searchText,
+ onSearchTextChange,
+ onSearch,
+ search,
+ result,
+ now,
+}: MyReviewsViewProps) {
const { reviews, totalCount, loading, loadingMore, hasNextPage, error, loadMoreError } = result;
const orderId = useId();
+ // The search field and the order are for a user with reviews, also when a search finds none.
+ // They stay while a new search or order loads, so focus is not lost.
+ const canSearch = totalCount !== 0 || search !== '';
// «Last inn flere» can disappear after the last page, so focus moves to the first new review.
const listRef = useRef(null);
@@ -64,25 +93,35 @@ export function MyReviewsView({ order, onChangeOrder, result, now }: MyReviewsVi
Sortert etter når du ga dommen. En endret dom beholder plassen sin.
Du har ikke gitt noen dommer ennå. Finn en vin du har smakt, og gi den stjerner.{' '}
Utforsk viner
diff --git a/frontend/src/features/my/api/myReviewsQuery.ts b/frontend/src/features/my/api/myReviewsQuery.ts
index 8dab5e5..77a51ef 100644
--- a/frontend/src/features/my/api/myReviewsQuery.ts
+++ b/frontend/src/features/my/api/myReviewsQuery.ts
@@ -22,12 +22,15 @@ export const MY_REVIEW_FIELDS = gql`
}
`;
-/** The logged-in user's reviews, one page at a time, newest or oldest first. */
+/**
+ * The logged-in user's reviews, one page at a time, newest or oldest first. With `search`, only
+ * those with every word in the wine's name or the comment (see docs/api.md).
+ */
export const MY_REVIEWS_QUERY = gql`
- query MyReviews($first: Int, $after: String, $order: ReviewOrder!) {
+ query MyReviews($first: Int, $after: String, $order: ReviewOrder!, $search: String) {
me {
id
- reviews(first: $first, after: $after, order: $order) {
+ reviews(first: $first, after: $after, order: $order, search: $search) {
totalCount
edges {
cursor
diff --git a/frontend/src/features/my/api/useMyReviews.ts b/frontend/src/features/my/api/useMyReviews.ts
index 1070326..ebbd336 100644
--- a/frontend/src/features/my/api/useMyReviews.ts
+++ b/frontend/src/features/my/api/useMyReviews.ts
@@ -22,12 +22,16 @@ export interface MyReviewsResult {
refetch: () => void;
}
-/** The logged-in user's reviews in one order, with «Last inn flere». */
-export function useMyReviews(order: ReviewOrder): MyReviewsResult {
+/**
+ * The logged-in user's reviews in one order, optionally only those that match `search`, with
+ * «Last inn flere». A blank search is left out of the request, so the reviews without a search
+ * are stored in the same place in the cache as on «Min side».
+ */
+export function useMyReviews(order: ReviewOrder, search = ''): MyReviewsResult {
const { data, error, networkStatus, fetchMore, refetch } = useQuery(
MY_REVIEWS_QUERY,
{
- variables: { first: REVIEWS_PAGE_SIZE, order },
+ variables: { first: REVIEWS_PAGE_SIZE, order, ...(search && { search }) },
// «Min side» keeps the newest reviews in the same place in the cache. Show those at once,
// but always ask for a whole page too, like the list pages.
fetchPolicy: 'cache-and-network',
@@ -35,7 +39,9 @@ export function useMyReviews(order: ReviewOrder): MyReviewsResult {
},
);
const isFetchingMore = useRef(false);
- const [failedLoad, setFailedLoad] = useState<{ order: ReviewOrder; error: Error }>();
+ // A failure belongs to the order and search it happened in, not to the others.
+ const shown = `${order}:${search}`;
+ const [failedLoad, setFailedLoad] = useState<{ shown: string; error: Error }>();
const connection = data?.me?.reviews;
async function loadMore() {
@@ -48,7 +54,7 @@ export function useMyReviews(order: ReviewOrder): MyReviewsResult {
setFailedLoad(undefined);
} catch (cause) {
// The reviews already loaded stay. The page offers to try the next page again.
- setFailedLoad({ order, error: cause instanceof Error ? cause : new Error(String(cause)) });
+ setFailedLoad({ shown, error: cause instanceof Error ? cause : new Error(String(cause)) });
} finally {
isFetchingMore.current = false;
}
@@ -61,8 +67,7 @@ export function useMyReviews(order: ReviewOrder): MyReviewsResult {
loadingMore: networkStatus === NetworkStatus.fetchMore,
hasNextPage: Boolean(connection?.pageInfo.hasNextPage),
error,
- // A failure belongs to the order it happened in, not to the other one.
- loadMoreError: failedLoad?.order === order ? failedLoad.error : undefined,
+ loadMoreError: failedLoad?.shown === shown ? failedLoad.error : undefined,
loadMore,
refetch: () => void refetch().catch(() => undefined),
};
diff --git a/frontend/src/features/search/useSearchText.ts b/frontend/src/features/search/useSearchText.ts
index d932f70..28e84bf 100644
--- a/frontend/src/features/search/useSearchText.ts
+++ b/frontend/src/features/search/useSearchText.ts
@@ -1,42 +1,16 @@
-import { useEffect, useState } from 'react';
-import { useSearchParams } from 'react-router';
+import { useDebouncedUrlText, type UrlText } from '../../hooks/useDebouncedUrlText';
import { parseSearchParams, toSearchParams } from '../../lib/searchParams';
-/** How long the field waits after the last key press before it searches. Exported for the tests. */
-export const SEARCH_DEBOUNCE_MS = 300;
+export { SEARCH_DEBOUNCE_MS } from '../../hooks/useDebouncedUrlText';
-const normalize = (text: string) => text.trim().replace(/\s+/g, ' ');
+/** The search page's text is `?q=`, kept with the filters and the sorting. */
+const SEARCH_TEXT: UrlText = {
+ read: (params) => parseSearchParams(params).q ?? '',
+ write: (params, q) => toSearchParams({ ...parseSearchParams(params), q }),
+};
-/**
- * The text in the search field. The URL is the source of truth for the search, so the
- * field has its own state only for what the user is typing right now. The URL is updated
- * when the user pauses, which keeps the number of requests down. `replace` means the
- * back button leaves the search page instead of stepping through every word.
- */
+/** The text in the search field on the search page. See useDebouncedUrlText. */
export function useSearchText() {
- const [params, setParams] = useSearchParams();
- const urlText = parseSearchParams(params).q ?? '';
- const [text, setText] = useState(urlText);
- const [lastUrlText, setLastUrlText] = useState(urlText);
-
- // The URL changed, for example with the back button. The check keeps a
- // trailing space while the user is on the way to the next word.
- if (urlText !== lastUrlText) {
- setLastUrlText(urlText);
- if (normalize(text) !== urlText) setText(urlText);
- }
-
- function search(value: string) {
- setParams(toSearchParams({ ...parseSearchParams(params), q: value }), { replace: true });
- }
-
- useEffect(() => {
- if (normalize(text) === urlText) return;
- const timer = setTimeout(() => {
- setParams(toSearchParams({ ...parseSearchParams(params), q: text }), { replace: true });
- }, SEARCH_DEBOUNCE_MS);
- return () => clearTimeout(timer);
- }, [text, urlText, params, setParams]);
-
- return { text, setText, submit: () => search(text) };
+ const { text, setText, submit } = useDebouncedUrlText(SEARCH_TEXT);
+ return { text, setText, submit };
}
diff --git a/frontend/src/features/wine/WinePage.test.tsx b/frontend/src/features/wine/WinePage.test.tsx
index 556d0b9..f520af3 100644
--- a/frontend/src/features/wine/WinePage.test.tsx
+++ b/frontend/src/features/wine/WinePage.test.tsx
@@ -257,6 +257,7 @@ describe('WinePage – tilbakelenke', () => {
['/mine', 'Tilbake til Min side'],
['/mine/favoritter', 'Tilbake til listen'],
['/mine/dommer?sortering=eldste', 'Tilbake til Mine dommer'],
+ ['/mine/dommer?q=r%C3%B8d+lam&sortering=eldste', 'Tilbake til Mine dommer'],
])('går tilbake til %s', async (from, label) => {
renderPage([found()], { pathname: '/vin/100062', state: { from } });
await heading();
@@ -272,17 +273,22 @@ describe('WinePage – tilbakelenke', () => {
);
});
- it.each(['https://evil.example', '//evil.example', 42, '/mine/../konto', '/mine/x?a='])(
- 'ignorerer ugyldig tilstand: %s',
- async (from) => {
- renderPage([found()], { pathname: '/vin/100062', state: { from } });
- await heading();
- expect(screen.getByRole('link', { name: 'Utforsk alle viner' })).toHaveAttribute(
- 'href',
- '/sok',
- );
- },
- );
+ it.each([
+ 'https://evil.example',
+ '//evil.example',
+ 42,
+ '/mine/../konto',
+ '/mine/x?a=',
+ '/mine/dommer?q=//evil.example',
+ '/mine/dommer?q=javascript:alert(1)',
+ ])('ignorerer ugyldig tilstand: %s', async (from) => {
+ renderPage([found()], { pathname: '/vin/100062', state: { from } });
+ await heading();
+ expect(screen.getByRole('link', { name: 'Utforsk alle viner' })).toHaveAttribute(
+ 'href',
+ '/sok',
+ );
+ });
});
describe('WinePage – tilstander', () => {
diff --git a/frontend/src/features/wine/WineView.tsx b/frontend/src/features/wine/WineView.tsx
index e69a636..e082c4e 100644
--- a/frontend/src/features/wine/WineView.tsx
+++ b/frontend/src/features/wine/WineView.tsx
@@ -30,9 +30,11 @@ function backLink(state: unknown) {
return { to: from, label: 'Tilbake til søket' };
}
if (from === '/mine') return { to: from, label: 'Tilbake til Min side' };
- // A list or the reviews on «Min side», with the order in the URL: /mine/favoritter,
- // /mine/dommer?sortering=eldste. Only letters, digits and dashes, so it stays on the site.
- if (typeof from === 'string' && /^\/mine\/[a-z-]+(\?[a-z0-9=&-]*)?$/.test(from)) {
+ // A list or the reviews on «Min side», with the order and the search in the URL:
+ // /mine/favoritter, /mine/dommer?sortering=eldste&q=r%C3%B8d+lam. The path is lowercase
+ // letters and dashes, and the query only what a browser puts in an encoded query: no slash,
+ // colon or angle bracket, so the link stays on the site.
+ if (typeof from === 'string' && /^\/mine\/[a-z-]+(\?[A-Za-z0-9=&%+*._~-]*)?$/.test(from)) {
return {
to: from,
label: from.startsWith('/mine/dommer') ? 'Tilbake til Mine dommer' : 'Tilbake til listen',
diff --git a/frontend/src/hooks/useDebouncedUrlText.test.tsx b/frontend/src/hooks/useDebouncedUrlText.test.tsx
new file mode 100644
index 0000000..a2e678f
--- /dev/null
+++ b/frontend/src/hooks/useDebouncedUrlText.test.tsx
@@ -0,0 +1,137 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { act, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { MemoryRouter, useNavigate } from 'react-router';
+import { LocationProbe } from '../test/LocationProbe';
+import {
+ normalizeSearchText,
+ SEARCH_DEBOUNCE_MS,
+ useDebouncedUrlText,
+ type UrlText,
+} from './useDebouncedUrlText';
+
+/*
+ * React Router changes the URL in a transition, a moment after the hook asks for it. In a test,
+ * act() makes that happen at once, so to test what happens when the user types on meanwhile, the
+ * test holds the hook's writes back and lets them through itself. Nothing here depends on how
+ * fast the machine is: the pause only ends when the test moves the fake clock.
+ */
+const held = vi.hoisted(() => ({ on: false, writes: [] as (() => void)[] }));
+
+vi.mock('react-router', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ useSearchParams: () => {
+ const [params, setParams] = actual.useSearchParams();
+ const heldSetParams: typeof setParams = (...args) => {
+ if (held.on) held.writes.push(() => setParams(...args));
+ else setParams(...args);
+ };
+ return [params, heldSetParams] as const;
+ },
+ };
+});
+
+const TEXT: UrlText = {
+ read: (params) => normalizeSearchText(params.get('q') ?? ''),
+ write: (params, text) => {
+ const next = new URLSearchParams(params);
+ const value = normalizeSearchText(text);
+ if (value) next.set('q', value);
+ else next.delete('q');
+ return next;
+ },
+};
+
+function Field() {
+ const { text, setText } = useDebouncedUrlText(TEXT);
+ const navigate = useNavigate();
+ return (
+ <>
+
+
+ >
+ );
+}
+
+function renderField() {
+ const user = userEvent.setup({ delay: null });
+ render(
+
+
+
+ ,
+ );
+ return { user, field: screen.getByRole('textbox', { name: 'Søk' }) };
+}
+
+/** The user stops typing: the pause runs out. */
+const pause = () => act(() => vi.advanceTimersByTimeAsync(SEARCH_DEBOUNCE_MS));
+/** The URL change the hook asked for arrives, late. */
+const arrive = () => act(() => held.writes.splice(0).forEach((write) => write()));
+const location = () => screen.getByTestId('location');
+
+describe('useDebouncedUrlText', () => {
+ beforeEach(() => vi.useFakeTimers({ shouldAdvanceTime: true }));
+ afterEach(() => {
+ held.on = false;
+ held.writes = [];
+ vi.useRealTimers();
+ });
+
+ it('puts the text in the URL after the pause, not on every key', async () => {
+ const { user, field } = renderField();
+
+ await user.type(field, 'pinot');
+ expect(location()).toHaveTextContent(/^\/$/);
+ await pause();
+
+ expect(location()).toHaveTextContent('/?q=pinot');
+ expect(field).toHaveValue('pinot');
+ });
+
+ it('keeps what the user typed while its own URL change was on the way', async () => {
+ const { user, field } = renderField();
+ held.on = true;
+
+ // A busy machine: the pause runs out after «p», and the user types on before the URL changes.
+ await user.type(field, 'p');
+ await pause();
+ await user.type(field, 'i');
+ await arrive();
+
+ expect(field).toHaveValue('pi');
+ await user.type(field, 'not');
+ expect(field).toHaveValue('pinot');
+
+ held.on = false;
+ await pause();
+ expect(location()).toHaveTextContent('/?q=pinot');
+ });
+
+ it('follows a change of the URL from outside, such as a link or the back button', async () => {
+ const { user, field } = renderField();
+ await user.type(field, 'pinot');
+ await pause();
+
+ await user.click(screen.getByRole('button', { name: 'Lenke til et annet søk' }));
+
+ expect(field).toHaveValue('merlot');
+ });
+
+ it('keeps a trailing space while the user is on the way to the next word', async () => {
+ const { user, field } = renderField();
+
+ await user.type(field, 'pinot ');
+ await pause();
+
+ expect(location()).toHaveTextContent('/?q=pinot');
+ expect(field).toHaveValue('pinot ');
+ });
+});
diff --git a/frontend/src/hooks/useDebouncedUrlText.ts b/frontend/src/hooks/useDebouncedUrlText.ts
new file mode 100644
index 0000000..502fe60
--- /dev/null
+++ b/frontend/src/hooks/useDebouncedUrlText.ts
@@ -0,0 +1,61 @@
+import { useEffect, useState } from 'react';
+import { useSearchParams } from 'react-router';
+
+/** How long a search field waits after the last key press before it searches. Exported for the tests. */
+export const SEARCH_DEBOUNCE_MS = 300;
+
+/** Search text as it is put in the URL: no spaces at the ends, and one space between words. */
+export const normalizeSearchText = (text: string) => text.trim().replace(/\s+/g, ' ');
+
+/** Where a page keeps its search text in the URL. */
+export interface UrlText {
+ /** The search text in the URL, already normalized. */
+ read: (params: URLSearchParams) => string;
+ /** The URL's params with a new search text, keeping the other params of the page. */
+ write: (params: URLSearchParams, text: string) => URLSearchParams;
+}
+
+/**
+ * The text in a search field whose search lives in the URL. The URL is the source of truth for
+ * the search, so the field has its own state only for what the user is typing right now. The
+ * URL is updated when the user pauses, which keeps the number of requests down. `replace` means
+ * the back button leaves the page instead of stepping through every word.
+ *
+ * `url` must be the same object on every render (define it outside the component), or each
+ * render would start the pause again.
+ */
+export function useDebouncedUrlText(url: UrlText) {
+ const [params, setParams] = useSearchParams();
+ const urlText = url.read(params);
+ const [text, setText] = useState(urlText);
+ const [lastUrlText, setLastUrlText] = useState(urlText);
+ // The text this hook last put in the URL. React Router changes the URL in a transition, a
+ // moment later, and on a busy machine the user may have typed on meanwhile.
+ const [written, setWritten] = useState(null);
+
+ // The URL changed. If it changed from outside, for example with the back button, the field
+ // follows it. If it is the text this hook wrote, arriving late, the field keeps what the user
+ // has typed since: resetting it would lose those key presses («pinot» became «pnot»). The
+ // check on the text keeps a trailing space while the user is on the way to the next word.
+ if (urlText !== lastUrlText) {
+ setLastUrlText(urlText);
+ if (urlText !== written && normalizeSearchText(text) !== urlText) setText(urlText);
+ }
+
+ function search(value: string) {
+ setWritten(normalizeSearchText(value));
+ setParams(url.write(params, value), { replace: true });
+ }
+
+ useEffect(() => {
+ if (normalizeSearchText(text) === urlText) return;
+ const timer = setTimeout(() => {
+ setWritten(normalizeSearchText(text));
+ setParams(url.write(params, text), { replace: true });
+ }, SEARCH_DEBOUNCE_MS);
+ return () => clearTimeout(timer);
+ }, [text, urlText, params, setParams, url]);
+
+ /** `search` is the search in the URL, which the page shows results for. */
+ return { text, setText, submit: () => search(text), search: urlText };
+}
diff --git a/frontend/src/lib/apollo.test.ts b/frontend/src/lib/apollo.test.ts
index b4c6fb5..9f3e600 100644
--- a/frontend/src/lib/apollo.test.ts
+++ b/frontend/src/lib/apollo.test.ts
@@ -148,6 +148,62 @@ describe('createApolloCache – User.wines', () => {
});
});
+describe('createApolloCache – User.reviews', () => {
+ const REVIEWS = gql`
+ query Reviews($order: ReviewOrder!, $search: String) {
+ me {
+ id
+ reviews(order: $order, search: $search) {
+ totalCount
+ edges {
+ cursor
+ node {
+ id
+ }
+ }
+ }
+ }
+ }
+ `;
+ const write = (cache: ReturnType, ids: string[], search?: string) =>
+ cache.writeQuery({
+ query: REVIEWS,
+ variables: { order: 'NEWEST', search },
+ data: {
+ me: {
+ __typename: 'User',
+ id: '1',
+ reviews: {
+ __typename: 'ReviewConnection',
+ totalCount: ids.length,
+ edges: ids.map((id) => ({
+ __typename: 'ReviewEdge',
+ cursor: id,
+ node: { __typename: 'Review', id },
+ })),
+ },
+ },
+ },
+ });
+ const idsOf = (cache: ReturnType, search?: string) =>
+ cache
+ .readQuery<{ me: { reviews: { edges: { node: { id: string } }[] } } }>({
+ query: REVIEWS,
+ variables: { order: 'NEWEST', search },
+ })
+ ?.me.reviews.edges.map((edge) => edge.node.id);
+
+ it('keeps each search apart, and the reviews without a search where «Min side» has them', () => {
+ const cache = createApolloCache();
+ write(cache, ['3', '2', '1']);
+ write(cache, ['2'], 'lam');
+
+ expect(idsOf(cache)).toEqual(['3', '2', '1']);
+ expect(idsOf(cache, 'lam')).toEqual(['2']);
+ expect(cache.extract()['User:1']).toHaveProperty(['reviews:{"order":"NEWEST"}']);
+ });
+});
+
describe('createSessionLink', () => {
const ME = gql`
query Me {
diff --git a/frontend/src/lib/apollo.ts b/frontend/src/lib/apollo.ts
index 2d7dfb8..2a9f65e 100644
--- a/frontend/src/lib/apollo.ts
+++ b/frontend/src/lib/apollo.ts
@@ -48,9 +48,10 @@ export function createApolloCache() {
return mergeWineConnection(existing, incoming, args?.after as string | undefined);
},
},
- // The user's reviews, one list per order, with the pages added after each other.
+ // The user's reviews, one list per order and search, with the pages added after each
+ // other. Without a search, the newest first is shared with «Min side».
reviews: {
- keyArgs: ['order'],
+ keyArgs: ['order', 'search'],
merge(existing: WineConnection | undefined, incoming: WineConnection, { args }) {
return mergeWineConnection(existing, incoming, args?.after as string | undefined);
},