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
92 changes: 92 additions & 0 deletions frontend/e2e/filters.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,3 +173,95 @@ test.describe('Filterdialogen på mobil', () => {
}
});
});

test.describe('Lange filterlister på stor skjerm', () => {
const codes =
'AR AT AU BG BR CA CH CL CN CZ DE ES FR GB GR HU IL IT JP LB MX NZ PT RO SI SK TR US UY ZA';

test.beforeEach(async ({ page, isMobile }) => {
test.skip(isMobile, 'Sidepanelet finnes bare på store skjermer.');
await stubGraphQL(page, {
FilterOptions: () => ({
data: {
filterOptions: {
...filterResponse.data.filterOptions,
countries: codes.split(' ').map((code, index) => option(code, 60 - index)),
},
},
}),
SearchWines: () => {
const wines = Array.from({ length: 24 }, (_, index) => wine(index + 1, 'Red'));
return {
data: {
wines: {
__typename: 'WineConnection',
totalCount: wines.length,
edges: wines.map((node) => ({ __typename: 'WineEdge', cursor: node.id, node })),
pageInfo: { __typename: 'PageInfo', hasNextPage: false, endCursor: null },
},
},
};
},
});
await page.goto('./sok');
await expect(results(page).getByRole('article')).toHaveCount(24);
});

test('en utvidet liste scroller selv, og knappen er synlig og har fokus når den lukkes', async ({
page,
}) => {
const countries = page.getByRole('group', { name: 'Land' });
const pageHeight = () => page.evaluate(() => document.documentElement.scrollHeight);
const before = await pageHeight();

await countries.getByRole('button', { name: 'Vis alle i Land (30)' }).click();

const list = countries.getByRole('list');
const sizes = await list.evaluate((element) => ({
scroll: element.scrollHeight,
client: element.clientHeight,
}));
expect(sizes.scroll).toBeGreaterThan(sizes.client);
expect(await pageHeight()).toBeLessThan(before + 400);

// As in the issue: scroll to the bottom of the list, then close it.
await list.evaluate((element) => element.scrollTo(0, element.scrollHeight));
await countries.getByRole('button', { name: 'Vis færre i Land' }).click();

const toggle = countries.getByRole('button', { name: 'Vis alle i Land (30)' });
await expect(toggle).toBeFocused();
await expect(toggle).toBeInViewport();
});

test('søk i en utvidet liste finner riktig land', async ({ page }) => {
const countries = page.getByRole('group', { name: 'Land' });
await countries.getByRole('button', { name: 'Vis alle i Land (30)' }).click();

await countries.getByRole('searchbox', { name: 'Søk i Land' }).fill('spa');

await expect(countries.getByRole('checkbox')).toHaveCount(1);
await countries.getByRole('checkbox', { name: /Spania/ }).check();
await expect(page).toHaveURL(/land=ES/);
});

test('filtrene blir stående synlige når brukeren scroller i resultatene', async ({ page }) => {
// Halfway through the results. At the very bottom the footer pushes the panel up, as it should.
await page.evaluate(() => window.scrollTo(0, 1200));
expect(await page.evaluate(() => window.scrollY)).toBeGreaterThan(1000);

await expect(page.getByRole('heading', { level: 2, name: 'Filtre' })).toBeInViewport();
await expect(page.getByRole('checkbox', { name: /Rødvin/ })).toBeInViewport();
});

test('har ingen axe-brudd med en utvidet liste og søk', async ({ page }) => {
const countries = page.getByRole('group', { name: 'Land' });
await countries.getByRole('button', { name: 'Vis alle i Land (30)' }).click();
await countries.getByRole('searchbox', { name: 'Søk i Land' }).fill('xyz');
await expect(countries.getByText('Ingen treff på «xyz».')).toBeVisible();

const axe = await new AxeBuilder({ page })
.withTags(['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa'])
.analyze();
expect(axe.violations).toEqual([]);
});
});
44 changes: 44 additions & 0 deletions frontend/src/features/search/SearchFilters.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,50 @@ describe('Filter på stor skjerm', () => {
expect(within(grapes).getAllByRole('checkbox')).toHaveLength(6);
});

