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
8 changes: 2 additions & 6 deletions frontend/src/app/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import PlaceholderPage from './PlaceholderPage';
const LandingPage = lazy(() => import('../features/landing/LandingPage'));
const SearchPage = lazy(() => import('../features/search/SearchPage'));
const WinePage = lazy(() => import('../features/wine/WinePage'));
const MyPage = lazy(() => import('../features/my/MyPage'));

/** BASE_URL kommer fra `base` i vite.config.ts (f.eks. «/project2/»). */
const basename = import.meta.env.BASE_URL.replace(/\/$/, '') || '/';
Expand All @@ -18,12 +19,7 @@ export function AppRoutes() {
<Route index element={<LandingPage />} />
<Route path="sok" element={<SearchPage />} />
<Route path="vin/:id" element={<WinePage />} />
<Route
path="mine"
element={
<PlaceholderPage title="Mine anmeldelser" text="Her kommer dommene og listene dine." />
}
/>
<Route path="mine" element={<MyPage />} />
<Route
path="*"
element={
Expand Down
115 changes: 115 additions & 0 deletions frontend/src/features/my/MyPage.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import { afterEach, describe, expect, it } from 'vitest';
import { render, screen, 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 } from 'react-router';
import { axe } from 'vitest-axe';
import { createApolloCache } from '../../lib/apollo';
import MyPage from './MyPage';
import { wishlistQuery, wishlistVariables } from './api/wishlistQuery';

const WISHLIST_KEY = 'kk:wishlist';

const apiWine = (id: string, name: string, type = 'Red') => ({
__typename: 'Wine',
id,
name,
type,
grapes: ['Merlot'],
country: 'Italy',
countryCode: 'IT',
wineryName: 'Produsent',
communityRating: 4.2,
communityRatingCount: 12,
});

/** One answer for the wines on the list, in the order the page asks for them. */
function wines(saved: { id: string; name: string }[]): MockLink.MockedResponse {
const ids = saved.map((wine) => wine.id);
return {
request: { query: wishlistQuery(ids), variables: wishlistVariables(ids) },
result: {
data: Object.fromEntries(
saved.map((wine, index) => [`wine${index}`, apiWine(wine.id, wine.name)]),
),
},
};
}

/** The hearts are stored newest last, and the page shows them newest first. */
function save(ids: string[]) {
window.localStorage.setItem(WISHLIST_KEY, JSON.stringify(ids));
}

function renderPage(mocks: MockLink.MockedResponse[]) {
const user = userEvent.setup();
const result = render(
<MockedProvider mocks={mocks} cache={createApolloCache()}>
<MemoryRouter>
<MyPage />
</MemoryRouter>
</MockedProvider>,
);
return { user, ...result };
}

afterEach(() => window.localStorage.clear());

describe('MyPage', () => {
it('explains the empty list and links to the search', () => {
renderPage([]);
expect(screen.getByText(/Du har ikke lagret noen viner ennå/)).toBeInTheDocument();
expect(screen.getByRole('link', { name: 'Utforsk viner' })).toHaveAttribute('href', '/sok');
expect(document.title).toBe('Mine anmeldelser – Kork & Krone');
});

it('shows the saved wines, newest first', async () => {
save(['100062', '111427']);
renderPage([
wines([
{ id: '111427', name: 'Chianti' },
{ id: '100062', name: 'Origem Merlot' },
]),
]);

const list = await screen.findByRole('list', { name: 'Viner du vil prøve' });
const names = within(list)
.getAllByRole('link')
.map((link) => link.textContent);
expect(names).toEqual(['Chianti', 'Origem Merlot']);
expect(screen.getByText('2 viner')).toBeInTheDocument();
});

it('removes a wine from the list when the heart is clicked again', async () => {
save(['100062']);
const { user } = renderPage([wines([{ id: '100062', name: 'Origem Merlot' }])]);

await user.click(await screen.findByRole('button', { name: 'Vil prøve Origem Merlot' }));

expect(screen.getByText(/Du har ikke lagret noen viner ennå/)).toBeInTheDocument();
});

it('offers a new attempt when the wines cannot be fetched', async () => {
save(['100062']);
renderPage([
{
request: {
query: wishlistQuery(['100062']),
variables: wishlistVariables(['100062']),
},
error: new Error('Nede'),
},
]);

expect(await screen.findByRole('alert')).toHaveTextContent('Vi fikk ikke hentet vinene');
expect(screen.getByRole('button', { name: 'Prøv igjen' })).toBeInTheDocument();
});

it('has no axe violations', async () => {
save(['100062']);
const { container } = renderPage([wines([{ id: '100062', name: 'Origem Merlot' }])]);
await screen.findByRole('list', { name: 'Viner du vil prøve' });
expect(await axe(container)).toHaveNoViolations();
});
});
10 changes: 10 additions & 0 deletions frontend/src/features/my/MyPage.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { useDocumentTitle } from '../../hooks/useDocumentTitle';
import { useWishlistWines } from './api/useWishlistWines';
import { MyView } from './MyView';

/** Route component for `/mine`. Connects the data source to the presentation. */
export default function MyPage() {
useDocumentTitle('Mine anmeldelser');
const result = useWishlistWines();
return <MyView {...result} />;
}
15 changes: 15 additions & 0 deletions frontend/src/features/my/MyView.module.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
.page {
display: grid;
gap: var(--space-6);
padding-block: var(--space-7);
}

.count {
margin-bottom: var(--space-3);
color: var(--color-text-muted);
}

.empty {
margin-top: var(--space-2);
color: var(--color-text-muted);
}
51 changes: 51 additions & 0 deletions frontend/src/features/my/MyView.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { Link } from 'react-router';
import { ErrorNotice } from '../../components/ui/ErrorNotice';
import { Skeleton } from '../../components/ui/Skeleton';
import { WineList } from '../../components/ui/WineList';
import { pluralize } from '../../lib/format';
import { buildSearchUrl } from '../../lib/searchParams';
import type { WishlistResult } from './api/useWishlistWines';
import styles from './MyView.module.css';

/** Presentation of «Mine anmeldelser». The list lives in the browser until we have login. */
export function MyView({ wines, savedCount, loading, error, refetch }: WishlistResult) {
return (
<div className={`container ${styles.page}`}>
<h1>Mine anmeldelser</h1>

<section aria-labelledby="wishlist-title">
<h2 id="wishlist-title">Vil prøve</h2>

<p role="status" className="sr-only">
{loading ? 'Laster viner …' : ''}
</p>

{savedCount === 0 ? (
<p className={styles.empty}>
Du har ikke lagret noen viner ennå. Trykk på hjertet på en vin for å legge den her.{' '}
<Link to={buildSearchUrl()}>Utforsk viner</Link>
</p>
) : (
<>
<p className={styles.count}>{pluralize(savedCount, 'vin', 'viner')}</p>

{loading && wines.length === 0 && <Skeleton rows={3} />}

{error && (
<ErrorNotice message="Vi fikk ikke hentet vinene akkurat nå." onRetry={refetch} />
)}

{wines.length > 0 && <WineList wines={wines} label="Viner du vil prøve" />}
</>
)}
</section>

<section aria-labelledby="reviews-title">
<h2 id="reviews-title">Mine dommer</h2>
<p className={styles.empty}>
Dommene dine vises her når innlogging er på plass. Fram til da finner du dem på vinsiden.
</p>
</section>
</div>
);
}
44 changes: 44 additions & 0 deletions frontend/src/features/my/api/useWishlistWines.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { useMemo } from 'react';
import { useQuery } from '@apollo/client/react';
import { useWishlistIds } from '../../../hooks/useWishlist';
import { toWineSummary } from '../../../lib/mapWine';
import type { WineSummary } from '../../../lib/types';
import { wishlistQuery, wishlistVariables, type WishlistData } from './wishlistQuery';

export interface WishlistResult {
wines: WineSummary[];
/** How many wines are on the list, also before they are loaded. */
savedCount: number;
loading: boolean;
error: Error | undefined;
refetch: () => void;
}

/** The wines on the «Vil prøve» list, fetched in one request. */
export function useWishlistWines(): WishlistResult {
const ids = useWishlistIds();
// useWishlistIds gives a new array every render, so the query is rebuilt from the ids as text.
const key = ids.join(',');

// A new query object on every render would make Apollo fetch again in a loop.
const query = useMemo(() => wishlistQuery(key ? key.split(',') : []), [key]);

const { data, loading, error, refetch } = useQuery<WishlistData>(query, {
variables: wishlistVariables(ids),
skip: ids.length === 0,
});

const wines = ids
.map((_, index) => data?.[`wine${index}`])
.filter((wine) => wine != null)
.map(toWineSummary)
.filter((wine): wine is WineSummary => wine !== null);

return {
wines,
savedCount: ids.length,
loading,
error,
refetch: () => void refetch().catch(() => undefined),
};
}
25 changes: 25 additions & 0 deletions frontend/src/features/my/api/wishlistQuery.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { describe, expect, it } from 'vitest';
import { print } from 'graphql';
import { wishlistQuery, wishlistVariables } from './wishlistQuery';

describe('wishlistQuery', () => {
it('asks for one field per wine, with its own variable', () => {
const query = print(wishlistQuery(['1', '2']));
expect(query).toContain('query Wishlist($id0: ID!, $id1: ID!)');
expect(query).toContain('wine0: wine(id: $id0)');
expect(query).toContain('wine1: wine(id: $id1)');
});

it('is still valid GraphQL with an empty list', () => {
expect(print(wishlistQuery([]))).toContain('query Wishlist');
});
});

describe('wishlistVariables', () => {
it('numbers the ids in the same order', () => {
expect(wishlistVariables(['100062', '111427'])).toEqual({
id0: '100062',
id1: '111427',
});
});
});
53 changes: 53 additions & 0 deletions frontend/src/features/my/api/wishlistQuery.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { gql } from '@apollo/client';
import type { ApiWine } from '../../../lib/mapWine';

export interface WishlistData {
/** One wine per id, in the same order. A wine that no longer exists is null. */
[key: `wine${number}`]: ApiWine | null;
}

/**
* The API has no "wines by id" query, so we ask for each wine as its own field in
* one request: wine0, wine1 and so on. One round trip, and the Apollo cache reuses
* wines the user has already seen.
*/
export function wishlistQuery(ids: string[]) {
// With an empty list the page asks for nothing, but the query still has to be valid GraphQL.
if (ids.length === 0) {
return gql`
query Wishlist {
__typename
}
`;
}

const fields = ids
.map(
(_, index) => `
wine${index}: wine(id: $id${index}) {
id
name
type
grapes
country
countryCode
wineryName
communityRating
communityRatingCount
}`,
)
.join('');

const variables = ids.map((_, index) => `$id${index}: ID!`).join(', ');

return gql`
query Wishlist(${variables}) {
${fields}
}
`;
}

/** { id0: "123", id1: "456", ... } as the query expects them. */
export function wishlistVariables(ids: string[]): Record<string, string> {
return Object.fromEntries(ids.map((id, index) => [`id${index}`, id]));
}
6 changes: 6 additions & 0 deletions frontend/src/hooks/useWishlist.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,9 @@ export function useWishlist(wineId: string) {

return { isSaved, toggle };
}

/** The whole «Vil prøve» list, newest first. Updates when a heart is clicked. */
export function useWishlistIds(): string[] {
const ids = useSyncExternalStore(subscribe, getSnapshot, () => '');
return ids ? ids.split(',').reverse() : [];
}