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
9 changes: 6 additions & 3 deletions frontend/e2e/search.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ async function stubApi(page: Page) {

const searchbox = (page: Page) => page.getByRole('searchbox', { name: 'Søk etter vin' });
const results = (page: Page) => page.getByRole('list', { name: 'Søkeresultater' });
// Scoped to <main>: the layout has its own live region for the connection banner.
const searchStatus = (page: Page) => page.getByRole('main').getByRole('status');

test.describe('Søkesiden', () => {
test('søk, last inn flere, last siden på nytt og gå tilbake', async ({ page }) => {
Expand All @@ -74,7 +76,7 @@ test.describe('Søkesiden', () => {

await searchbox(page).pressSequentially('pinot', { delay: 30 });
await expect(page).toHaveURL(/\/sok\?q=pinot$/);
await expect(page.getByRole('status')).toHaveText('Viser 24 av 30 viner for «pinot»');
await expect(searchStatus(page)).toHaveText('Viser 24 av 30 viner for «pinot»');

await page.getByRole('button', { name: 'Last inn flere' }).click();
await expect(results(page).getByRole('article')).toHaveCount(30);
Expand All @@ -83,7 +85,7 @@ test.describe('Søkesiden', () => {

await page.reload();
await expect(searchbox(page)).toHaveValue('pinot');
await expect(page.getByRole('status')).toHaveText('Viser 24 av 30 viner for «pinot»');
await expect(searchStatus(page)).toHaveText('Viser 24 av 30 viner for «pinot»');

await page.getByRole('link', { name: 'Pinot 1', exact: true }).click();
await expect(page).toHaveURL(/\/vin\/1$/);
Expand All @@ -98,7 +100,7 @@ test.describe('Søkesiden', () => {

await searchbox(page).pressSequentially('riesling', { delay: 30 });
await expect(page).toHaveURL(/\/sok\?q=riesling$/);
await expect(page.getByRole('status')).toContainText('riesling');
await expect(searchStatus(page)).toContainText('riesling');

expect(searches.map((variables) => variables.search)).toEqual([undefined, 'riesling']);
});
Expand All @@ -122,6 +124,7 @@ test.describe('Søkesiden', () => {
});
await page.goto('./sok');
await expect(page.getByRole('alert')).toContainText('Vi fikk ikke søkt');
await expect(page.getByRole('alert')).toContainText('Feilen er hos oss, ikke hos deg.');

down = false;
await page.getByRole('button', { name: 'Prøv igjen' }).click();
Expand Down
8 changes: 8 additions & 0 deletions frontend/src/app/App.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,14 @@ describe('AppRoutes', () => {
expect(await findHeading(heading)).toBeInTheDocument();
});

it('gives the 404 page a way back to the front page and the search', async () => {
renderRoute('/finnes-ikke');
expect(await findHeading('Fant ikke siden')).toBeInTheDocument();
expect(document.title).toBe('Fant ikke siden – Kork & Krone');
expect(screen.getByRole('link', { name: 'Til forsiden' })).toHaveAttribute('href', '/');
expect(screen.getByRole('link', { name: 'Utforsk viner' })).toHaveAttribute('href', '/sok');
});

it('loads the search page lazily', async () => {
renderRoute('/sok');
expect(await findHeading('Utforsk viner')).toBeInTheDocument();
Expand Down
9 changes: 2 additions & 7 deletions frontend/src/app/App.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { lazy } from 'react';
import { BrowserRouter, Route, Routes } from 'react-router';
import { AppLayout } from '../components/layout/AppLayout';
import PlaceholderPage from './PlaceholderPage';
import NotFoundPage from './NotFoundPage';

// Kodesplitting per rute: forsiden laster ikke koden for søk og detaljside.
const LandingPage = lazy(() => import('../features/landing/LandingPage'));
Expand All @@ -22,12 +22,7 @@ export function AppRoutes() {
<Route path="vin/:id" element={<WinePage />} />
<Route path="mine" element={<MyPage />} />
<Route path="konto" element={<AccountPage />} />
<Route
path="*"
element={
<PlaceholderPage title="Fant ikke siden" text="Lenken kan være feil eller utdatert." />
}
/>
<Route path="*" element={<NotFoundPage />} />
</Route>
</Routes>
);
Expand Down
26 changes: 26 additions & 0 deletions frontend/src/app/NotFoundPage.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { Link } from 'react-router';
import { EmptyState } from '../components/ui/EmptyState';
import { useDocumentTitle } from '../hooks/useDocumentTitle';
import { buildSearchUrl } from '../lib/searchParams';

/** The page for addresses that do not exist. The header search is shown here as well. */
export default function NotFoundPage() {
useDocumentTitle('Fant ikke siden');
return (
<div className="container" style={{ paddingBlock: 'var(--space-7)' }}>
<EmptyState
icon="signpost"
title="Fant ikke siden"
titleAs="h1"
actions={
<>
<Link to="/">Til forsiden</Link>
<Link to={buildSearchUrl()}>Utforsk viner</Link>
</>
}
>
<p>Lenken kan være feil eller utdatert. Prøv søket øverst, eller gå videre herfra.</p>
</EmptyState>
</div>
);
}
14 changes: 0 additions & 14 deletions frontend/src/app/PlaceholderPage.tsx

This file was deleted.

24 changes: 23 additions & 1 deletion frontend/src/components/layout/AppLayout.test.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { describe, expect, it } from 'vitest';
import { describe, expect, it, vi } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter, Route, Routes } from 'react-router';
Expand All @@ -11,6 +11,10 @@ import { ME_QUERY } from '../../features/auth/api/authQueries';
/** The header shows who is logged in, so the layout needs Apollo and AuthProvider. */
const notLoggedIn = { request: { query: ME_QUERY }, result: { data: { me: null } } };

function Broken(): never {
throw new TypeError('Failed to fetch dynamically imported module: /project2/assets/Feil.js');
}

function renderApp(route = '/') {
return render(
<MockedProvider mocks={[notLoggedIn]}>
Expand All @@ -21,6 +25,7 @@ function renderApp(route = '/') {
<Route index element={<h1>Forside</h1>} />
<Route path="sok" element={<h1>Søk</h1>} />
<Route path="mine" element={<h1>Mine</h1>} />
<Route path="feil" element={<Broken />} />
</Route>
</Routes>
</AuthProvider>
Expand Down Expand Up @@ -75,4 +80,21 @@ describe('AppLayout', () => {
await user.click(screen.getByRole('link', { name: 'Utforsk' }));
expect(screen.getByRole('heading', { level: 1, name: 'Søk' })).toHaveFocus();
});

it('viser en feilside i stedet for en blank side når en side ikke lastes', async () => {
// React logs the caught error. That is expected here, so it is kept out of the test output.
vi.spyOn(console, 'error').mockImplementation(() => undefined);
const user = userEvent.setup();
renderApp('/feil');

expect(
screen.getByRole('heading', { level: 1, name: 'Siden kunne ikke vises' }),
).toBeInTheDocument();
expect(screen.getByRole('alert')).toHaveTextContent('Vi fikk ikke kontakt med serveren');
expect(screen.getByRole('banner')).toBeInTheDocument();

await user.click(screen.getByRole('link', { name: 'Utforsk' }));
expect(screen.getByRole('heading', { level: 1, name: 'Søk' })).toBeInTheDocument();
vi.restoreAllMocks();
});
});
23 changes: 14 additions & 9 deletions frontend/src/components/layout/AppLayout.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { Suspense, useEffect, useRef } from 'react';
import { Outlet, useLocation } from 'react-router';
import { ConnectionBanner } from './ConnectionBanner';
import { Footer } from './Footer';
import { Header } from './Header';
import { focusHeadingWhenReady } from '../../lib/focus';
import { RouteErrorBoundary } from './RouteErrorBoundary';
import styles from './AppLayout.module.css';

/**
Expand Down Expand Up @@ -32,16 +34,19 @@ export function AppLayout() {
Hopp til hovedinnhold
</a>
<Header showSearch={pathname !== '/' && pathname !== '/sok'} />
<ConnectionBanner />
<main id="main" ref={mainRef} tabIndex={-1} className={styles.main}>
<Suspense
fallback={
<p className={`container ${styles.loading}`} role="status">
Laster …
</p>
}
>
<Outlet />
</Suspense>
<RouteErrorBoundary resetKey={pathname}>
<Suspense
fallback={
<p className={`container ${styles.loading}`} role="status">
Laster …
</p>
}
>
<Outlet />
</Suspense>
</RouteErrorBoundary>
</main>
<Footer />
</>
Expand Down
15 changes: 15 additions & 0 deletions frontend/src/components/layout/ConnectionBanner.module.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
.banner {
padding-block: var(--space-3);
font-size: var(--text-sm);
font-weight: 700;
}

.offline {
background: var(--color-text);
color: var(--color-bg);
}

.online {
background: var(--color-surface-muted);
color: var(--color-text);
}
98 changes: 98 additions & 0 deletions frontend/src/components/layout/ConnectionBanner.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import type { ReactNode } from 'react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { act, render, screen, waitFor } from '@testing-library/react';
import { gql } from '@apollo/client';
import { useQuery } from '@apollo/client/react';
import type { MockLink } from '@apollo/client/testing';
import { MockedProvider } from '@apollo/client/testing/react';
import { BACK_ONLINE_MS, ConnectionBanner } from './ConnectionBanner';

const GREETING_QUERY = gql`
query Greeting($who: String!) {
greeting(who: $who)
}
`;

function Greeting({ who }: { who: string }) {
const { data, error } = useQuery<{ greeting: string }>(GREETING_QUERY, { variables: { who } });
if (error) return <p>Feil for {who}</p>;
return <p>{data?.greeting ?? 'Laster'}</p>;
}

function greeting(who: string, answer: string | Error): MockLink.MockedResponse {
return {
request: { query: GREETING_QUERY, variables: { who } },
...(answer instanceof Error ? { error: answer } : { result: { data: { greeting: answer } } }),
};
}

function setOnline(online: boolean) {
vi.spyOn(navigator, 'onLine', 'get').mockReturnValue(online);
act(() => {
window.dispatchEvent(new Event(online ? 'online' : 'offline'));
});
}

function renderBanner(mocks: MockLink.MockedResponse[] = [], children?: ReactNode) {
return render(
// MockedProvider renders a single child only.
<MockedProvider mocks={mocks}>
<>
<ConnectionBanner />
{children}
</>
</MockedProvider>,
);
}

afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
});

describe('ConnectionBanner', () => {
it('shows nothing while the connection is fine, but keeps the live region', () => {
renderBanner();
expect(screen.getByRole('status')).toBeEmptyDOMElement();
});

it('says when the connection is lost and when it comes back', () => {
vi.useFakeTimers();
renderBanner();

setOnline(false);
expect(screen.getByRole('status')).toHaveTextContent('Du er frakoblet.');

setOnline(true);
expect(screen.getByRole('status')).toHaveTextContent('Du er på nett igjen.');

act(() => {
vi.advanceTimersByTime(BACK_ONLINE_MS);
});
expect(screen.getByRole('status')).toBeEmptyDOMElement();
});

it('sends failed requests again when the connection comes back, and only those', async () => {
// Each mock answers once, so a second request for «ok» would fail and show «Feil for ok».
renderBanner(
[
greeting('failed', new TypeError('Failed to fetch')),
greeting('failed', 'Hei igjen'),
greeting('ok', 'Hei'),
],
<>
<Greeting who="failed" />
<Greeting who="ok" />
</>,
);
expect(await screen.findByText('Feil for failed')).toBeInTheDocument();
expect(await screen.findByText('Hei')).toBeInTheDocument();

setOnline(false);
setOnline(true);

expect(await screen.findByText('Hei igjen')).toBeInTheDocument();
await waitFor(() => expect(screen.getByText('Hei')).toBeInTheDocument());
expect(screen.queryByText('Feil for ok')).not.toBeInTheDocument();
});
});
56 changes: 56 additions & 0 deletions frontend/src/components/layout/ConnectionBanner.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { useEffect, useState } from 'react';
import { useApolloClient } from '@apollo/client/react';
import { useOnlineStatus } from '../../hooks/useOnlineStatus';
import styles from './ConnectionBanner.module.css';

/** How long «Du er på nett igjen» stays before the banner goes away. */
export const BACK_ONLINE_MS = 4000;

/**
* Tells the user when the connection is lost, and when it comes back. On the way back,
* every request that failed on the page is sent again, so the user does not have to find
* each «Prøv igjen» button. Requests that worked are left alone.
*/
export function ConnectionBanner() {
const online = useOnlineStatus();
const client = useApolloClient();
const [previous, setPrevious] = useState(online);
const [backOnline, setBackOnline] = useState(false);

// Updated during render instead of in an effect, so the text changes in the same paint.
if (online !== previous) {
setPrevious(online);
setBackOnline(online);
}

useEffect(() => {
if (!backOnline) return;

void client
.refetchQueries({
include: 'active',
onQueryUpdated: (query) => Boolean(query.getCurrentResult().error),
})
// A request that fails again shows its own error where it belongs.
.catch(() => undefined);

const timer = setTimeout(() => setBackOnline(false), BACK_ONLINE_MS);
return () => clearTimeout(timer);
}, [backOnline, client]);

const text = !online
? 'Du er frakoblet. Vi henter det som mangler når nettet er tilbake.'
: backOnline
? 'Du er på nett igjen.'
: '';

// The live region is always in the DOM, so screen readers announce every change (WCAG 4.1.3).
return (
<div
role="status"
className={text ? `${styles.banner} ${online ? styles.online : styles.offline}` : undefined}
>
{text && <p className="container">{text}</p>}
</div>
);
}
Loading