it('har et søkefelt i en utvidet liste som snevrer inn valgene', async () => {
const { user } = renderPage([searchMock(() => 3).mock, filterOptionsMock().mock]);
const grapes = await screen.findByRole('group', { name: 'Drue' });
await within(grapes).findAllByRole('checkbox');
expect(within(grapes).queryByRole('searchbox')).not.toBeInTheDocument();

await user.click(within(grapes).getByRole('button', { name: 'Vis alle i Drue (8)' }));
await user.type(within(grapes).getByRole('searchbox', { name: 'Søk i Drue' }), 'drue8');

expect(within(grapes).getAllByRole('checkbox')).toHaveLength(1);
expect(within(grapes).getByRole('checkbox', { name: /Drue8/ })).toBeInTheDocument();
});

it('forklarer når søket i lista ikke gir treff', async () => {
const { user } = renderPage([searchMock(() => 3).mock, filterOptionsMock().mock]);
const grapes = await screen.findByRole('group', { name: 'Drue' });
await within(grapes).findAllByRole('checkbox');
await user.click(within(grapes).getByRole('button', { name: 'Vis alle i Drue (8)' }));

await user.type(within(grapes).getByRole('searchbox', { name: 'Søk i Drue' }), 'merlot');

expect(within(grapes).queryAllByRole('checkbox')).toHaveLength(0);
expect(within(grapes).getByText('Ingen treff på «merlot».')).toBeInTheDocument();
});

it('beholder fokus på knappen og holder den synlig når lista lukkes', async () => {
const scrollIntoView = vi.fn();
Element.prototype.scrollIntoView = scrollIntoView;
const { user } = renderPage([searchMock(() => 3).mock, filterOptionsMock().mock]);
const grapes = await screen.findByRole('group', { name: 'Drue' });
await within(grapes).findAllByRole('checkbox');
await user.click(within(grapes).getByRole('button', { name: 'Vis alle i Drue (8)' }));
await user.type(within(grapes).getByRole('searchbox', { name: 'Søk i Drue' }), 'drue8');

await user.click(within(grapes).getByRole('button', { name: 'Vis færre i Drue' }));

const toggle = within(grapes).getByRole('button', { name: 'Vis alle i Drue (8)' });
expect(toggle).toHaveFocus();
expect(scrollIntoView).toHaveBeenCalledWith({ block: 'nearest' });
expect(scrollIntoView.mock.contexts.at(-1)).toBe(toggle);
// The search is cleared, so the list is whole when it opens again.
expect(within(grapes).getAllByRole('checkbox')).toHaveLength(6);
});

it('viser alltid et valgt filter, også når listen er kort', async () => {
renderPage([searchMock(() => 3).mock, filterOptionsMock().mock], '/sok?drue=Drue8');
const grapes = await screen.findByRole('group', { name: 'Drue' });
Expand Down
12 changes: 12 additions & 0 deletions frontend/src/features/search/SearchView.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,18 @@
grid-template-columns: 16rem minmax(0, 1fr);
gap: var(--space-6);
}

/* The filters stay in view while the user scrolls through the results. If they are
taller than the window, they scroll by themselves instead of being cut off. */
.sidebar {
position: sticky;
top: var(--space-4);
align-self: start;
max-height: calc(100vh - 2 * var(--space-4));
overflow-y: auto;
overscroll-behavior: contain;
padding-inline: var(--space-1) var(--space-2);
}
}

/* The height is reserved so the list does not jump when the text changes. */
Expand Down
30 changes: 30 additions & 0 deletions frontend/src/features/search/components/FilterPanel.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,36 @@
list-style: none;
}

