Redesigns the testimonials section #16

Merged
Sluijsens merged 3 commits from feature/testimonials-redesign into master 2026-11-06 01:35:57 +01:00
14 changed files with 607 additions and 159 deletions
Showing only changes of commit b03b18f58e - Show all commits
@@ -4,6 +4,7 @@ import {
Carousel,
chakra,
Flex,
Text,
useCarousel,
useMediaQuery,
useRecipe,
@@ -13,14 +14,16 @@ import { Icon } from '@iconify/react/offline';
import leftOutlined from '@iconify-icons/ant-design/left-outlined';
import rightOutlined from '@iconify-icons/ant-design/right-outlined';
import type { Testimonial } from '@/content/types';
import { slideCounter } from '@/lib/slideCounter';
import { slideLabel } from '@/lib/slideLabel';
import TestimonialSlide from './TestimonialSlide';
// The carousel itself. Chakra's carousel (Zag) handles paging, snapping,
// looping, swiping and hiding off-screen slides. The buttons, dots and arrow
// keys are our own: the built-in ones always scroll smoothly from
// JavaScript, which CSS cannot switch off for visitors who prefer reduced
// motion; ours pass the API's `instant` flag instead (BR-REV-06).
// looping, swiping and hiding off-screen slides. The buttons and arrow keys
// are our own: the built-in ones always scroll smoothly from JavaScript,
// which CSS cannot switch off for visitors who prefer reduced motion; ours
// pass the API's `instant` flag instead (BR-REV-06). The review only changes
// by those buttons and keys or by swiping: nothing moves by itself.
export default function TestimonialCarousel({
testimonials,
}: {
@@ -34,8 +37,8 @@ export default function TestimonialCarousel({
slideCount: count,
loop: true,
allowMouseDrag: true,
// Room between slides, so the next one never peeks in
spacing: '4rem',
// The slides follow each other directly, as in the design
spacing: '0px',
translations: { item: slideLabel },
onPageChange: ({ page }) => setAnnouncement(slideLabel(page, count)),
});
@@ -50,30 +53,39 @@ export default function TestimonialCarousel({
aria-label="Reviews"
aria-roledescription="carrousel"
gap={0}
// The control bar lies over the bottom right of the slides
position="relative"
maxW={{ lg: '1120px' }}
mx="auto"
>
{/* Our own live region announces changes, so the item group's
built-in one is switched off to avoid hearing it twice */}
<Carousel.ItemGroup aria-live="off">
{testimonials.map((testimonial, index) => (
// The photo's sand block sticks out 1.5rem to the left
// and below (FramedImage); the item group clips
// everything outside a slide, so each slide makes room
<Carousel.Item
key={testimonial.id}
index={index}
ps={{ base: 0, sm: '1.5rem' }}
pb={{ base: 0, sm: '1.5rem' }}
>
<TestimonialSlide testimonial={testimonial} />
<Carousel.Item key={testimonial.id} index={index}>
<TestimonialSlide
testimonial={testimonial}
withControls
near
/>
</Carousel.Item>
))}
</Carousel.ItemGroup>
{/* From lg the bar sits in the room under the card, in line with
the card's text; below lg it follows the slides, centred.
The 25% and 44px match the card's padding. */}
<Flex
position={{ lg: 'absolute' }}
bottom={{ lg: 0 }}
right={{ lg: 0 }}
w={{ lg: '56%' }}
ps={{ lg: '25%' }}
pe={{ lg: '44px' }}
mt={{ base: 7, lg: 0 }}
justifyContent="center"
alignItems="center"
gap={6}
mt="clamp(2.5rem, 5vw, 4rem)"
gap={3}
onKeyDown={(event) => {
if (event.key === 'ArrowLeft') previous();
else if (event.key === 'ArrowRight') next();
@@ -90,23 +102,19 @@ export default function TestimonialCarousel({
>
<Icon icon={leftOutlined} aria-hidden />
</chakra.button>
<Flex gap={1}>
{testimonials.map((testimonial, index) => (
<chakra.button
key={testimonial.id}
type="button"
aria-label={`Review ${index + 1}`}
aria-current={
carousel.page === index ? 'true' : undefined
}
data-testid={`testimonials-dot-${index + 1}`}
css={control({ kind: 'dot' })}
onClick={() =>
carousel.scrollTo(index, reducedMotion)
}
/>
))}
</Flex>
{/* Visible text only: the live region below says it aloud */}
<Text
aria-hidden="true"
data-testid="testimonials-counter"
minW="56px"
textAlign="center"
fontFamily="heading"
fontSize="16px"
letterSpacing="0.08em"
color="ink.soft"
>
{slideCounter(carousel.page, count)}
</Text>
<chakra.button
type="button"
aria-label="Volgende review"
@@ -2,11 +2,16 @@ import { screen } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import testimonials from '@/content/testimonials';
import { axeResults } from '@/test/axe';
import { cssRulesFor } from '@/test/cssRules';
import { renderWithProviders } from '@/test/renderWithProviders';
import TestimonialSlide from './TestimonialSlide';
// The rings review has a crop position; the newborn review has none
const rings = testimonials[0];
const review = testimonials[1];
const cropOf = () => cssRulesFor(screen.getByRole('img')).join();
describe('TestimonialSlide', () => {
it('shows the photo, shoot, quote and names', async () => {
const { container } = await renderWithProviders(
@@ -23,13 +28,58 @@ describe('TestimonialSlide', () => {
expect(await axeResults(container)).toHaveNoViolations();
});
it('keeps the decorative quotation mark away from assistive technology', async () => {
it('shows the names as they are, without a leading dash', async () => {
const { container } = await renderWithProviders(
<TestimonialSlide testimonial={review} />,
);
const mark = [
...container.querySelectorAll('[aria-hidden="true"]'),
].find((element) => element.textContent === '“');
expect(mark).toBeDefined();
const caption = container.querySelector('figcaption');
expect(caption).toHaveTextContent(review.author);
expect(cssRulesFor(caption!).join()).not.toContain('content');
});
it('has no decorative quotation mark', async () => {
const { container } = await renderWithProviders(
<TestimonialSlide testimonial={review} />,
);
expect(container.textContent).not.toMatch(/[“”]/);
expect(
[...container.querySelectorAll('[aria-hidden="true"]')].filter(
(element) => element.textContent?.trim(),
),
).toEqual([]);
});
it('crops the photo at the position of the review', async () => {
await renderWithProviders(<TestimonialSlide testimonial={rings} />);
expect(cropOf()).toContain('object-position: 50% 42%');
});
it('crops at the centre when the review has no position or a bad one', async () => {
const { unmount } = await renderWithProviders(
<TestimonialSlide testimonial={review} />,
);
expect(cropOf()).toContain('object-position: 50% 50%');
unmount();
await renderWithProviders(
<TestimonialSlide
testimonial={{ ...rings, imagePosition: '120% 40%' }}
/>,
);
expect(cropOf()).toContain('object-position: 50% 50%');
});
it('lays the card on paper.deep with no coloured block behind the photo', async () => {
const { container } = await renderWithProviders(
<TestimonialSlide testimonial={review} />,
);
const card = container.querySelector('figure')!.parentElement!;
expect(cssRulesFor(card).join()).toContain(
'background: var(--slp-colors-paper-deep)',
);
// No leftover sand block: the old frame drew it with a ::before
expect(
cssRulesFor(screen.getByRole('img').parentElement!).join(),
).not.toContain('::before');
});
});
@@ -1,73 +1,123 @@
import { Box, chakra, Grid, Text } from '@chakra-ui/react';
import Eyebrow from '@/components/Eyebrow/Eyebrow';
import FramedImage from '@/components/FramedImage/FramedImage';
import { Box, chakra, Text } from '@chakra-ui/react';
import DeferredImage from '@/components/DeferredImage/DeferredImage';
import type { Testimonial } from '@/content/types';
import { normalizeImagePosition } from '@/lib/normalizeImagePosition';
type TestimonialSlideProps = {
testimonial: Testimonial;
// The slide sits in a carousel whose control bar needs room under the
// card (from `lg` the bar lies inside the slide's own height)
withControls?: boolean;
// Load the photo straight away: for a slide in the carousel, whose
// off-screen slides are clipped and would never come into view on their
// own, so the next photo would still be loading while it slides in
near?: boolean;
};
// One review (design .testimonial): framed photo next to a large quotation
// mark, the shoot type, the quote and the names. Stacked below `lg`, with
// the photo centred.
// Room under the card for the control bar: a 22px gap and the 44px buttons
const CONTROL_ROOM = '66px';
// One review (design .testimonial): a landscape photo that overlaps a card
// with the shoot type, the quote and the names, centred. From `lg` the photo
// lies over the left of the card; below `lg` it is stacked, at most 640px
// wide and centred, with the card overlapping the bottom of the photo.
export default function TestimonialSlide({
testimonial,
withControls = false,
near,
}: TestimonialSlideProps) {
return (
<Grid
<Box
data-testid={`testimonial-${testimonial.id}`}
// 5:11 makes the photo column about 75% of the design's 5:7
templateColumns={{ base: '1fr', lg: '5fr 11fr' }}
gap={{ base: 5, lg: 'clamp(2rem, 6vw, 5.5rem)' }}
// Stacked, all slides share the tallest one's height: keep the
// content at the top, or a short review floats in the middle
alignContent={{ base: 'start', lg: 'center' }}
alignItems={{ base: 'start', lg: 'center' }}
w="100%"
h="100%"
maxW={{ base: '640px', lg: '1120px' }}
mx="auto"
// From lg both layers share one grid cell, so the slide is as high
// as the higher of the photo and the card
display={{ base: 'block', lg: 'grid' }}
alignContent={{ lg: 'start' }}
>
{/* Kept small and centred on phones and tablets, so the photo
does not fill the screen above the quote */}
<Box
maxW={{ base: '180px', md: '320px', lg: 'none' }}
w="100%"
mx={{ base: 'auto', lg: 0 }}
position="relative"
zIndex={1}
gridArea={{ lg: '1 / 1' }}
justifySelf={{ lg: 'start' }}
alignSelf={{ lg: 'start' }}
w={{ base: '100%', lg: '57%' }}
mt={{ lg: '40px' }}
>
<FramedImage image={testimonial.image} aspectRatio="4 / 5" />
<DeferredImage
image={testimonial.image}
near={near}
display="block"
w="100%"
h="auto"
aspectRatio={{ base: '4 / 3', lg: '3 / 2' }}
objectFit="cover"
objectPosition={normalizeImagePosition(
testimonial.imagePosition,
)}
// Shown until the photo arrives
bg="paper.deep"
/>
</Box>
<Box>
<Text
aria-hidden="true"
fontFamily="heading"
fontSize="clamp(5rem, 9vw, 7.5rem)"
lineHeight="1"
h="0.55em"
color="accent"
>
“
</Text>
<Eyebrow>{testimonial.shoot}</Eyebrow>
<Box
bg="paper.deep"
gridArea={{ lg: '1 / 1' }}
justifySelf={{ lg: 'end' }}
alignSelf={{ lg: 'start' }}
w={{ base: '100%', lg: '56%' }}
// The photo covers 13% of the width at the left of the card
// from lg; below it, 36px at the top. The text starts clear
// of it either way
mt={{ base: '-36px', lg: 0 }}
mb={{ lg: withControls ? CONTROL_ROOM : 0 }}
minH={{ lg: '400px' }}
pt={{ base: '72px', lg: '48px' }}
pb={{ base: 9, lg: '48px' }}
ps={{ base: 7, lg: '25%' }}
pe={{ base: 7, lg: '44px' }}
display="flex"
alignItems="center"
justifyContent="center"
>
{/* Plain elements, not Chakra's Blockquote: its slot recipe
would pull shared code into the chunk the hero waits for */}
<chakra.figure display="flex" flexDirection="column" gap={7}>
{/* Smaller than the design's clamp(1.35rem, 2.2vw,
1.75rem) at the owner's request: 18.4px to 22px */}
<chakra.blockquote
<chakra.figure
w="100%"
display="flex"
flexDirection="column"
alignItems="center"
gap={6}
textAlign="center"
>
<Text
fontFamily="heading"
fontSize="clamp(1.15rem, 1.7vw, 1.375rem)"
lineHeight="1.5"
fontSize={{ base: '19px', lg: '21px' }}
letterSpacing="0.2em"
textTransform="uppercase"
color="ink"
>
{testimonial.shoot}
</Text>
<chakra.blockquote
fontSize={{ base: '16.5px', lg: '17px' }}
fontWeight="300"
lineHeight="1.75"
color="ink.soft"
textWrap="pretty"
>
{testimonial.quote}
</chakra.blockquote>
<chakra.figcaption
textStyle="eyebrow"
color="ink.soft"
_before={{ content: '"— "' }}
color="accent.deeper"
>
{testimonial.author}
</chakra.figcaption>
</chakra.figure>
</Box>
</Grid>
</Box>
);
}
@@ -17,6 +17,8 @@ import Testimonials from './Testimonials';
const carousel = vi.hoisted(() => ({
props: undefined as UseCarouselProps | undefined,
calls: [] as Array<[string, ...unknown[]]>,
// Zag can not move in jsdom: a test sets the page the counter should show
page: undefined as number | undefined,
}));
vi.mock('@chakra-ui/react', async (importOriginal) => {
@@ -34,6 +36,7 @@ vi.mock('@chakra-ui/react', async (importOriginal) => {
};
return {
...api,
page: carousel.page ?? api.page,
scrollNext: record('scrollNext', api.scrollNext),
scrollPrev: record('scrollPrev', api.scrollPrev),
scrollTo: record('scrollTo', api.scrollTo),
@@ -44,6 +47,7 @@ vi.mock('@chakra-ui/react', async (importOriginal) => {
beforeEach(() => {
carousel.calls = [];
carousel.page = undefined;
vi.stubGlobal('IntersectionObserver', FakeIntersectionObserver);
Element.prototype.scrollTo = () => {};
});
@@ -79,6 +83,7 @@ async function renderTestimonials(items = testimonials) {
}
const status = () => screen.getByTestId('testimonials-status');
const counter = () => screen.getByTestId('testimonials-counter');
const button = (name: string) => screen.getByRole('button', { name });
const preferReducedMotion = () =>
@@ -130,8 +135,6 @@ describe('Testimonials', () => {
});
expect(button('Vorige review')).toBeInTheDocument();
expect(button('Volgende review')).toBeInTheDocument();
expect(button('Review 1')).toHaveAttribute('aria-current', 'true');
expect(button('Review 2')).not.toHaveAttribute('aria-current');
const slides = container.querySelectorAll(
'[aria-roledescription="slide"]',
);
@@ -157,42 +160,73 @@ describe('Testimonials', () => {
expect(status()).toHaveTextContent('Review 2 van 2');
});
it('moves with the arrows, the dots and the arrow keys', async () => {
it('moves with the arrows and the arrow keys', async () => {
await renderTestimonials();
fireEvent.click(button('Volgende review'));
fireEvent.click(button('Vorige review'));
fireEvent.click(button('Review 2'));
fireEvent.keyDown(button('Review 2'), { key: 'ArrowRight' });
fireEvent.keyDown(button('Review 2'), { key: 'ArrowLeft' });
fireEvent.keyDown(button('Review 2'), { key: 'Enter' });
fireEvent.keyDown(button('Vorige review'), { key: 'ArrowRight' });
fireEvent.keyDown(button('Volgende review'), { key: 'ArrowLeft' });
fireEvent.keyDown(button('Volgende review'), { key: 'Enter' });
expect(carousel.calls).toEqual([
['scrollNext', false],
['scrollPrev', false],
['scrollTo', 1, false],
['scrollNext', false],
['scrollPrev', false],
]);
});
it('has no dots: only the two arrows and the counter', async () => {
await renderTestimonials();
expect(screen.getAllByRole('button').map((b) => b.ariaLabel)).toEqual([
'Vorige review',
'Volgende review',
]);
expect(screen.queryByTestId('testimonials-dot-1')).toBeNull();
});
it('shows the counter as "X / Y" and keeps it away from assistive technology', async () => {
await renderTestimonials();
expect(counter()).toHaveTextContent('1 / 2');
expect(counter()).toHaveAttribute('aria-hidden', 'true');
carousel.page = 1;
act(() => {
carousel.props?.onPageChange?.({ page: 1, pageSnapPoint: 0 });
});
expect(counter()).toHaveTextContent('2 / 2');
// The announcement says the same thing aloud
expect(status()).toHaveTextContent('Review 2 van 2');
});
it('does not move by itself', async () => {
await renderTestimonials();
expect(carousel.props).not.toHaveProperty('autoplay');
await new Promise((resolve) => setTimeout(resolve, 100));
expect(carousel.calls).toEqual([]);
expect(status()).toHaveTextContent('');
expect(
screen.queryByRole('button', { name: /paus|afspel/i }),
).toBeNull();
});
it('scrolls instantly for visitors who prefer reduced motion', async () => {
preferReducedMotion();
await renderTestimonials();
fireEvent.click(button('Volgende review'));
fireEvent.click(button('Review 1'));
fireEvent.keyDown(button('Review 1'), { key: 'ArrowLeft' });
fireEvent.keyDown(button('Vorige review'), { key: 'ArrowLeft' });
expect(carousel.calls).toEqual([
['scrollNext', true],
['scrollTo', 0, true],
['scrollPrev', true],
]);
});
it('shows a single review without carousel controls', async () => {
it('shows a single review without carousel controls or counter', async () => {
await renderTestimonials([testimonials[0]]);
expect(
screen.getByTestId(`testimonial-${testimonials[0].id}`),
).toBeInTheDocument();
expect(screen.queryByRole('button')).toBeNull();
expect(screen.queryByTestId('testimonials-counter')).toBeNull();
});
it('leaves the section out when no review is valid', async () => {
@@ -68,13 +68,15 @@ export default function Testimonials({
}
// Stands in for the carousel until it has loaded: the longest review laid
// out exactly like a slide (same padding), plus the controls' height. That
// makes it as tall as the carousel at every screen width, so nothing below
// moves when the carousel takes its place, not even during a scroll to
// #contact that passes this section while it loads. The other reviews are in
// the page too, visually hidden, so the prerendered HTML holds every review
// text for search engines (BR-LZY-02). They are aria-hidden and inert, so
// assistive technology reads each review once, in the carousel.
// out exactly like a slide, plus the room for the controls. From `lg` that
// room is part of the slide; below `lg` the control bar follows the slides, so
// a spacer of its height is added. That makes it as tall as the carousel at
// every screen width, so nothing below moves when the carousel takes its
// place, not even during a scroll to #contact that passes this section while
// it loads. The other reviews are in the page too, visually hidden, so the
// prerendered HTML holds every review text for search engines (BR-LZY-02).
// They are aria-hidden and inert, so assistive technology reads each review
// once, in the carousel.
function CarouselPlaceholder({
testimonials,
}: {
@@ -84,10 +86,8 @@ function CarouselPlaceholder({
b.quote.length > a.quote.length ? b : a,
);
return (
<Box>
<Box ps={{ base: 0, sm: '1.5rem' }} pb={{ base: 0, sm: '1.5rem' }}>
<TestimonialSlide testimonial={longest} />
</Box>
<Box maxW={{ lg: '1120px' }} mx="auto">
<TestimonialSlide testimonial={longest} withControls />
{testimonials
.filter((testimonial) => testimonial !== longest)
.map((testimonial) => (
@@ -97,8 +97,13 @@ function CarouselPlaceholder({
</Box>
</VisuallyHidden>
))}
{/* The control bar: 48px buttons below the same margin */}
<Box mt="clamp(2.5rem, 5vw, 4rem)" h="48px" data-requires-js />
{/* Below lg the control bar: 44px buttons under a 28px margin */}
<Box
display={{ base: 'block', lg: 'none' }}
mt={7}
h="44px"
data-requires-js
/>
</Box>
);
}
+2
View File
@@ -18,6 +18,8 @@ const testimonials: Testimonial[] = [
width: 880,
height: 1100,
},
// The rings sit a little above the middle of the photo
imagePosition: '50% 42%',
},
{
id: 'demi-kevin',
+6 -1
View File
@@ -130,13 +130,18 @@ export interface ShootType {
}
// A review from a client ("Lieve woorden"). quote is plain text without
// quotation marks; the design adds a decorative one.
// quotation marks; the design shows none either.
export interface Testimonial {
id: string;
shoot: string;
quote: string;
author: string;
image: ContentImage;
// Which part of the photo stays visible in the landscape crop, as a CSS
// object-position of two percentages, e.g. '50% 42%'. Optional and not
// trusted: it goes through normalizeImagePosition, which falls back to
// the centre, and it has no say in whether the review is shown.
imagePosition?: string;
}
// Content of the homepage sections below the hero
@@ -0,0 +1,95 @@
import fc from 'fast-check';
import { describe, expect, it } from 'vitest';
import {
imagePositionAny,
imagePositionInvalid,
imagePositionValid,
} from '../test/arbitraries';
import { normalizeImagePosition } from './normalizeImagePosition';
const CENTRE = '50% 50%';
// The shape every result has: two numbers with at most two decimals
const SHAPE = /^(\d+(?:\.\d{1,2})?)% (\d+(?:\.\d{1,2})?)%$/;
describe('normalizeImagePosition (examples)', () => {
it('keeps a good value', () => {
expect(normalizeImagePosition('50% 42%')).toBe('50% 42%');
expect(normalizeImagePosition('0% 100%')).toBe('0% 100%');
});
it('writes the numbers tidily and ignores extra whitespace', () => {
expect(normalizeImagePosition('050.0% 42%')).toBe('50% 42%');
expect(normalizeImagePosition(' 12.50% 7.25% ')).toBe(
'12.5% 7.25%',
);
expect(normalizeImagePosition('50%\t42%')).toBe('50% 42%');
});
it('rounds tiny values instead of writing an exponent', () => {
expect(normalizeImagePosition('0.0000001% 50%')).toBe('0% 50%');
});
it('falls back to the centre for anything else', () => {
for (const bad of [
'120% 40%',
'50 42',
'50%',
'-5% 10%',
'1e1% 5%',
'',
'center',
]) {
expect(normalizeImagePosition(bad)).toBe(CENTRE);
}
expect(normalizeImagePosition(undefined)).toBe(CENTRE);
expect(normalizeImagePosition(null)).toBe(CENTRE);
expect(normalizeImagePosition(42)).toBe(CENTRE);
});
});
describe('normalizeImagePosition (properties)', () => {
it('always gives two numbers from 0 to 100 (invariant)', () => {
fc.assert(
fc.property(imagePositionAny, (value) => {
const match = SHAPE.exec(normalizeImagePosition(value));
expect(match).not.toBeNull();
const [x, y] = [Number(match?.[1]), Number(match?.[2])];
expect(x >= 0 && x <= 100 && y >= 0 && y <= 100).toBe(true);
}),
);
});
it('does not change a value that is already normalised (idempotence)', () => {
fc.assert(
fc.property(imagePositionAny, (value) => {
const once = normalizeImagePosition(value);
expect(normalizeImagePosition(once)).toBe(once);
}),
);
});
it('reads any layout of whitespace as the plain form (round-trip)', () => {
fc.assert(
fc.property(imagePositionValid, ({ x, y, text }) => {
expect(normalizeImagePosition(text)).toBe(`${x}% ${y}%`);
}),
);
});
it('gives exactly the centre for a value that is not acceptable (easy verification)', () => {
fc.assert(
fc.property(imagePositionInvalid, (value) => {
expect(normalizeImagePosition(value)).toBe(CENTRE);
}),
);
});
it('never throws, whatever it is given', () => {
fc.assert(
fc.property(fc.anything(), (value) => {
expect(typeof normalizeImagePosition(value)).toBe('string');
}),
);
});
});
+23
View File
@@ -0,0 +1,23 @@
// The centre of a photo, used whenever a crop position can not be trusted
const CENTRE = '50% 50%';
// Two numbers with a percent sign, separated by whitespace. Digits and an
// optional decimal part only: no sign, no exponent.
const NUMBER = '(\\d{1,3}(?:\\.\\d+)?)';
const POSITION = new RegExp(`^${NUMBER}%\\s+${NUMBER}%$`);
// Rounded to two decimals: enough for a crop, and it keeps tiny values from
// being written in exponent form, which would not read back
const tidy = (n: number) => Math.round(n * 100) / 100;
// The crop position of a photo (CSS object-position) from content that a CMS
// may deliver later: "X% Y%" with X and Y from 0 to 100, or the centre when
// the value is missing or not exactly that. Never throws (FR-TR-11/12).
export function normalizeImagePosition(value: unknown): string {
if (typeof value !== 'string') return CENTRE;
const match = POSITION.exec(value.trim());
if (!match) return CENTRE;
const [x, y] = [Number(match[1]), Number(match[2])];
if (x > 100 || y > 100) return CENTRE;
return `${tidy(x)}% ${tidy(y)}%`;
}
+80
View File
@@ -0,0 +1,80 @@
import fc from 'fast-check';
import { describe, expect, it } from 'vitest';
import { slideCounter } from './slideCounter';
// A position within a carousel: 1 to 20 slides, index within range
const position = fc
.integer({ min: 1, max: 20 })
.chain((count) =>
fc
.integer({ min: 0, max: count - 1 })
.map((index) => ({ index, count })),
);
// Any number at all, including the odd ones
const anyNumber = fc.oneof(
fc.integer(),
fc.double(),
fc.constantFrom(
Number.NaN,
Infinity,
-Infinity,
0,
-0,
1.5,
Number.MAX_VALUE,
),
);
describe('slideCounter (examples)', () => {
it('counts from one', () => {
expect(slideCounter(0, 2)).toBe('1 / 2');
expect(slideCounter(1, 2)).toBe('2 / 2');
expect(slideCounter(4, 12)).toBe('5 / 12');
});
it('stays within the range for odd input', () => {
expect(slideCounter(5, 2)).toBe('2 / 2');
expect(slideCounter(-3, 2)).toBe('1 / 2');
expect(slideCounter(0, 0)).toBe('1 / 1');
expect(slideCounter(Number.NaN, 3)).toBe('1 / 3');
expect(slideCounter(1, Number.NaN)).toBe('1 / 1');
expect(slideCounter(1.9, 3)).toBe('2 / 3');
});
});
describe('slideCounter (properties)', () => {
it('always reads "X / Y" with 1 <= X <= Y, for any numbers (invariant)', () => {
fc.assert(
fc.property(anyNumber, anyNumber, (index, count) => {
const match = /^(\d+) \/ (\d+)$/.exec(
slideCounter(index, count),
);
expect(match).not.toBeNull();
const [x, y] = [Number(match?.[1]), Number(match?.[2])];
expect(x >= 1 && x <= y).toBe(true);
}),
);
});
it('gives back its numbers for a valid position (round-trip)', () => {
fc.assert(
fc.property(position, ({ index, count }) => {
const [, x, y] =
/^(\d+) \/ (\d+)$/.exec(slideCounter(index, count)) ?? [];
expect(Number(x)).toBe(index + 1);
expect(Number(y)).toBe(count);
}),
);
});
it('equals the plain template for a valid position (oracle)', () => {
fc.assert(
fc.property(position, ({ index, count }) => {
expect(slideCounter(index, count)).toBe(
`${index + 1} / ${count}`,
);
}),
);
});
});
+13
View File
@@ -0,0 +1,13 @@
// The visible counter under the testimonials, e.g. "2 / 3": the current
// review (counted from 1) out of the total. index is zero-based. Odd input
// is made safe instead of thrown at: a total below 1 or not a finite number
// counts as 1, and an index outside the range moves to the nearest end, so
// the result always reads X / Y with 1 <= X <= Y (FR-TR-12).
export function slideCounter(index: number, count: number): string {
const total = Number.isFinite(count)
? Math.min(Math.max(1, Math.trunc(count)), Number.MAX_SAFE_INTEGER)
: 1;
const current = Number.isFinite(index) ? Math.trunc(index) : 0;
const position = Math.min(Math.max(current, 0), total - 1);
return `${position + 1} / ${total}`;
}
+31 -1
View File
@@ -1,7 +1,12 @@
import fc from 'fast-check';
import { describe, expect, it } from 'vitest';
import testimonials from '../content/testimonials';
import { anyTestimonial, uniqueTestimonials } from '../test/arbitraries';
import type { Testimonial } from '../content/types';
import {
anyTestimonial,
imagePositionAny,
uniqueTestimonials,
} from '../test/arbitraries';
import { isValidTestimonial, visibleTestimonials } from './visibleTestimonials';
const valid = testimonials[0];
@@ -63,6 +68,31 @@ describe('visibleTestimonials', () => {
);
});
it('does not let the crop position decide what is shown (invariant)', () => {
const ids = (items: Testimonial[]) =>
visibleTestimonials(items).map((item) => item.id);
fc.assert(
fc.property(
fc.array(anyTestimonial),
fc.array(imagePositionAny, { minLength: 1, maxLength: 5 }),
(input, positions) => {
const withOther = input.map((item, index) => ({
...item,
imagePosition: positions[index % positions.length] as
string | undefined,
}));
const withNone = input.map((item) => {
const copy = { ...item };
delete copy.imagePosition;
return copy;
});
expect(ids(withOther)).toEqual(ids(input));
expect(ids(withNone)).toEqual(ids(input));
},
),
);
});
it('returns valid, unique reviews unchanged (oracle)', () => {
fc.assert(
fc.property(uniqueTestimonials, (input) => {
+6 -29
View File
@@ -1,8 +1,8 @@
import { defineRecipe } from '@chakra-ui/react';
// Buttons under a carousel on a light background (design .testimonials__arrow
// and .testimonials__dot): square arrows with a hairline, and dots with a
// 44px hit area around a small visible circle.
// The previous and next buttons under the testimonials (design
// .testimonials__arrow): just the arrow, with no circle or border, in a 44px
// target. Hovering lightens it; keyboard focus gets the theme's focus ring.
const carouselControlRecipe = defineRecipe({
className: 'carousel-control',
base: {
@@ -18,34 +18,11 @@ const carouselControlRecipe = defineRecipe({
variants: {
kind: {
arrow: {
w: '48px',
h: '48px',
borderWidth: '1px',
borderColor: 'line',
fontSize: '1.1rem',
transitionProperty: 'border-color, background',
_hover: { borderColor: 'ink', bg: 'paper' },
_focusVisible: { borderColor: 'ink', bg: 'paper' },
},
dot: {
position: 'relative',
w: '44px',
h: '44px',
_after: {
content: '""',
position: 'absolute',
top: '50%',
left: '50%',
w: '8px',
h: '8px',
borderWidth: '1px',
borderColor: 'accent.deep',
rounded: 'full',
transform: 'translate(-50%, -50%)',
transitionProperty: 'background',
transitionDuration: 'interaction',
},
'&[aria-current="true"]::after': { bg: 'accent.deep' },
fontSize: '1.15rem',
transitionProperty: 'opacity',
_hover: { opacity: 0.55 },
},
},
},
+98 -22
View File
@@ -228,17 +228,89 @@ export const uniqueShootTypes = fc.uniqueArray(shootType, {
maxLength: 5,
});
// A review that meets every invariant
export const testimonial: fc.Arbitrary<Testimonial> = fc.record({
id: fc.oneof(
fc.constantFrom('majella-mark', 'demi-kevin'),
fc.stringMatching(/^[a-z0-9-]{1,16}$/),
// A crop position the way content may write it: two percentages from 0 to
// 100 (whole or with up to two decimals) with any whitespace around and
// between. x and y are the numbers, text is how they are written.
export const imagePositionValid = fc
.tuple(
fc.integer({ min: 0, max: 10000 }),
fc.integer({ min: 0, max: 10000 }),
fc.constantFrom('', ' ', '\t', '\n '),
fc.constantFrom(' ', ' ', '\t', ' \n '),
fc.constantFrom('', ' ', '\t'),
)
.map(([hundredthsX, hundredthsY, before, between, after]) => {
const [x, y] = [hundredthsX / 100, hundredthsY / 100];
return {
x,
y,
text: `${before}${x}%${between}${y}%${after}`,
};
});
// Crop positions that are not acceptable: out of range, one part, no percent
// sign, a sign or exponent, extra parts, other text and non-strings
export const imagePositionInvalid: fc.Arbitrary<unknown> = fc.oneof(
fc
.tuple(
fc.integer({ min: 10001, max: 99999 }),
fc.integer({ min: 0, max: 10000 }),
)
.map(([big, small]) => `${big / 100}% ${small / 100}%`),
fc
.tuple(
fc.integer({ min: 0, max: 10000 }),
fc.integer({ min: 10001, max: 99999 }),
)
.map(([small, big]) => `${small / 100}% ${big / 100}%`),
fc.constantFrom(
'',
' ',
'50%',
'50 42',
'50% 42',
'50 42%',
'-5% 10%',
'+5% 10%',
'1e1% 5%',
'50% 42% 10%',
'50%42%',
'center',
'top left',
'50.% 42%',
'.5% 42%',
),
shoot: nonBlank,
quote: nonBlank,
author: nonBlank,
image,
});
fc.constantFrom(undefined, null, 50, true, {}, ['50% 42%']),
);
// Anything content might hold in imagePosition: good and bad
export const imagePositionAny: fc.Arbitrary<unknown> = fc.oneof(
imagePositionValid.map(({ text }) => text),
imagePositionInvalid,
fc.string(),
);
// The raw text of a crop position as a review field: valid, garbled or odd
const imagePositionText = fc.oneof(
imagePositionValid.map(({ text }) => text),
fc.string(),
);
// A review that meets every invariant, with or without a crop position
export const testimonial: fc.Arbitrary<Testimonial> = fc.record(
{
id: fc.oneof(
fc.constantFrom('majella-mark', 'demi-kevin'),
fc.stringMatching(/^[a-z0-9-]{1,16}$/),
),
shoot: nonBlank,
quote: nonBlank,
author: nonBlank,
image,
imagePosition: imagePositionText,
},
{ requiredKeys: ['id', 'shoot', 'quote', 'author', 'image'] },
);
// Valid reviews with unique ids
export const uniqueTestimonials = fc.uniqueArray(testimonial, {
@@ -249,18 +321,22 @@ export const uniqueTestimonials = fc.uniqueArray(testimonial, {
// Valid and broken reviews mixed, as a CMS might deliver them
export const anyTestimonial: fc.Arbitrary<Testimonial> = fc.oneof(
testimonial,
fc.record({
id: fc.oneof(fc.constantFrom('majella-mark', '', ' '), fc.string()),
shoot: fc.oneof(nonBlank, fc.constantFrom('', ' ')),
quote: fc.oneof(nonBlank, fc.constantFrom('', ' ')),
author: fc.oneof(nonBlank, fc.constantFrom('', ' ')),
image: fc.record({
src: fc.oneof(fc.constant(''), fc.constant('/a.jpg')),
alt: fc.string({ maxLength: 10 }),
width: fc.integer({ min: -1, max: 10 }),
height: fc.integer({ min: -1, max: 10 }),
}),
}),
fc.record(
{
id: fc.oneof(fc.constantFrom('majella-mark', '', ' '), fc.string()),
shoot: fc.oneof(nonBlank, fc.constantFrom('', ' ')),
quote: fc.oneof(nonBlank, fc.constantFrom('', ' ')),
author: fc.oneof(nonBlank, fc.constantFrom('', ' ')),
image: fc.record({
src: fc.oneof(fc.constant(''), fc.constant('/a.jpg')),
alt: fc.string({ maxLength: 10 }),
width: fc.integer({ min: -1, max: 10 }),
height: fc.integer({ min: -1, max: 10 }),
}),
imagePosition: imagePositionText,
},
{ requiredKeys: ['id', 'shoot', 'quote', 'author', 'image'] },
),
);
// Shoot values as the form offers them for the live packages