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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -335,9 +335,11 @@ Choices and why:
Known limit: a rating can change while someone pages (a new review changes the shared rating).
The wine then moves in the order, and the next page can miss it or have it again. The frontend
leaves out a wine it already has when a page is added (`mergeWineConnection` in
`frontend/src/lib/apollo.ts`), so it is never shown twice, and a reload gives the right order. The list pages on «Min
side» do not use `sort` yet. When they do, add `sort` and `minRating` to `keyArgs` for
`User.wines` in `frontend/src/lib/apollo.ts`, so each order is kept apart in the cache.
`frontend/src/lib/apollo.ts`), so it is never shown twice, and a reload gives the right order.

The list pages on «Min side» use `sort` (see [«Min side»](#min-side)). `keyArgs` for
`User.wines` in `frontend/src/lib/apollo.ts` is `['list', 'sort', 'minRating']`, so each order
of a list is kept apart in the cache.

### Tests

Expand Down Expand Up @@ -373,12 +375,13 @@ The code is in `frontend/src/features/my/`. Every page is behind `RequireAuth`.
| Address | What it shows |
|---|---|
| `/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, newest first, 24 at a time with «Last inn flere». An unknown list shows «Fant ikke listen» |
| `/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 |

| Part | What it does |
|---|---|
| `useMyProfile` | The `MyProfile` query. The lists in it are stored by name (`User.wines` with `keyArgs: ['list']`), so they are the same ones the list pages show, and a button on a card updates both. While a list is fetched again, the page keeps what it had (`previousData`) |
| `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`) |
| `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 |
| `topFavouritesDraft.ts` | The steps of the editor as pure functions, with at most four wines, the same limit as the API |
Expand Down
6 changes: 6 additions & 0 deletions docs/manual-testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,12 @@ Log in as `demo` (see section 8), which has favourites, a top 4, both other list
| Move a wine down, take one out, add another, «Lagre topp 4» | The new order in the frame, «Topp 4 er lagret.» is read, and focus is on «Endre topp 4». The same after a reload and in a private window |
| Four wines chosen: «Legg til» on a fifth | Nothing happens, and the button is described by «Topp 4 er full …» |
| Change something, then «Avbryt» | The top 4 as before |
| `/mine/vil-prove`: «Sorter etter» → «Navn A–Å», then reload | A to Z, `?sortering=navn` in the URL, and the same order after the reload |
| On a list page: change the order a few times, then the browser's back button | Back to «Min side», not to the previous order |
| On a list page: Tab to «Sorter etter», then the arrow keys (on a Mac they open the menu: choose with the arrow keys and Enter) | The order changes, focus stays on the select, and a screen reader reads «… viner, sortert etter …» when the list has loaded |
| After a change of order: «Last inn flere» | Focus moves to the first new wine. The screen reader reads nothing more |
| 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 |
| 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» |
Expand Down
51 changes: 51 additions & 0 deletions frontend/e2e/lists.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { expect, test, type Page } from '@playwright/test';
import { expectNoAxeViolations } from './support/axe';
import { fakeApi, loggedIn } from './support/fakeApi';
import { skipWhereArrowKeysOpenSelect } from './support/select';

/*
* E2E for the wine lists: the buttons on the wine cards and the wine page, the list pages,
Expand Down Expand Up @@ -112,6 +113,56 @@ test.describe('Listene', () => {
await expect(myList(page).getByRole('link')).toHaveText(['Rødvin 1', 'Rødvin 2']);
});

/** Three wines on «Vil prøve», added 1, 2, 3, and the list page opened from «Min side». */
async function openThreeWantToTry(page: Page) {
await fakeApi(page);
await page.goto('./sok');
await loggedIn(page);
for (const id of ['1', '2', '3']) {
const bookmark = page.getByRole('button', { name: `Vil prøve Rødvin ${id}` });
await bookmark.click();
await expect(bookmark).toHaveAttribute('aria-pressed', 'true');
}
await page.goto('./mine');
await page.getByRole('link', { name: /Se alle 3 viner du vil prøve/ }).click();
await expect(myList(page).getByRole('link')).toHaveText(['Rødvin 3', 'Rødvin 2', 'Rødvin 1']);
return page.getByRole('combobox', { name: 'Sorter etter' });
}

test('sorteringen står i URL-en, beholdes ved ny lasting, og tilbake forlater siden', async ({
page,
}) => {
const sort = await openThreeWantToTry(page);

await sort.selectOption({ label: 'Best vurdert' });
await expect(page).toHaveURL(/\/mine\/vil-prove\?sortering=best-vurdert$/);
await sort.selectOption({ label: 'Navn A–Å' });
await expect(page).toHaveURL(/\/mine\/vil-prove\?sortering=navn$/);
await expect(myList(page).getByRole('link')).toHaveText(['Rødvin 1', 'Rødvin 2', 'Rødvin 3']);
await expectNoAxeViolations(page);

await page.reload();
await expect(sort).toHaveValue('NAME');
await expect(myList(page).getByRole('link')).toHaveText(['Rødvin 1', 'Rødvin 2', 'Rødvin 3']);

// Each change replaced the address, so one step back is «Min side».
await page.goBack();
await expect(page).toHaveURL(/\/mine$/);
});

test('piltastene bytter sortering uten at et trykk går tapt', async ({ page, isMobile }) => {
skipWhereArrowKeysOpenSelect(isMobile);
const sort = await openThreeWantToTry(page);

// Three presses at once: each must start where the one before ended.
await sort.focus();
for (let step = 0; step < 3; step += 1) await page.keyboard.press('ArrowDown');

await expect(page).toHaveURL(/\/mine\/vil-prove\?sortering=navn$/);
await expect(myList(page).getByRole('link')).toHaveText(['Rødvin 1', 'Rødvin 2', 'Rødvin 3']);
await expect(sort).toBeFocused();
});

test('har ingen axe-brudd på en tom «Min side» og en tom liste', async ({ page }) => {
await fakeApi(page);
await page.goto('./mine');
Expand Down
48 changes: 48 additions & 0 deletions frontend/e2e/profile.spec.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import { expect, test, type Page } from '@playwright/test';
import { expectNoAxeViolations } from './support/axe';
import { fakeApi, loggedIn } from './support/fakeApi';
import { skipWhereArrowKeysOpenSelect } from './support/select';

/*
* E2E for «Min side», the whole way a user goes: log in, add favourites, choose the top 4 with
* the keyboard, see the profile, and log out. Runs against `vite preview` with the fake API in
* support/fakeApi.ts, which remembers the lists and the top 4 between page loads.
*/

const myReviews = (page: Page) => page.getByRole('list', { name: 'Mine dommer' }).getByRole('link');

const topPlaces = (page: Page) =>
page.getByRole('list', { name: 'Topp 4 favoritter' }).getByRole('link');

Expand Down Expand Up @@ -99,4 +102,49 @@ test.describe('Min side', () => {

await expect(topPlaces(page)).toHaveText(['Rødvin 3']);
});

/** «Mine dommer» with two reviews, opened after «Min side», so there is a page to go back to. */
async function openMyReviews(page: Page) {
await fakeApi(page);
await page.goto('./mine');
await page.goto('./mine/dommer');
await expect(myReviews(page)).toHaveText(['Rødvin 2', 'Rødvin 1']);
return page.getByRole('combobox', { name: 'Rekkefølge' });
}

test('rekkefølgen på «Mine dommer» står i URL-en, beholdes ved ny lasting, og tilbake forlater siden', async ({
page,
}) => {
const order = await openMyReviews(page);

await order.selectOption({ label: 'Eldste først' });
await expect(page).toHaveURL(/\/mine\/dommer\?sortering=eldste$/);
await expect(myReviews(page)).toHaveText(['Rødvin 1', 'Rødvin 2']);

await page.reload();
await expect(order).toHaveValue('OLDEST');
await expect(myReviews(page)).toHaveText(['Rødvin 1', 'Rødvin 2']);
await page.goBack();
await expect(page).toHaveURL(/\/mine$/);
});

test('piltastene bytter rekkefølgen på «Mine dommer» uten at et trykk går tapt', async ({
page,
isMobile,
}) => {
skipWhereArrowKeysOpenSelect(isMobile);
const order = await openMyReviews(page);

// Down and up again at once: the second press must start from «Eldste først».
await order.focus();
await page.keyboard.press('ArrowDown');
await page.keyboard.press('ArrowUp');
await expect(page).toHaveURL(/\/mine\/dommer$/);
await expect(order).toHaveValue('NEWEST');

await page.keyboard.press('ArrowDown');
await expect(page).toHaveURL(/\/mine\/dommer\?sortering=eldste$/);
await expect(myReviews(page)).toHaveText(['Rødvin 1', 'Rødvin 2']);
await expect(order).toBeFocused();
});
});
34 changes: 27 additions & 7 deletions frontend/e2e/support/fakeApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,13 +40,26 @@ const details = {
vintages: [],
};

const connection = (nodes: object[]) => ({
__typename: 'WineConnection',
const connection = (nodes: object[], type = 'Wine') => ({
__typename: `${type}Connection`,
totalCount: nodes.length,
edges: nodes.map((node, index) => ({ __typename: 'WineEdge', cursor: String(index), node })),
edges: nodes.map((node, index) => ({ __typename: `${type}Edge`, cursor: String(index), node })),
pageInfo: { __typename: 'PageInfo', hasNextPage: false, endCursor: null },
});

const myReview = (wineId: string, givenAt: string) => ({
__typename: 'Review',
id: `r${wineId}`,
rating: 4,
comment: null,
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 emptyReviews = {
__typename: 'ReviewConnection',
totalCount: 0,
Expand Down Expand Up @@ -115,7 +128,11 @@ export async function fakeApi(page: Page, { loggedIn = true } = {}) {
data: { setTopFavourites: { ...KARI, topFavourites: top.map(wine) } },
};
},
MyReviews: () => ({ data: { me: me && { ...me, reviews: emptyReviews } } }),
// Two fixed reviews for «Mine dommer», newest or oldest first.
MyReviews: ({ order }: { order: 'NEWEST' | 'OLDEST' }) => {
const reviews = order === 'OLDEST' ? [...MY_REVIEWS].reverse() : MY_REVIEWS;
return { data: { me: me && { ...me, reviews: connection(reviews, 'Review') } } };
},
SearchWines: () => ({ data: { wines: connection(ids.map(wine)) } }),
FilterOptions: () => ({ data: { filterOptions } }),
Wine: ({ id }: { id: string }) => ({ data: { wine: { ...wine(id), ...details } } }),
Expand Down Expand Up @@ -152,9 +169,12 @@ export async function fakeApi(page: Page, { loggedIn = true } = {}) {
data: { setWineInList: { __typename: 'Wine', id: wineId, myLists: listsOf(wineId) } },
};
},
MyWineList: ({ list }: { list: ListName }) => ({
data: { me: me && { ...me, wines: connection(newestOn(list).map(wine)) } },
}),
// Of the orders, only the name is faked: the newest first, unless `sort: NAME`.
MyWineList: ({ list, sort }: { list: ListName; sort?: string }) => {
const wines = newestOn(list).map(wine);
if (sort === 'NAME') wines.sort((a, b) => a.name.localeCompare(b.name, 'nb'));
return { data: { me: me && { ...me, wines: connection(wines) } } };
},
MyProfile: ({ preview }: { preview: number }) => {
const page = (list: ListName) => {
const all = newestOn(list);
Expand Down
15 changes: 15 additions & 0 deletions frontend/e2e/support/select.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { test } from '@playwright/test';

/**
* Skips the rest of a test that changes a native select with the arrow keys, where that does
* not work. Chrome on a Mac desktop opens the select's menu on an arrow key instead of changing
* the value. On Windows and Linux, and in the mobile emulation, the value changes at once.
* Call it at the start of the test. Choose the value with `selectOption` in tests that should
* run everywhere.
*/
export function skipWhereArrowKeysOpenSelect(isMobile: boolean) {
test.skip(
process.platform === 'darwin' && !isMobile,
'On macOS, the arrow keys open a native select instead of changing its value',
);
}
70 changes: 49 additions & 21 deletions frontend/src/features/lists/api/listCache.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ import type { WineListName } from '../../../lib/wineLists';
import { updateListPages } from './listCache';

const LIST = gql`
query List($list: WineList!) {
query List($list: WineList!, $sort: WineListSort) {
me {
id
wines(list: $list) {
wines(list: $list, sort: $sort) {
totalCount
edges {
cursor
Expand All @@ -34,26 +34,34 @@ const TOP = gql`

const wineRef = (id: string) => ({ __typename: 'Wine', id });

/** A list in the cache as the API sent it, in one order (none: the newest first). */
function writeList(
cache: ReturnType<typeof createApolloCache>,
list: string,
ids: string[],
sort?: string,
) {
cache.writeQuery({
query: LIST,
variables: { list, sort },
data: {
me: {
__typename: 'User',
id: '1',
wines: {
__typename: 'WineConnection',
totalCount: ids.length,
edges: ids.map((id) => ({ __typename: 'WineEdge', cursor: id, node: wineRef(id) })),
},
},
},
});
}

/** A cache with the user's lists as the API last sent them. */
function cacheWith(lists: Partial<Record<WineListName, string[]>>, top: string[] = []) {
const cache = createApolloCache();
for (const [list, ids] of Object.entries(lists)) {
cache.writeQuery({
query: LIST,
variables: { list },
data: {
me: {
__typename: 'User',
id: '1',
wines: {
__typename: 'WineConnection',
totalCount: ids.length,
edges: ids.map((id) => ({ __typename: 'WineEdge', cursor: id, node: wineRef(id) })),
},
},
},
});
}
for (const [list, ids] of Object.entries(lists)) writeList(cache, list, ids);
cache.writeQuery({
query: TOP,
data: { me: { __typename: 'User', id: '1', topFavourites: top.map(wineRef) } },
Expand All @@ -64,8 +72,8 @@ function cacheWith(lists: Partial<Record<WineListName, string[]>>, top: string[]
type ListData = { me: { wines: { totalCount: number; edges: { node: { id: string } }[] } } };

/** The ids on a cached list and its count, or null when the list is no longer in the cache. */
function read(cache: ReturnType<typeof createApolloCache>, list: WineListName) {
const data = cache.readQuery<ListData>({ query: LIST, variables: { list } });
function read(cache: ReturnType<typeof createApolloCache>, list: WineListName, sort?: string) {
const data = cache.readQuery<ListData>({ query: LIST, variables: { list, sort } });
if (!data) return null;
return {
ids: data.me.wines.edges.map((edge) => edge.node.id),
Expand Down Expand Up @@ -102,6 +110,26 @@ describe('updateListPages', () => {
expect(read(cache, 'FAVOURITE')).toEqual({ ids: ['8'], totalCount: 1 });
});

it('changes every order of a list, as each is stored apart', () => {
const cache = cacheWith({ WANT_TO_TRY: ['7', '8'], FAVOURITE: ['8'] });
writeList(cache, 'WANT_TO_TRY', ['8', '7'], 'NAME');
writeList(cache, 'FAVOURITE', ['8'], 'COMMUNITY_RATING');

// Taken off «Vil prøve»: gone from both orders. Added to the favourites: where it belongs in
// an order is up to the API, so every order of the list is fetched again.
updateListPages(cache, {
userId: '1',
wineId: '7',
before: ['WANT_TO_TRY'],
after: ['FAVOURITE'],
});

expect(read(cache, 'WANT_TO_TRY')).toEqual({ ids: ['8'], totalCount: 1 });
expect(read(cache, 'WANT_TO_TRY', 'NAME')).toEqual({ ids: ['8'], totalCount: 1 });
expect(read(cache, 'FAVOURITE')).toBeNull();
expect(read(cache, 'FAVOURITE', 'COMMUNITY_RATING')).toBeNull();
});

it('takes a wine out of the top 4 when it is no longer a favourite, and keeps the order', () => {
const cache = cacheWith({ FAVOURITE: ['7', '8', '9'] }, ['9', '7', '8']);

Expand Down
12 changes: 9 additions & 3 deletions frontend/src/features/lists/api/listCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ import type { ApolloCache, Reference } from '@apollo/client';
import type { WineConnection } from '../../../lib/apollo';
import type { WineListName } from '../../../lib/wineLists';

/** The list a cached `wines` field belongs to, from its key in the cache: wines:{"list":"TRIED"}. */
/**
* The list a cached `wines` field belongs to, from its key in the cache: wines:{"list":"TRIED"},
* or wines:{"list":"TRIED","sort":"NAME"} for another order of the same list.
*/
function listOf(storeFieldName: string): string | null {
return /"list":"([A-Z_]+)"/.exec(storeFieldName)?.[1] ?? null;
}
Expand All @@ -11,10 +14,13 @@ function listOf(storeFieldName: string): string | null {
* Keeps the user's list pages in the cache in step with a change of one wine's lists, so a page
* that shows them (such as «Min side» and the list pages) changes at once without a new request.
*
* Each order of a list is stored apart, and every order is changed:
*
* - A list the wine left: the wine is taken out, and the count goes down by one. Also from the
* top 4 when it is no longer a favourite.
* - A list the wine joined: the new wine belongs at the top, with a cursor only the API can make.
* The cached list is removed instead, so it is fetched again the next time it is shown.
* - A list the wine joined: where the new wine belongs depends on the order, and needs a cursor
* only the API can make. The cached list is removed instead, so it is fetched again the next
* time it is shown.
*
* Runs in the mutation's `update`, also for the optimistic answer, so a failed change is undone
* here too.
Expand Down
Loading