Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
5 changes: 5 additions & 0 deletions docs/manual-testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,11 @@ 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 | The order changes with each key, focus stays on the select, and a screen reader reads «… viner, sortert etter …» when the list has loaded |
| 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
34 changes: 34 additions & 0 deletions frontend/e2e/lists.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,40 @@ test.describe('Listene', () => {
await expect(myList(page).getByRole('link')).toHaveText(['Rødvin 1', 'Rødvin 2']);
});

test('listen sorteres med tastaturet, beholder sorteringen ved ny lasting, og tilbake forlater siden', async ({
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']);

// A native select: the arrow keys change the order without opening it.
const sort = page.getByRole('combobox', { name: 'Sorter etter' });
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();
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('har ingen axe-brudd på en tom «Min side» og en tom liste', async ({ page }) => {
await fakeApi(page);
await page.goto('./mine');
Expand Down
29 changes: 29 additions & 0 deletions frontend/e2e/profile.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,4 +99,33 @@ test.describe('Min side', () => {

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

test('«Mine dommer» byttes med piltastene uten at et trykk går tapt, og står i URL-en', async ({
page,
}) => {
await fakeApi(page);
await page.goto('./mine');
await page.goto('./mine/dommer');
const reviews = page.getByRole('list', { name: 'Mine dommer' }).getByRole('link');
await expect(reviews).toHaveText(['Rødvin 2', 'Rødvin 1']);

// Down and up again at once: the second press must start from «Eldste først».
const order = page.getByRole('combobox', { name: 'Rekkefølge' });
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(reviews).toHaveText(['Rødvin 1', 'Rødvin 2']);
await expect(order).toBeFocused();

await page.reload();
await expect(order).toHaveValue('OLDEST');
await expect(reviews).toHaveText(['Rødvin 1', 'Rødvin 2']);
await page.goBack();
await expect(page).toHaveURL(/\/mine$/);
});
});
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
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
12 changes: 8 additions & 4 deletions frontend/src/features/lists/api/myWineListQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,19 @@ import { gql } from '@apollo/client';
import type { ApiWine } from '../../../lib/mapWine';
import { WINE_CARD_FIELDS } from './wineCardFields';

/** The same values as the GraphQL enum WineListSort. See docs/api.md. */
export type WineListSort = 'NEWEST' | 'OWN_RATING' | 'COMMUNITY_RATING' | 'NAME';

/**
* One page of one of the logged-in user's lists, newest first. The wine fields are the same as
* on the wine cards, with `myLists`, so the buttons on the cards know their state.
* One page of one of the logged-in user's lists, newest first unless `sort` says otherwise. The
* wine fields are the same as on the wine cards, with `myLists`, so the buttons on the cards
* know their state.
*/
export const MY_WINE_LIST_QUERY = gql`
query MyWineList($list: WineList!, $first: Int, $after: String) {
query MyWineList($list: WineList!, $sort: WineListSort, $first: Int, $after: String) {
me {
id
wines(list: $list, first: $first, after: $after) {
wines(list: $list, sort: $sort, first: $first, after: $after) {
totalCount
edges {
cursor
Expand Down
17 changes: 13 additions & 4 deletions frontend/src/features/lists/api/useMyWineList.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { useQuery } from '@apollo/client/react';
import { toWineSummary } from '../../../lib/mapWine';
import type { WineSummary } from '../../../lib/types';
import type { WineListName } from '../../../lib/wineLists';
import { MY_WINE_LIST_QUERY, type MyWineListData } from './myWineListQuery';
import { MY_WINE_LIST_QUERY, type MyWineListData, type WineListSort } from './myWineListQuery';

/** How many wines one page of a list has: the same as a page of search results. */
export const LIST_PAGE_SIZE = 24;
Expand All @@ -24,15 +24,24 @@ export interface MyWineListResult {
}

/**
* The logged-in user's wines on one list, newest first, one page at a time. The pages are kept
* The variables for the first page of a list. NEWEST is the API's default and is left out, so
* the newest first is stored in the same place in the cache as the lists on «Min side», which
* ask without a sort. Each other order has its own place (keyArgs for User.wines in lib/apollo.ts).
*/
function listVariables(list: WineListName, sort: WineListSort) {
return { list, ...(sort !== 'NEWEST' && { sort }), first: LIST_PAGE_SIZE };
}

/**
* The logged-in user's wines on one list in one order, one page at a time. The pages are kept
* together in the cache (User.wines in lib/apollo.ts), and a change made with the list buttons
* updates them at once (updateListPages).
*/
export function useMyWineList(list: WineListName): MyWineListResult {
export function useMyWineList(list: WineListName, sort: WineListSort = 'NEWEST'): MyWineListResult {
const { data, error, networkStatus, fetchMore, refetch } = useQuery<MyWineListData>(
MY_WINE_LIST_QUERY,
{
variables: { list, first: LIST_PAGE_SIZE },
variables: listVariables(list, sort),
// «Min side» keeps the first four wines of each list in the same place in the cache. Show
// those at once, but always ask for a whole page too, so a list of six shows all six.
fetchPolicy: 'cache-and-network',
Expand Down
Loading