/* About seven values are visible at a time. The padding keeps the focus ring inside the box. */
.scrollable {
max-height: 20rem;
overflow-y: auto;
overscroll-behavior: contain;
padding: var(--space-1);
border: 1px solid var(--color-border);
border-radius: var(--radius-sm);
}

.search {
margin-bottom: var(--space-2);
}

.search input {
width: 100%;
min-height: var(--tap-target);
padding: 0 var(--space-3);
border: 1px solid var(--color-text-muted);
border-radius: var(--radius-sm);
background: var(--color-surface);
color: var(--color-text);
}

.noMatch {
font-size: var(--text-sm);
color: var(--color-text-muted);
overflow-wrap: anywhere;
}

.option {
display: flex;
align-items: center;
Expand Down
56 changes: 51 additions & 5 deletions frontend/src/features/search/components/FilterPanel.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useId, useState, type ChangeEvent } from 'react';
import { useId, useRef, useState, type ChangeEvent } from 'react';
import { flushSync } from 'react-dom';
import { useOnlineStatus } from '../../../hooks/useOnlineStatus';
import { classifyError, ERROR_DETAILS, isRetryable } from '../../../lib/errors';
import { pluralize } from '../../../lib/format';
Expand Down Expand Up @@ -74,16 +75,59 @@ export function FilterPanel({ state, groups, error, onRetry, onChange }: FilterP

function FilterGroup({ group, onToggle }: { group: Group; onToggle: (value: string) => void }) {
const [expanded, setExpanded] = useState(false);
const [query, setQuery] = useState('');
const toggleRef = useRef<HTMLButtonElement>(null);
const searchId = useId();
const listId = useId();
const { legend, options } = group;
// A selected value is always visible, so what filters the result can never be hidden.

const term = query.trim().toLocaleLowerCase('nb');
// A selected value is always visible when collapsed, so what filters the result is never hidden.
const visible = expanded
? options
? options.filter((option) => option.label.toLocaleLowerCase('nb').includes(term))
: options.filter((option, index) => index < COLLAPSED_COUNT || option.selected);

function toggle() {
if (!expanded) {
setExpanded(true);
return;
}
// Render the shorter list first, so the button is where it ends up before we scroll to it.
// Otherwise the user would be left far below the group they just closed.
flushSync(() => {
setExpanded(false);
setQuery('');
});
toggleRef.current?.scrollIntoView?.({ block: 'nearest' });
}

return (
<fieldset className={styles.group}>
<legend className={styles.legend}>{legend}</legend>
<ul role="list" className={styles.options}>
{expanded && (
<div className={styles.search}>
<label htmlFor={searchId} className="sr-only">
Søk i {legend}
</label>
<input
id={searchId}
type="search"
value={query}
placeholder={`Søk i ${legend.toLocaleLowerCase('nb')}`}
autoComplete="off"
onChange={(event) => setQuery(event.target.value)}
/>
</div>
)}
{expanded && visible.length === 0 && (
<p className={styles.noMatch}>Ingen treff på «{query.trim()}».</p>
)}
{/* The expanded list scrolls by itself, so the page does not grow by up to 40 values. */}
<ul
id={listId}
role="list"
className={`${styles.options} ${expanded ? styles.scrollable : ''}`}
>
{visible.map((option) => (
<li key={option.value}>
<label className={styles.option}>
Expand All @@ -101,10 +145,12 @@ function FilterGroup({ group, onToggle }: { group: Group; onToggle: (value: stri
</ul>
{options.length > COLLAPSED_COUNT && (
<button
ref={toggleRef}
type="button"
className={styles.expand}
aria-expanded={expanded}
onClick={() => setExpanded(!expanded)}
aria-controls={listId}
onClick={toggle}
>
{expanded ? `Vis færre i ${legend}` : `Vis alle i ${legend} (${options.length})`}
</button>
Expand Down