Makes the first render match the prerendered HTML
Search values, the 404 buttons and the footer year now apply after hydration. The e-mail address stays out of the HTML behind a placeholder, and all review texts are in the page, so crawlers can read them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,7 +1,10 @@
|
||||
import { screen, within } from '@testing-library/react';
|
||||
import fc from 'fast-check';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import siteContent from '@/content/siteContent';
|
||||
import { validEmail } from '@/test/arbitraries';
|
||||
import { axeResults } from '@/test/axe';
|
||||
import { hydratePage, serverHtml } from '@/test/hydrate';
|
||||
import { renderWithProviders } from '@/test/renderWithProviders';
|
||||
import ContactDetails from './ContactDetails';
|
||||
|
||||
@@ -104,3 +107,72 @@ describe('ContactDetails', () => {
|
||||
expect(await axeResults(container)).toHaveNoViolations();
|
||||
});
|
||||
});
|
||||
|
||||
// The address is only there after hydrating; before, the first item is an
|
||||
// empty placeholder of the same height (BR-MAIL-04, BR-MAIL-07)
|
||||
describe('ContactDetails in the prerendered HTML', () => {
|
||||
it('holds a placeholder first and the socials, but no address', async () => {
|
||||
const html = await serverHtml(card());
|
||||
expect(html.toLowerCase()).not.toContain('info@andreaslop.nl');
|
||||
expect(html).not.toContain('mailto:');
|
||||
expect(html).toContain('data-testid="contact-details-email-pending"');
|
||||
expect(html.indexOf('contact-details-email-pending')).toBeLessThan(
|
||||
html.indexOf('contact-details-instagram'),
|
||||
);
|
||||
expect(html).toContain('contact-details-facebook');
|
||||
});
|
||||
|
||||
it('never holds the address, whatever the content (invariant)', async () => {
|
||||
await fc.assert(
|
||||
fc.asyncProperty(validEmail, async (email) => {
|
||||
const html = await serverHtml(card({ email }));
|
||||
expect(html.toLowerCase()).not.toContain(
|
||||
`${email.user}@${email.domain}`.toLowerCase(),
|
||||
);
|
||||
expect(html).not.toContain('mailto:');
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('swaps the placeholder for the link after hydrating', async () => {
|
||||
const { errors } = await hydratePage(card());
|
||||
const mail = await screen.findByTestId('contact-details-email');
|
||||
expect(mail).toHaveAttribute(
|
||||
'href',
|
||||
'mailto:info@andreaslop.nl?subject=Vraag%20via%20andreaslop.nl',
|
||||
);
|
||||
expect(
|
||||
screen.queryByTestId('contact-details-email-pending'),
|
||||
).not.toBeInTheDocument();
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
|
||||
it('marks the placeholder hidden, empty and without a link', async () => {
|
||||
const html = await serverHtml(card());
|
||||
const doc = new DOMParser().parseFromString(html, 'text/html');
|
||||
const pending = doc.querySelector('[data-email-pending]')!;
|
||||
expect(pending.getAttribute('aria-hidden')).toBe('true');
|
||||
expect(pending.textContent).toBe('');
|
||||
expect(pending.querySelector('a')).toBeNull();
|
||||
});
|
||||
|
||||
it('has no placeholder on a plain mount', async () => {
|
||||
const { container } = await renderWithProviders(card());
|
||||
expect(container.querySelector('[data-email-pending]')).toBeNull();
|
||||
});
|
||||
|
||||
it('has no placeholder without a valid address, only the socials', async () => {
|
||||
const html = await serverHtml(
|
||||
card({ email: { user: '', domain: 'andreaslop.nl' } }),
|
||||
);
|
||||
expect(html).not.toContain('email-pending');
|
||||
expect(html).toContain('contact-details-instagram');
|
||||
});
|
||||
|
||||
it('renders nothing without an address and without socials', async () => {
|
||||
const html = await serverHtml(
|
||||
card({ email: { user: '', domain: '' }, socials: [] }),
|
||||
);
|
||||
expect(html).not.toContain('data-testid="details"');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -11,6 +11,7 @@ import { Icon } from '@iconify/react/offline';
|
||||
import Eyebrow from '@/components/Eyebrow/Eyebrow';
|
||||
import socialPlatforms from '@/content/socialPlatforms';
|
||||
import type { ContentImage, EmailAddress, SocialLink } from '@/content/types';
|
||||
import useHydrated from '@/hooks/useHydrated';
|
||||
import { contactChannels, type ContactChannel } from '@/lib/contactChannels';
|
||||
|
||||
type ContactDetailsProps = {
|
||||
@@ -25,13 +26,18 @@ type ContactDetailsProps = {
|
||||
'data-testid'?: string;
|
||||
};
|
||||
|
||||
const iconOf = (channel: ContactChannel) =>
|
||||
// Channels that render as a link; the pending e-mail item is not one
|
||||
type LinkChannel = Exclude<ContactChannel, { kind: 'email-pending' }>;
|
||||
|
||||
const iconOf = (channel: LinkChannel) =>
|
||||
channel.kind === 'email'
|
||||
? mailFilled
|
||||
: socialPlatforms[channel.platform].icon;
|
||||
|
||||
// "Direct contact": a card with the ways to reach Andrea, each an icon and a
|
||||
// link (BR-CD-01..08). Renders nothing when no channel is valid.
|
||||
// link (BR-CD-01..08). Renders nothing when no channel is valid. Before
|
||||
// hydration the e-mail item is an empty placeholder of the same height
|
||||
// (BR-MAIL-04).
|
||||
export default function ContactDetails({
|
||||
titleId,
|
||||
title,
|
||||
@@ -40,7 +46,8 @@ export default function ContactDetails({
|
||||
portrait,
|
||||
'data-testid': testId,
|
||||
}: ContactDetailsProps) {
|
||||
const channels = contactChannels(email, socials);
|
||||
// The address is only assembled after hydration (BR-MAIL-07)
|
||||
const channels = contactChannels(email, socials, useHydrated());
|
||||
if (channels.length === 0) return null;
|
||||
|
||||
return (
|
||||
@@ -71,47 +78,57 @@ export default function ContactDetails({
|
||||
</Eyebrow>
|
||||
</Flex>
|
||||
<chakra.ul listStyleType="none" aria-labelledby={titleId}>
|
||||
{channels.map((channel) => (
|
||||
<chakra.li key={channel.href}>
|
||||
<Link
|
||||
variant="subtle"
|
||||
href={channel.href}
|
||||
display="flex"
|
||||
alignItems="center"
|
||||
gap={4}
|
||||
{channels.map((channel) =>
|
||||
channel.kind === 'email-pending' ? (
|
||||
<chakra.li
|
||||
key={channel.kind}
|
||||
aria-hidden="true"
|
||||
minH="44px"
|
||||
{...(channel.external && {
|
||||
target: '_blank',
|
||||
rel: 'noopener noreferrer',
|
||||
})}
|
||||
data-testid={`contact-details-${
|
||||
channel.kind === 'email'
|
||||
? 'email'
|
||||
: channel.platform
|
||||
}`}
|
||||
>
|
||||
<Box
|
||||
as="span"
|
||||
color="accent.deep"
|
||||
fontSize="1.375rem"
|
||||
display="inline-flex"
|
||||
data-email-pending
|
||||
data-testid="contact-details-email-pending"
|
||||
/>
|
||||
) : (
|
||||
<chakra.li key={channel.href}>
|
||||
<Link
|
||||
variant="subtle"
|
||||
href={channel.href}
|
||||
display="flex"
|
||||
alignItems="center"
|
||||
gap={4}
|
||||
minH="44px"
|
||||
{...(channel.external && {
|
||||
target: '_blank',
|
||||
rel: 'noopener noreferrer',
|
||||
})}
|
||||
data-testid={`contact-details-${
|
||||
channel.kind === 'email'
|
||||
? 'email'
|
||||
: channel.platform
|
||||
}`}
|
||||
>
|
||||
<Icon icon={iconOf(channel)} aria-hidden />
|
||||
</Box>
|
||||
{/* Space outside the hidden text, or it drops out
|
||||
<Box
|
||||
as="span"
|
||||
color="accent.deep"
|
||||
fontSize="1.375rem"
|
||||
display="inline-flex"
|
||||
>
|
||||
<Icon icon={iconOf(channel)} aria-hidden />
|
||||
</Box>
|
||||
{/* Space outside the hidden text, or it drops out
|
||||
of the announced name */}
|
||||
{channel.label}
|
||||
{channel.external && (
|
||||
<>
|
||||
{' '}
|
||||
<VisuallyHidden>
|
||||
(opent in nieuw tabblad)
|
||||
</VisuallyHidden>
|
||||
</>
|
||||
)}
|
||||
</Link>
|
||||
</chakra.li>
|
||||
))}
|
||||
{channel.label}
|
||||
{channel.external && (
|
||||
<>
|
||||
{' '}
|
||||
<VisuallyHidden>
|
||||
(opent in nieuw tabblad)
|
||||
</VisuallyHidden>
|
||||
</>
|
||||
)}
|
||||
</Link>
|
||||
</chakra.li>
|
||||
),
|
||||
)}
|
||||
</chakra.ul>
|
||||
</Box>
|
||||
);
|
||||
|
||||
@@ -5,6 +5,7 @@ import packages from '@/content/packages';
|
||||
import siteContent from '@/content/siteContent';
|
||||
import { shootOptions } from '@/lib/shootOptions';
|
||||
import { axeResults } from '@/test/axe';
|
||||
import { serverHtml } from '@/test/hydrate';
|
||||
import { renderWithProviders } from '@/test/renderWithProviders';
|
||||
import ContactForm from './ContactForm';
|
||||
|
||||
@@ -234,3 +235,21 @@ describe('ContactForm', () => {
|
||||
expect(container.querySelector('[data-robot-check]')).not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('ContactForm in the prerendered HTML', () => {
|
||||
it('does not hold the address (BR-MAIL-06)', async () => {
|
||||
const html = await serverHtml(
|
||||
<ContactForm
|
||||
idPrefix="test"
|
||||
options={options}
|
||||
mailSubject="Vraag via andreaslop.nl"
|
||||
email={siteContent.email}
|
||||
replyTime="1-2 werkdagen"
|
||||
submit={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
expect(html).toContain('contact-form-submit');
|
||||
expect(html.toLowerCase()).not.toContain('info@andreaslop.nl');
|
||||
expect(html).not.toContain('mailto:');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -26,7 +26,7 @@ import {
|
||||
INITIAL_CONTACT_STATE,
|
||||
type ContactFormEvent,
|
||||
} from '@/lib/contactFormReducer';
|
||||
import { emailAddress } from '@/lib/emailAddress';
|
||||
import useEmailAddress from '@/hooks/useEmailAddress';
|
||||
import { mailtoLink } from '@/lib/mailLink';
|
||||
import { toContactPayload } from '@/lib/toContactPayload';
|
||||
import { CONTACT_FIELDS } from '@/lib/validateContact';
|
||||
@@ -92,7 +92,7 @@ export default function ContactForm({
|
||||
if (state.status === 'sent') sentMessage.current?.focus();
|
||||
}, [state.status]);
|
||||
|
||||
const address = emailAddress(email);
|
||||
const { address } = useEmailAddress(email);
|
||||
const disabled = state.status === 'sending';
|
||||
|
||||
if (state.status === 'sent') {
|
||||
|
||||
@@ -2,6 +2,8 @@ import { screen } from '@testing-library/react';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import siteContent from '@/content/siteContent';
|
||||
import { axeResults } from '@/test/axe';
|
||||
import { cssRulesFor } from '@/test/cssRules';
|
||||
import { hydratePage, serverHtml } from '@/test/hydrate';
|
||||
import { renderWithProviders } from '@/test/renderWithProviders';
|
||||
import ContactFormGate from './ContactFormGate';
|
||||
|
||||
@@ -71,3 +73,77 @@ describe('ContactFormGate', () => {
|
||||
expect(await axeResults(container)).toHaveNoViolations();
|
||||
});
|
||||
});
|
||||
|
||||
// Before hydrating the notice has the sentence only and reserves the room of
|
||||
// the address and the button (BR-MAIL-05)
|
||||
describe('ContactFormGate in the prerendered HTML', () => {
|
||||
const gate = (email = siteContent.email) => (
|
||||
<ContactFormGate
|
||||
enabled={false}
|
||||
email={email}
|
||||
subject="Aanvraag fotoshoot: Newborn"
|
||||
>
|
||||
<form aria-label="Formulier" />
|
||||
</ContactFormGate>
|
||||
);
|
||||
const prerendered = async (email?: typeof siteContent.email) => {
|
||||
const html = await serverHtml(gate(email));
|
||||
const doc = new DOMParser().parseFromString(html, 'text/html');
|
||||
return { html, doc };
|
||||
};
|
||||
|
||||
it('holds the sentence only, hidden placeholders and no address', async () => {
|
||||
const { html, doc } = await prerendered();
|
||||
expect(html.toLowerCase()).not.toContain('info@andreaslop.nl');
|
||||
expect(html).not.toContain('mailto:');
|
||||
expect(html).not.toContain('Mail me voor nu op');
|
||||
expect(html).not.toContain('data-testid="contact-gate-mail"');
|
||||
expect(
|
||||
doc.querySelector('[data-testid="contact-gate-notice"]')!
|
||||
.textContent,
|
||||
).toContain('Het contactformulier komt binnenkort.');
|
||||
const pending = doc.querySelector(
|
||||
'[data-testid="contact-gate-mail-pending"]',
|
||||
)!;
|
||||
expect(pending.getAttribute('aria-hidden')).toBe('true');
|
||||
expect(pending.hasAttribute('data-email-pending')).toBe(true);
|
||||
expect(pending.getAttribute('href')).toBeNull();
|
||||
});
|
||||
|
||||
it('reserves the width of the lead and the address in characters', async () => {
|
||||
const { doc } = await prerendered();
|
||||
const reserved = doc.querySelector('p [data-email-pending]')!;
|
||||
// Hydrating makes React generate the same classes, which puts their
|
||||
// rules in the document
|
||||
await hydratePage(gate());
|
||||
const probe = document.createElement('span');
|
||||
probe.className = reserved.className;
|
||||
// ' Mail me voor nu op ' (20) + 'info@andreaslop.nl' (18)
|
||||
expect(cssRulesFor(probe).join(' ')).toContain('width: 38ch');
|
||||
});
|
||||
|
||||
it('shows the address, link and button after hydrating', async () => {
|
||||
const { errors } = await hydratePage(gate());
|
||||
const mail = await screen.findByTestId('contact-gate-mail');
|
||||
expect(mail).toHaveAttribute(
|
||||
'href',
|
||||
'mailto:info@andreaslop.nl?subject=Aanvraag%20fotoshoot%3A%20Newborn',
|
||||
);
|
||||
expect(screen.getByTestId('contact-gate-notice')).toHaveTextContent(
|
||||
'Het contactformulier komt binnenkort. Mail me voor nu op info@andreaslop.nl',
|
||||
);
|
||||
expect(
|
||||
screen.queryByTestId('contact-gate-mail-pending'),
|
||||
).not.toBeInTheDocument();
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
|
||||
it('has no placeholders without a valid address', async () => {
|
||||
const { html } = await prerendered({
|
||||
user: '',
|
||||
domain: 'andreaslop.nl',
|
||||
});
|
||||
expect(html).not.toContain('email-pending');
|
||||
expect(html).toContain('Het contactformulier komt binnenkort.');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,7 +3,7 @@ import { Box, chakra, Link, Text, useRecipe } from '@chakra-ui/react';
|
||||
import Eyebrow from '@/components/Eyebrow/Eyebrow';
|
||||
import PrivacyNote from '@/components/PrivacyNote/PrivacyNote';
|
||||
import type { EmailAddress } from '@/content/types';
|
||||
import { emailAddress } from '@/lib/emailAddress';
|
||||
import useEmailAddress from '@/hooks/useEmailAddress';
|
||||
import { mailtoLink } from '@/lib/mailLink';
|
||||
|
||||
type ContactFormGateProps = {
|
||||
@@ -13,6 +13,9 @@ type ContactFormGateProps = {
|
||||
children: ReactNode;
|
||||
};
|
||||
|
||||
// The text that comes before the address once it is shown
|
||||
const MAIL_LEAD = ' Mail me voor nu op ';
|
||||
|
||||
// Until there is a back-end the form stays visible but dimmed and inert
|
||||
// under a "coming soon" notice with a mail button (FR-HP-07). inert keeps
|
||||
// keyboard and screen reader users out of a form that does nothing.
|
||||
@@ -23,10 +26,11 @@ export default function ContactFormGate({
|
||||
children,
|
||||
}: ContactFormGateProps) {
|
||||
const linkButton = useRecipe({ key: 'linkButton' });
|
||||
// Assembled after hydration, so the address is nowhere in the HTML or the
|
||||
// bundle (BR-MAIL-05)
|
||||
const { available, address } = useEmailAddress(email);
|
||||
if (enabled) return <>{children}</>;
|
||||
|
||||
// Assembled in the browser, so the address is nowhere in the bundle
|
||||
const address = emailAddress(email);
|
||||
const href = address ? mailtoLink(address, subject) : undefined;
|
||||
|
||||
return (
|
||||
@@ -49,26 +53,52 @@ export default function ContactFormGate({
|
||||
data-testid="contact-gate-notice"
|
||||
>
|
||||
<Eyebrow>Binnenkort</Eyebrow>
|
||||
<Text color="ink.soft" mb={address ? 7 : 0}>
|
||||
<Text color="ink.soft" mb={available ? 7 : 0}>
|
||||
Het contactformulier komt binnenkort.
|
||||
{address && (
|
||||
{address ? (
|
||||
<>
|
||||
{' Mail me voor nu op '}
|
||||
{MAIL_LEAD}
|
||||
<Link variant="underline" href={href}>
|
||||
{address}
|
||||
</Link>
|
||||
</>
|
||||
) : (
|
||||
available && (
|
||||
// Reserves the width of the lead and the address
|
||||
// (counted without assembling it), so the line
|
||||
// breaks where it will after hydration
|
||||
<chakra.span
|
||||
display="inline-block"
|
||||
visibility="hidden"
|
||||
aria-hidden="true"
|
||||
w={`${MAIL_LEAD.length + email.user.length + 1 + email.domain.length}ch`}
|
||||
data-email-pending
|
||||
/>
|
||||
)
|
||||
)}
|
||||
</Text>
|
||||
{address && (
|
||||
<chakra.a
|
||||
href={href}
|
||||
css={linkButton({ variant: 'accent' })}
|
||||
data-testid="contact-gate-mail"
|
||||
>
|
||||
Stuur een e-mail
|
||||
</chakra.a>
|
||||
)}
|
||||
{available &&
|
||||
(address ? (
|
||||
<chakra.a
|
||||
href={href}
|
||||
css={linkButton({ variant: 'accent' })}
|
||||
data-testid="contact-gate-mail"
|
||||
>
|
||||
Stuur een e-mail
|
||||
</chakra.a>
|
||||
) : (
|
||||
// Same recipe and label, so the notice is as high as
|
||||
// it will be; hidden from sight and from readers
|
||||
<chakra.span
|
||||
css={linkButton({ variant: 'accent' })}
|
||||
visibility="hidden"
|
||||
aria-hidden="true"
|
||||
data-email-pending
|
||||
data-testid="contact-gate-mail-pending"
|
||||
>
|
||||
Stuur een e-mail
|
||||
</chakra.span>
|
||||
))}
|
||||
{/* Readable now, while the form's own line is inert (BR-PR-03) */}
|
||||
<PrivacyNote mt={6} />
|
||||
</Box>
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import { screen, within } from '@testing-library/react';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import fc from 'fast-check';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import siteContent from '@/content/siteContent';
|
||||
import type { SiteContent } from '@/content/types';
|
||||
import { validEmail } from '@/test/arbitraries';
|
||||
import { axeResults } from '@/test/axe';
|
||||
import { hydratePage, serverHtml } from '@/test/hydrate';
|
||||
import { renderWithProviders } from '@/test/renderWithProviders';
|
||||
import Footer from './Footer';
|
||||
|
||||
@@ -126,3 +129,95 @@ describe('Footer', () => {
|
||||
expect(screen.queryByTestId('footer-email-link')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// The page is prerendered and hydrated in the browser: the address and the
|
||||
// current year only come after hydrating (BR-MAIL-01, BR-HYD-14)
|
||||
describe('Footer in the prerendered HTML', () => {
|
||||
const noAddress = (html: string, address: string) => {
|
||||
expect(html.toLowerCase()).not.toContain(address.toLowerCase());
|
||||
expect(html).not.toContain('mailto:');
|
||||
};
|
||||
|
||||
it('holds an empty placeholder instead of the address', async () => {
|
||||
const html = await serverHtml(<Footer content={siteContent} />);
|
||||
noAddress(html, 'info@andreaslop.nl');
|
||||
expect(html).not.toContain('footer-email-link');
|
||||
expect(html).toContain('data-testid="footer-email-pending"');
|
||||
expect(html).toContain('>Contact</h2>');
|
||||
});
|
||||
|
||||
it('never holds the address, whatever the content (invariant)', async () => {
|
||||
await fc.assert(
|
||||
fc.asyncProperty(validEmail, async ({ user, domain }) => {
|
||||
const html = await serverHtml(
|
||||
<Footer
|
||||
content={{ ...siteContent, email: { user, domain } }}
|
||||
/>,
|
||||
);
|
||||
noAddress(html, `${user}@${domain}`);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('has no Contact column and no placeholder without a valid address', async () => {
|
||||
const html = await serverHtml(
|
||||
<Footer
|
||||
content={{
|
||||
...siteContent,
|
||||
email: { user: '', domain: 'andreaslop.nl' },
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
expect(html).not.toContain('>Contact</h2>');
|
||||
expect(html).not.toContain('footer-email-pending');
|
||||
});
|
||||
|
||||
it('shows the placeholder, no link and an empty hidden item while hydrating, then the link', async () => {
|
||||
const html = await serverHtml(<Footer content={siteContent} />);
|
||||
const { container, errors } = await hydratePage(
|
||||
<Footer content={siteContent} />,
|
||||
);
|
||||
expect(errors).toEqual([]);
|
||||
expect(html).toContain('aria-hidden="true"');
|
||||
await screen.findByTestId('footer-email-link');
|
||||
expect(screen.getByTestId('footer-email-link')).toHaveAttribute(
|
||||
'href',
|
||||
'mailto:info@andreaslop.nl',
|
||||
);
|
||||
expect(
|
||||
container.querySelector('[data-email-pending]'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('uses the build year while hydrating and the current year after', async () => {
|
||||
vi.stubEnv('VITE_BUILD_YEAR', '2001');
|
||||
try {
|
||||
const html = await serverHtml(<Footer content={siteContent} />);
|
||||
expect(html).toContain('© 2001 Andrea Slop Fotografie');
|
||||
|
||||
const { container, errors } = await hydratePage(
|
||||
<Footer content={siteContent} />,
|
||||
);
|
||||
expect(container).toHaveTextContent(
|
||||
`© ${new Date().getFullYear()} Andrea Slop Fotografie`,
|
||||
);
|
||||
expect(errors).toEqual([]);
|
||||
} finally {
|
||||
vi.unstubAllEnvs();
|
||||
}
|
||||
});
|
||||
|
||||
it('shows the current year at once on a plain mount', async () => {
|
||||
vi.stubEnv('VITE_BUILD_YEAR', '2001');
|
||||
try {
|
||||
await renderFooter();
|
||||
expect(
|
||||
screen.getByText(
|
||||
`© ${new Date().getFullYear()} Andrea Slop Fotografie`,
|
||||
),
|
||||
).toBeInTheDocument();
|
||||
} finally {
|
||||
vi.unstubAllEnvs();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -10,8 +10,9 @@ import {
|
||||
} from '@chakra-ui/react';
|
||||
import socialPlatforms from '@/content/socialPlatforms';
|
||||
import type { SiteContent } from '@/content/types';
|
||||
import useEmailAddress from '@/hooks/useEmailAddress';
|
||||
import useHydrated from '@/hooks/useHydrated';
|
||||
import { copyrightLine } from '@/lib/copyrightLine';
|
||||
import { emailAddress } from '@/lib/emailAddress';
|
||||
import { visibleSocials } from '@/lib/visibleSocials';
|
||||
import { footerNav } from '@/navigation';
|
||||
import RouterLink from '../RouterLink';
|
||||
@@ -29,9 +30,15 @@ type FooterProps = {
|
||||
// copyright en het footermenu. Een lege kolom valt weg (BR-FOOT-01).
|
||||
export default function Footer({ content }: FooterProps) {
|
||||
const socials = visibleSocials(content.socials);
|
||||
// Pas hier samengevoegd, zodat het adres nergens letterlijk staat
|
||||
const email = emailAddress(content.email);
|
||||
const year = new Date().getFullYear();
|
||||
// Het adres wordt pas na de hydratatie samengevoegd, zodat het nergens
|
||||
// letterlijk in de HTML of de bundel staat (BR-MAIL-01). Ervoor houdt een
|
||||
// lege plek de ruimte vrij.
|
||||
const { available, address } = useEmailAddress(content.email);
|
||||
// Het jaar van de build tot de hydratatie, zodat server en browser
|
||||
// dezelfde HTML hebben; daarna het huidige jaar (BR-HYD-14)
|
||||
const year = useHydrated()
|
||||
? new Date().getFullYear()
|
||||
: Number(import.meta.env.VITE_BUILD_YEAR);
|
||||
|
||||
return (
|
||||
<Box
|
||||
@@ -98,16 +105,27 @@ export default function Footer({ content }: FooterProps) {
|
||||
</FooterColumn>
|
||||
)}
|
||||
|
||||
{email && (
|
||||
{available && (
|
||||
<FooterColumn title="Contact">
|
||||
<chakra.li>
|
||||
<FooterLink
|
||||
href={`mailto:${email}`}
|
||||
data-testid="footer-email-link"
|
||||
>
|
||||
{email}
|
||||
</FooterLink>
|
||||
</chakra.li>
|
||||
{address === null ? (
|
||||
// Even hoog als FooterLink (44px onder lg, daarna
|
||||
// een tekstregel), zodat de kolom niet verspringt
|
||||
<chakra.li
|
||||
aria-hidden="true"
|
||||
minH={{ base: '44px', lg: '1lh' }}
|
||||
data-email-pending
|
||||
data-testid="footer-email-pending"
|
||||
/>
|
||||
) : (
|
||||
<chakra.li>
|
||||
<FooterLink
|
||||
href={`mailto:${address}`}
|
||||
data-testid="footer-email-link"
|
||||
>
|
||||
{address}
|
||||
</FooterLink>
|
||||
</chakra.li>
|
||||
)}
|
||||
</FooterColumn>
|
||||
)}
|
||||
</Grid>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { act, fireEvent, render, renderHook } from '@testing-library/react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { hydrate, renderToString } from '@/test/hydrate';
|
||||
import useHeroSlider from './useHeroSlider';
|
||||
|
||||
// De automatische wissel komt in de browser van animationend op de
|
||||
@@ -84,3 +85,74 @@ describe('useHeroSlider', () => {
|
||||
expect(slider).toMatchObject({ stopped: false, paused: false });
|
||||
});
|
||||
});
|
||||
|
||||
// In de HTML is het tabblad zichtbaar en loopt autoplay; pas na de hydratatie
|
||||
// telt wat de browser meldt (BR-HYD-09)
|
||||
describe('useHeroSlider tijdens het hydrateren', () => {
|
||||
const seen: { paused: boolean; autoplay: boolean }[] = [];
|
||||
|
||||
function Probe() {
|
||||
const { paused, autoplay } = useHeroSlider(3);
|
||||
seen.push({ paused, autoplay });
|
||||
return (
|
||||
<p>
|
||||
{paused ? 'gepauzeerd' : 'loopt'}
|
||||
{autoplay ? ' autoplay' : ' stil'}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
it('geeft in de serverrender een zichtbaar tabblad', () => {
|
||||
vi.spyOn(document, 'hidden', 'get').mockReturnValue(true);
|
||||
expect(renderToString(<Probe />)).toContain('loopt');
|
||||
});
|
||||
|
||||
it('leest document.hidden pas na het hydrateren', () => {
|
||||
vi.spyOn(document, 'hidden', 'get').mockReturnValue(true);
|
||||
seen.length = 0;
|
||||
const { container, errors } = hydrate(<Probe />);
|
||||
expect(seen[0].paused).toBe(false);
|
||||
expect(container).toHaveTextContent('gepauzeerd');
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
|
||||
it('volgt visibilitychange', () => {
|
||||
const hidden = vi.spyOn(document, 'hidden', 'get');
|
||||
hidden.mockReturnValue(false);
|
||||
const { container } = hydrate(<Probe />);
|
||||
expect(container).toHaveTextContent('loopt');
|
||||
|
||||
act(() => {
|
||||
hidden.mockReturnValue(true);
|
||||
document.dispatchEvent(new Event('visibilitychange'));
|
||||
});
|
||||
expect(container).toHaveTextContent('gepauzeerd');
|
||||
});
|
||||
|
||||
it('leest document.hidden meteen bij een latere mount', () => {
|
||||
vi.spyOn(document, 'hidden', 'get').mockReturnValue(true);
|
||||
seen.length = 0;
|
||||
render(<Probe />);
|
||||
expect(seen[0].paused).toBe(true);
|
||||
});
|
||||
|
||||
it('gaat in de eerste render uit van autoplay, ook bij verminderde beweging', () => {
|
||||
vi.spyOn(window, 'matchMedia').mockImplementation(
|
||||
(query: string) =>
|
||||
({
|
||||
matches: query.includes('reduce'),
|
||||
media: query,
|
||||
onchange: null,
|
||||
addListener: () => {},
|
||||
removeListener: () => {},
|
||||
dispatchEvent: () => false,
|
||||
addEventListener: () => {},
|
||||
removeEventListener: () => {},
|
||||
}) as MediaQueryList,
|
||||
);
|
||||
seen.length = 0;
|
||||
const { container } = hydrate(<Probe />);
|
||||
expect(seen[0].autoplay).toBe(true);
|
||||
expect(container).toHaveTextContent('stil');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,6 +5,10 @@ import { hasChildren, mainNav } from '@/navigation';
|
||||
import RouterLink from '../RouterLink';
|
||||
import MobileNavGroup from './MobileNavGroup';
|
||||
|
||||
// Exact, like the submenu: no link counts as current on an unknown URL
|
||||
// (BR-404-05)
|
||||
const exactActive = { exact: true, includeSearch: false } as const;
|
||||
|
||||
type MobileNavProps = {
|
||||
id: string;
|
||||
open: boolean;
|
||||
@@ -93,6 +97,7 @@ export default function MobileNav({
|
||||
) : (
|
||||
<RouterLink
|
||||
to={item.to}
|
||||
activeOptions={exactActive}
|
||||
onClick={() =>
|
||||
dispatch({ type: 'linkChosen' })
|
||||
}
|
||||
|
||||
@@ -282,3 +282,44 @@ describe('NavigationBar current page', () => {
|
||||
expect(parent).not.toHaveAttribute('aria-current');
|
||||
});
|
||||
});
|
||||
|
||||
// The 404 page is prerendered for /404, so on an unknown URL no link may count
|
||||
// as current in the browser either, also not through the router's fuzzy
|
||||
// matching of a sub-path (BR-404-05)
|
||||
describe('NavigationBar and the current page', () => {
|
||||
const desktopLinks = () =>
|
||||
[
|
||||
...screen
|
||||
.getByRole('navigation', { name: 'Hoofdmenu' })
|
||||
.querySelectorAll('a'),
|
||||
].filter((link) => !panel()?.contains(link));
|
||||
const mobileLinks = () => [
|
||||
...document.getElementById('mobile-nav')!.querySelectorAll('a'),
|
||||
];
|
||||
const currentOf = (links: HTMLElement[]) =>
|
||||
links
|
||||
.filter((link) => link.getAttribute('aria-current') === 'page')
|
||||
.map((link) => link.textContent);
|
||||
|
||||
it.each(['/over-mij/x', '/portfolio/x', '/contact/x', '/onbekend'])(
|
||||
'marks no link as current on the unknown URL %s',
|
||||
async (path) => {
|
||||
await renderBar(path);
|
||||
expect(currentOf(desktopLinks())).toEqual([]);
|
||||
expect(currentOf(mobileLinks())).toEqual([]);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
['/over-mij', 'Over mij'],
|
||||
['/portfolio?shoot=gezin', 'Portfolio'],
|
||||
['/contact?pakket=gezin', 'Contact'],
|
||||
])(
|
||||
'marks the page itself on %s, also with a search',
|
||||
async (path, name) => {
|
||||
await renderBar(path);
|
||||
expect(currentOf(desktopLinks())).toEqual([name]);
|
||||
expect(currentOf(mobileLinks())).toEqual([name]);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -24,6 +24,10 @@ import logoDark from '../../assets/logo-dark.png';
|
||||
// Het item met een submenu: bepaalt of het mobiele menu open start in een sectie
|
||||
const parentItem = mainNav.find(hasChildren);
|
||||
|
||||
// Exact: on an unknown URL (the prerendered 404 page) no link may count as
|
||||
// current, while the router would match /over-mij/x to Over mij (BR-404-05)
|
||||
const exactActive = { exact: true, includeSearch: false } as const;
|
||||
|
||||
export default function NavigationBar() {
|
||||
// Eén reducer voor het mobiele menu, de groep en het desktop-submenu, zodat
|
||||
// ze elkaar niet tegenspreken
|
||||
@@ -161,7 +165,10 @@ export default function NavigationBar() {
|
||||
dispatch={dispatch}
|
||||
/>
|
||||
) : (
|
||||
<NavLink to={item.to}>
|
||||
<NavLink
|
||||
to={item.to}
|
||||
activeOptions={exactActive}
|
||||
>
|
||||
{item.label}
|
||||
</NavLink>
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { screen, waitFor } from '@testing-library/react';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { hydrateApp } from '@/test/hydrate';
|
||||
import { renderApp } from '@/test/renderApp';
|
||||
|
||||
// The 404 page is prerendered for /404 and served for every unknown URL, so
|
||||
// the first browser render must not depend on the real path (BR-404-04, 05)
|
||||
const homeLink = () => screen.queryByTestId('status-page-home-link');
|
||||
const sectionLink = () => screen.queryByTestId('status-page-section-link');
|
||||
|
||||
describe('NotFound while hydrating', () => {
|
||||
it('shows the section buttons only after hydrating under /soorten-fotoshoots/', async () => {
|
||||
const { container, errors } = await hydrateApp(
|
||||
'/404',
|
||||
'/soorten-fotoshoots/onbekend',
|
||||
);
|
||||
await waitFor(() => expect(sectionLink()).toBeInTheDocument());
|
||||
expect(sectionLink()).toHaveAttribute('href', '/soorten-fotoshoots');
|
||||
expect(homeLink()).toHaveAttribute('href', '/');
|
||||
expect(container).toHaveTextContent('Pagina niet gevonden');
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
|
||||
it('keeps one button on an unknown URL outside the section', async () => {
|
||||
const { container, errors } = await hydrateApp('/404', '/onbekend');
|
||||
expect(
|
||||
await screen.findByRole('link', { name: 'Terug naar home' }),
|
||||
).toBeInTheDocument();
|
||||
expect(sectionLink()).not.toBeInTheDocument();
|
||||
expect(container).toHaveTextContent('Pagina niet gevonden');
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('NotFound on a plain mount', () => {
|
||||
it('shows the section buttons at once under /soorten-fotoshoots/', async () => {
|
||||
await renderApp('/soorten-fotoshoots/onbekend');
|
||||
expect(sectionLink()).toBeInTheDocument();
|
||||
expect(homeLink()).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows one button at once elsewhere', async () => {
|
||||
await renderApp('/onbekend');
|
||||
expect(sectionLink()).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByRole('link', { name: 'Terug naar home' }),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useRouterState } from '@tanstack/react-router';
|
||||
import useHydrated from '@/hooks/useHydrated';
|
||||
import { isShootSectionPath } from '@/lib/isShootSectionPath';
|
||||
import LinkButton from '../LinkButton';
|
||||
import StatusPage from './StatusPage';
|
||||
@@ -9,6 +10,9 @@ import StatusPage from './StatusPage';
|
||||
// Onder /soorten-fotoshoots/ komt er een knop naar het overzicht bij
|
||||
// (FR-ST-14).
|
||||
export default function NotFound() {
|
||||
// De prerender is gemaakt voor /404; het echte pad telt pas na de
|
||||
// hydratatie, anders verschilt de eerste render van de HTML (BR-404-04)
|
||||
const hydrated = useHydrated();
|
||||
const pathname = useRouterState({
|
||||
select: (routerState) => routerState.location.pathname,
|
||||
});
|
||||
@@ -20,7 +24,7 @@ export default function NotFound() {
|
||||
<StatusPage
|
||||
title="Pagina niet gevonden"
|
||||
actions={
|
||||
isShootSectionPath(pathname) ? (
|
||||
hydrated && isShootSectionPath(pathname) ? (
|
||||
<>
|
||||
<LinkButton
|
||||
to="/soorten-fotoshoots"
|
||||
|
||||
@@ -5,6 +5,7 @@ import homeContent from '@/content/homeContent';
|
||||
import testimonials from '@/content/testimonials';
|
||||
import { axeResults } from '@/test/axe';
|
||||
import { FakeIntersectionObserver } from '@/test/fakeIntersectionObserver';
|
||||
import { serverHtml } from '@/test/hydrate';
|
||||
import { renderWithProviders } from '@/test/renderWithProviders';
|
||||
import { visibleTestimonials } from '@/lib/visibleTestimonials';
|
||||
import Testimonials from './Testimonials';
|
||||
@@ -201,3 +202,64 @@ describe('Testimonials', () => {
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// Every review is in the prerendered HTML for search engines; the copies
|
||||
// besides the longest one are hidden and inert (BR-LZY-02)
|
||||
describe('Testimonials in the prerendered HTML', () => {
|
||||
const shown = visibleTestimonials(testimonials);
|
||||
const page = <Testimonials content={content} testimonials={testimonials} />;
|
||||
|
||||
it('holds the text of every visible review', async () => {
|
||||
const doc = new DOMParser().parseFromString(
|
||||
await serverHtml(page),
|
||||
'text/html',
|
||||
);
|
||||
expect(shown.length).toBeGreaterThan(1);
|
||||
for (const testimonial of shown) {
|
||||
expect(
|
||||
doc.querySelector(
|
||||
`[data-testid="testimonial-${testimonial.id}"]`,
|
||||
)?.textContent,
|
||||
).toContain(testimonial.quote);
|
||||
}
|
||||
});
|
||||
|
||||
it('puts the longest in the flow and hides the others from readers', async () => {
|
||||
const doc = new DOMParser().parseFromString(
|
||||
await serverHtml(page),
|
||||
'text/html',
|
||||
);
|
||||
const longest = shown.reduce((a, b) =>
|
||||
b.quote.length > a.quote.length ? b : a,
|
||||
);
|
||||
for (const testimonial of shown) {
|
||||
const copy = doc.querySelector(
|
||||
`[data-testid="testimonial-${testimonial.id}"]`,
|
||||
)!;
|
||||
const hidden = copy.closest('[aria-hidden="true"][inert]');
|
||||
if (testimonial === longest) {
|
||||
expect(hidden).toBeNull();
|
||||
} else {
|
||||
expect(hidden).not.toBeNull();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('exposes one review to readers while the carousel loads, without axe violations', async () => {
|
||||
const { container } = await renderWithProviders(page);
|
||||
const quotes = [...container.querySelectorAll('blockquote')];
|
||||
expect(quotes).toHaveLength(shown.length);
|
||||
expect(
|
||||
quotes.filter((quote) => !quote.closest('[aria-hidden="true"]')),
|
||||
).toHaveLength(1);
|
||||
expect(await axeResults(container)).toHaveNoViolations();
|
||||
});
|
||||
|
||||
it('does not add copies for a single review', async () => {
|
||||
const html = await serverHtml(
|
||||
<Testimonials content={content} testimonials={[shown[0]]} />,
|
||||
);
|
||||
expect(html.match(/data-testid="testimonial-/g)).toHaveLength(1);
|
||||
expect(html).not.toContain('inert');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { lazy, Suspense } from 'react';
|
||||
import { Box } from '@chakra-ui/react';
|
||||
import { Box, VisuallyHidden } from '@chakra-ui/react';
|
||||
import { DEFERRED_LOAD_MARGIN } from '@/components/DeferredImage/DeferredImage';
|
||||
import PageSection from '@/components/PageSection/PageSection';
|
||||
import Reveal from '@/components/Reveal/Reveal';
|
||||
@@ -71,7 +71,10 @@ export default function Testimonials({
|
||||
// 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.
|
||||
// #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,
|
||||
}: {
|
||||
@@ -85,6 +88,15 @@ function CarouselPlaceholder({
|
||||
<Box ps={{ base: 0, sm: '1.5rem' }} pb={{ base: 0, sm: '1.5rem' }}>
|
||||
<TestimonialSlide testimonial={longest} />
|
||||
</Box>
|
||||
{testimonials
|
||||
.filter((testimonial) => testimonial !== longest)
|
||||
.map((testimonial) => (
|
||||
<VisuallyHidden key={testimonial.id} asChild>
|
||||
<Box aria-hidden="true" inert>
|
||||
<TestimonialSlide testimonial={testimonial} />
|
||||
</Box>
|
||||
</VisuallyHidden>
|
||||
))}
|
||||
{/* The control bar: 48px buttons below the same margin */}
|
||||
<Box mt="clamp(2.5rem, 5vw, 4rem)" h="48px" />
|
||||
</Box>
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { renderHook } from '@testing-library/react';
|
||||
import fc from 'fast-check';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { emailAddress } from '@/lib/emailAddress';
|
||||
import { anyEmail } from '@/test/arbitraries';
|
||||
import { hydrate, renderToString } from '@/test/hydrate';
|
||||
import useEmailAddress from './useEmailAddress';
|
||||
|
||||
const seen: { available: boolean; address: string | null }[] = [];
|
||||
|
||||
function Probe({ user, domain }: { user: string; domain: string }) {
|
||||
const result = useEmailAddress({ user, domain });
|
||||
seen.push(result);
|
||||
return <p>{result.address ?? (result.available ? 'pending' : 'absent')}</p>;
|
||||
}
|
||||
|
||||
const info = { user: 'info', domain: 'andreaslop.nl' };
|
||||
|
||||
describe('useEmailAddress', () => {
|
||||
it('is pending in the server render: available, without the address', () => {
|
||||
expect(renderToString(<Probe {...info} />)).toBe('<p>pending</p>');
|
||||
});
|
||||
|
||||
it('is absent in the server render for invalid parts', () => {
|
||||
expect(renderToString(<Probe user="" domain="andreaslop.nl" />)).toBe(
|
||||
'<p>absent</p>',
|
||||
);
|
||||
});
|
||||
|
||||
it('assembles the address only after the hydrating render', () => {
|
||||
seen.length = 0;
|
||||
const { container, errors } = hydrate(<Probe {...info} />);
|
||||
expect(seen[0]).toEqual({ available: true, address: null });
|
||||
expect(seen.at(-1)).toEqual({
|
||||
available: true,
|
||||
address: 'info@andreaslop.nl',
|
||||
});
|
||||
expect(container).toHaveTextContent('info@andreaslop.nl');
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
|
||||
it('gives the address at once for a component that mounts later', () => {
|
||||
const { result } = renderHook(() => useEmailAddress(info));
|
||||
expect(result.current).toEqual({
|
||||
available: true,
|
||||
address: 'info@andreaslop.nl',
|
||||
});
|
||||
});
|
||||
|
||||
it('gives neither for invalid parts', () => {
|
||||
const { result } = renderHook(() =>
|
||||
useEmailAddress({ user: 'info', domain: 'nodot' }),
|
||||
);
|
||||
expect(result.current).toEqual({ available: false, address: null });
|
||||
});
|
||||
|
||||
it('agrees with emailAddress once hydrated (oracle)', () => {
|
||||
fc.assert(
|
||||
fc.property(anyEmail, (parts) => {
|
||||
const { result, unmount } = renderHook(() =>
|
||||
useEmailAddress(parts),
|
||||
);
|
||||
const expected = emailAddress(parts);
|
||||
expect(result.current).toEqual({
|
||||
available: expected !== null,
|
||||
address: expected,
|
||||
});
|
||||
unmount();
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { EmailAddress } from '@/content/types';
|
||||
import { emailAddress, isEmailAddressValid } from '@/lib/emailAddress';
|
||||
import useHydrated from './useHydrated';
|
||||
|
||||
// `available` is the same on the server and in the browser, so the layout can
|
||||
// reserve room for the address. `address` is assembled only after hydration,
|
||||
// which keeps it out of the prerendered HTML (BR-MAIL-01).
|
||||
export default function useEmailAddress(email: EmailAddress): {
|
||||
available: boolean;
|
||||
address: string | null;
|
||||
} {
|
||||
const hydrated = useHydrated();
|
||||
const available = isEmailAddressValid(email);
|
||||
return {
|
||||
available,
|
||||
address: hydrated && available ? emailAddress(email) : null,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { render } from '@testing-library/react';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { hydrate, renderToString } from '@/test/hydrate';
|
||||
import useHydrated from './useHydrated';
|
||||
|
||||
// Records the value of every render, to see the hydrating one
|
||||
const seen: boolean[] = [];
|
||||
|
||||
function Probe() {
|
||||
const hydrated = useHydrated();
|
||||
seen.push(hydrated);
|
||||
return <p>{String(hydrated)}</p>;
|
||||
}
|
||||
|
||||
describe('useHydrated', () => {
|
||||
it('is false in the server render', () => {
|
||||
expect(renderToString(<Probe />)).toBe('<p>false</p>');
|
||||
});
|
||||
|
||||
it('is false in the hydrating render and true right after', () => {
|
||||
seen.length = 0;
|
||||
const { container, errors } = hydrate(<Probe />);
|
||||
expect(seen[0]).toBe(false);
|
||||
expect(seen.at(-1)).toBe(true);
|
||||
expect(container).toHaveTextContent('true');
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
|
||||
it('is true at once for a component that mounts later', () => {
|
||||
seen.length = 0;
|
||||
const { container } = render(<Probe />);
|
||||
expect(seen).toEqual([true]);
|
||||
expect(container).toHaveTextContent('true');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,82 @@
|
||||
import { act, render, screen } from '@testing-library/react';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { FakeIntersectionObserver as FakeObserver } from '@/test/fakeIntersectionObserver';
|
||||
import { hydrate, renderToString } from '@/test/hydrate';
|
||||
import useInView from './useInView';
|
||||
|
||||
const seen: boolean[] = [];
|
||||
|
||||
function Probe({ skip }: { skip?: boolean }) {
|
||||
const { ref, inView } = useInView<HTMLDivElement>({ skip });
|
||||
seen.push(inView);
|
||||
return (
|
||||
<div ref={ref} data-testid="probe">
|
||||
{inView ? 'in view' : 'not in view'}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
FakeObserver.reset();
|
||||
});
|
||||
|
||||
describe('useInView without IntersectionObserver', () => {
|
||||
it('is not in view in the server render', () => {
|
||||
expect(renderToString(<Probe />)).toContain('not in view');
|
||||
});
|
||||
|
||||
it('is in view only after the hydrating render', () => {
|
||||
seen.length = 0;
|
||||
const { container, errors } = hydrate(<Probe />);
|
||||
expect(seen[0]).toBe(false);
|
||||
expect(seen.at(-1)).toBe(true);
|
||||
expect(container).toHaveTextContent(/^in view$/);
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
|
||||
it('is in view at once for a component that mounts later', () => {
|
||||
seen.length = 0;
|
||||
render(<Probe />);
|
||||
expect(seen).toEqual([true]);
|
||||
});
|
||||
|
||||
it('respects skip in every render', () => {
|
||||
expect(renderToString(<Probe skip />)).not.toContain('not in view');
|
||||
seen.length = 0;
|
||||
const { errors } = hydrate(<Probe skip />);
|
||||
expect(seen.every(Boolean)).toBe(true);
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('useInView with IntersectionObserver', () => {
|
||||
it('is not in view in the server render and observes only after hydrating', () => {
|
||||
vi.stubGlobal('IntersectionObserver', FakeObserver);
|
||||
expect(renderToString(<Probe />)).toContain('not in view');
|
||||
expect(FakeObserver.instances).toHaveLength(0);
|
||||
|
||||
const { container, errors } = hydrate(<Probe />);
|
||||
expect(container).toHaveTextContent('not in view');
|
||||
expect(FakeObserver.instances).toHaveLength(1);
|
||||
expect(errors).toEqual([]);
|
||||
|
||||
act(() => FakeObserver.instances[0].trigger(true));
|
||||
expect(container).toHaveTextContent(/^in view$/);
|
||||
});
|
||||
|
||||
it('is not in view on a plain mount until the element intersects', () => {
|
||||
vi.stubGlobal('IntersectionObserver', FakeObserver);
|
||||
render(<Probe />);
|
||||
expect(screen.getByTestId('probe')).toHaveTextContent('not in view');
|
||||
act(() => FakeObserver.instances[0].trigger(true));
|
||||
expect(screen.getByTestId('probe')).toHaveTextContent(/^in view$/);
|
||||
});
|
||||
|
||||
it('does not observe when skip is set', () => {
|
||||
vi.stubGlobal('IntersectionObserver', FakeObserver);
|
||||
render(<Probe skip />);
|
||||
expect(screen.getByTestId('probe')).toHaveTextContent(/^in view$/);
|
||||
expect(FakeObserver.instances).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -29,6 +29,9 @@ export default function useInView<T extends Element>({
|
||||
useEffect(() => {
|
||||
const element = ref.current;
|
||||
if (!element || skip || unsupported || intersected) return;
|
||||
// The effect of the hydrating render still sees the server's
|
||||
// `unsupported` (false), so check the browser itself as well
|
||||
if (typeof IntersectionObserver === 'undefined') return;
|
||||
|
||||
const observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
|
||||
@@ -1,7 +1,16 @@
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import { act, render, renderHook } from '@testing-library/react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { hydrate, renderToString } from '@/test/hydrate';
|
||||
import usePageLoaded from './usePageLoaded';
|
||||
|
||||
const seen: boolean[] = [];
|
||||
|
||||
function Probe() {
|
||||
const loaded = usePageLoaded();
|
||||
seen.push(loaded);
|
||||
return <p>{String(loaded)}</p>;
|
||||
}
|
||||
|
||||
describe('usePageLoaded', () => {
|
||||
it('is true when the page had already loaded', () => {
|
||||
const { result } = renderHook(() => usePageLoaded());
|
||||
@@ -22,4 +31,38 @@ describe('usePageLoaded', () => {
|
||||
});
|
||||
expect(result.current).toBe(true);
|
||||
});
|
||||
|
||||
it('is false in the server render, even when the page has loaded', () => {
|
||||
expect(renderToString(<Probe />)).toBe('<p>false</p>');
|
||||
});
|
||||
|
||||
it('is false in the hydrating render and true right after on a loaded page', () => {
|
||||
seen.length = 0;
|
||||
const { container, errors } = hydrate(<Probe />);
|
||||
expect(seen[0]).toBe(false);
|
||||
expect(seen.at(-1)).toBe(true);
|
||||
expect(container).toHaveTextContent('true');
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
|
||||
it('stays false after hydrating until the load event', () => {
|
||||
const readyState = vi
|
||||
.spyOn(document, 'readyState', 'get')
|
||||
.mockReturnValue('interactive');
|
||||
const { container, errors } = hydrate(<Probe />);
|
||||
expect(container).toHaveTextContent('false');
|
||||
|
||||
act(() => {
|
||||
readyState.mockReturnValue('complete');
|
||||
window.dispatchEvent(new Event('load'));
|
||||
});
|
||||
expect(container).toHaveTextContent('true');
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
|
||||
it('is true at once for a component that mounts on a loaded page', () => {
|
||||
seen.length = 0;
|
||||
render(<Probe />);
|
||||
expect(seen).toEqual([true]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,6 +2,7 @@ import { act, render, screen } from '@testing-library/react';
|
||||
import { ChakraProvider } from '@chakra-ui/react';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { FakeIntersectionObserver as FakeObserver } from '@/test/fakeIntersectionObserver';
|
||||
import { hydrate, renderToString } from '@/test/hydrate';
|
||||
import system from '../theme';
|
||||
import useReveal from './useReveal';
|
||||
|
||||
@@ -88,3 +89,35 @@ describe('useReveal', () => {
|
||||
expect(FakeObserver.instances[0].disconnected).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('useReveal while hydrating', () => {
|
||||
const page = (
|
||||
<ChakraProvider value={system}>
|
||||
<Probe />
|
||||
</ChakraProvider>
|
||||
);
|
||||
|
||||
it('is hidden in the server render', () => {
|
||||
vi.stubGlobal('IntersectionObserver', FakeObserver);
|
||||
expect(renderToString(page)).toContain('hidden');
|
||||
});
|
||||
|
||||
it('assumes no reduced motion in the hydrating render, then follows the preference', () => {
|
||||
vi.stubGlobal('IntersectionObserver', FakeObserver);
|
||||
mockReducedMotion();
|
||||
const markup = renderToString(page);
|
||||
const { container, errors } = hydrate(page, markup);
|
||||
expect(container).toHaveTextContent('visible');
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
|
||||
it('stays hidden after hydrating until the element scrolls into view', () => {
|
||||
vi.stubGlobal('IntersectionObserver', FakeObserver);
|
||||
const { container, errors } = hydrate(page);
|
||||
expect(container).toHaveTextContent('hidden');
|
||||
expect(errors).toEqual([]);
|
||||
|
||||
act(() => FakeObserver.instances.at(-1)!.trigger(true));
|
||||
expect(container).toHaveTextContent('visible');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,43 +2,52 @@ import fc from 'fast-check';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import siteContent from '../content/siteContent';
|
||||
import socialPlatforms from '../content/socialPlatforms';
|
||||
import { anyEmail, socialLink } from '../test/arbitraries';
|
||||
import { contactChannels } from './contactChannels';
|
||||
import { anyEmail, socialLink, validEmail } from '../test/arbitraries';
|
||||
import { type ContactChannel, contactChannels } from './contactChannels';
|
||||
import { emailAddress } from './emailAddress';
|
||||
import { visibleSocials } from './visibleSocials';
|
||||
|
||||
const socialLinks = fc.array(socialLink, { maxLength: 5 });
|
||||
|
||||
// With the address assembled there is no placeholder channel, so the narrowed
|
||||
// type lets the existing tests read href, label and external
|
||||
const assembled = (
|
||||
email: Parameters<typeof contactChannels>[0],
|
||||
socials: Parameters<typeof contactChannels>[1],
|
||||
) =>
|
||||
contactChannels(email, socials, true) as Exclude<
|
||||
ContactChannel,
|
||||
{ kind: 'email-pending' }
|
||||
>[];
|
||||
|
||||
describe('contactChannels', () => {
|
||||
it('lists e-mail, Instagram and Facebook for the site content', () => {
|
||||
expect(contactChannels(siteContent.email, siteContent.socials)).toEqual(
|
||||
[
|
||||
{
|
||||
kind: 'email',
|
||||
href: 'mailto:info@andreaslop.nl?subject=Vraag%20via%20andreaslop.nl',
|
||||
label: 'info@andreaslop.nl',
|
||||
external: false,
|
||||
},
|
||||
{
|
||||
kind: 'social',
|
||||
platform: 'instagram',
|
||||
href: 'https://www.instagram.com/andreaslopfotografie/',
|
||||
label: '@andreaslopfotografie',
|
||||
external: true,
|
||||
},
|
||||
{
|
||||
kind: 'social',
|
||||
platform: 'facebook',
|
||||
href: 'https://www.facebook.com/andreaslopfotografie/',
|
||||
label: 'Andrea Slop Fotografie',
|
||||
external: true,
|
||||
},
|
||||
],
|
||||
);
|
||||
expect(assembled(siteContent.email, siteContent.socials)).toEqual([
|
||||
{
|
||||
kind: 'email',
|
||||
href: 'mailto:info@andreaslop.nl?subject=Vraag%20via%20andreaslop.nl',
|
||||
label: 'info@andreaslop.nl',
|
||||
external: false,
|
||||
},
|
||||
{
|
||||
kind: 'social',
|
||||
platform: 'instagram',
|
||||
href: 'https://www.instagram.com/andreaslopfotografie/',
|
||||
label: '@andreaslopfotografie',
|
||||
external: true,
|
||||
},
|
||||
{
|
||||
kind: 'social',
|
||||
platform: 'facebook',
|
||||
href: 'https://www.facebook.com/andreaslopfotografie/',
|
||||
label: 'Andrea Slop Fotografie',
|
||||
external: true,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('leaves out an invalid e-mail address and invalid links', () => {
|
||||
const channels = contactChannels({ user: 'info', domain: 'nodot' }, [
|
||||
const channels = assembled({ user: 'info', domain: 'nodot' }, [
|
||||
{ platform: 'facebook', href: 'javascript:alert(1)' },
|
||||
{ platform: 'instagram', href: 'https://instagram.com/x' },
|
||||
]);
|
||||
@@ -46,7 +55,7 @@ describe('contactChannels', () => {
|
||||
});
|
||||
|
||||
it('falls back to the platform name without a usable label', () => {
|
||||
const channels = contactChannels({ user: '', domain: '' }, [
|
||||
const channels = assembled({ user: '', domain: '' }, [
|
||||
{ platform: 'instagram', href: 'https://instagram.com/x' },
|
||||
{
|
||||
platform: 'facebook',
|
||||
@@ -61,13 +70,13 @@ describe('contactChannels', () => {
|
||||
});
|
||||
|
||||
it('is empty when nothing is valid', () => {
|
||||
expect(contactChannels({ user: '', domain: '' }, [])).toEqual([]);
|
||||
expect(assembled({ user: '', domain: '' }, [])).toEqual([]);
|
||||
});
|
||||
|
||||
it('puts the e-mail channel first exactly when the address is valid (invariant)', () => {
|
||||
fc.assert(
|
||||
fc.property(anyEmail, socialLinks, (email, socials) => {
|
||||
const channels = contactChannels(email, socials);
|
||||
const channels = assembled(email, socials);
|
||||
const valid = emailAddress(email) !== null;
|
||||
expect(channels[0]?.kind === 'email').toBe(valid);
|
||||
expect(
|
||||
@@ -80,16 +89,15 @@ describe('contactChannels', () => {
|
||||
it('shows exactly the visible social links, in order (oracle)', () => {
|
||||
fc.assert(
|
||||
fc.property(anyEmail, socialLinks, (email, socials) => {
|
||||
const shown = contactChannels(email, socials).flatMap(
|
||||
(channel) =>
|
||||
channel.kind === 'social'
|
||||
? [
|
||||
{
|
||||
platform: channel.platform,
|
||||
href: channel.href,
|
||||
},
|
||||
]
|
||||
: [],
|
||||
const shown = assembled(email, socials).flatMap((channel) =>
|
||||
channel.kind === 'social'
|
||||
? [
|
||||
{
|
||||
platform: channel.platform,
|
||||
href: channel.href,
|
||||
},
|
||||
]
|
||||
: [],
|
||||
);
|
||||
expect(shown).toEqual(
|
||||
visibleSocials(socials).map(({ platform, href }) => ({
|
||||
@@ -104,10 +112,7 @@ describe('contactChannels', () => {
|
||||
it('labels a social link with its trimmed label, or else the platform name (invariant)', () => {
|
||||
fc.assert(
|
||||
fc.property(socialLinks, (socials) => {
|
||||
const channels = contactChannels(
|
||||
{ user: '', domain: '' },
|
||||
socials,
|
||||
);
|
||||
const channels = assembled({ user: '', domain: '' }, socials);
|
||||
visibleSocials(socials).forEach((link, index) => {
|
||||
const expected =
|
||||
link.label?.trim() ||
|
||||
@@ -122,7 +127,7 @@ describe('contactChannels', () => {
|
||||
it('only links to mailto: or https: (invariant)', () => {
|
||||
fc.assert(
|
||||
fc.property(anyEmail, socialLinks, (email, socials) => {
|
||||
for (const channel of contactChannels(email, socials)) {
|
||||
for (const channel of assembled(email, socials)) {
|
||||
const scheme = new URL(channel.href).protocol;
|
||||
expect(
|
||||
channel.kind === 'email' ? 'mailto:' : 'https:',
|
||||
@@ -135,7 +140,7 @@ describe('contactChannels', () => {
|
||||
it('opens exactly the social channels in a new tab (invariant)', () => {
|
||||
fc.assert(
|
||||
fc.property(anyEmail, socialLinks, (email, socials) => {
|
||||
for (const channel of contactChannels(email, socials)) {
|
||||
for (const channel of assembled(email, socials)) {
|
||||
expect(channel.external).toBe(channel.kind === 'social');
|
||||
}
|
||||
}),
|
||||
@@ -145,9 +150,56 @@ describe('contactChannels', () => {
|
||||
it('has at most one channel per link plus the e-mail (invariant)', () => {
|
||||
fc.assert(
|
||||
fc.property(anyEmail, socialLinks, (email, socials) => {
|
||||
expect(
|
||||
contactChannels(email, socials).length,
|
||||
).toBeLessThanOrEqual(1 + socials.length);
|
||||
expect(assembled(email, socials).length).toBeLessThanOrEqual(
|
||||
1 + socials.length,
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('contactChannels before the address may be assembled', () => {
|
||||
it('puts a placeholder without href and label first for valid parts', () => {
|
||||
expect(
|
||||
contactChannels(siteContent.email, siteContent.socials, false)[0],
|
||||
).toEqual({ kind: 'email-pending' });
|
||||
});
|
||||
|
||||
it('keeps the social channels the same as when assembling', () => {
|
||||
const socials = (assemble: boolean) =>
|
||||
contactChannels(
|
||||
siteContent.email,
|
||||
siteContent.socials,
|
||||
assemble,
|
||||
).filter((channel) => channel.kind === 'social');
|
||||
expect(socials(false)).toEqual(socials(true));
|
||||
});
|
||||
|
||||
it('gives no placeholder for invalid parts', () => {
|
||||
expect(
|
||||
contactChannels({ user: 'info', domain: 'nodot' }, [], false),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it('never contains the assembled address (invariant)', () => {
|
||||
fc.assert(
|
||||
fc.property(validEmail, socialLinks, (email, socials) => {
|
||||
const address = emailAddress(email)!;
|
||||
const json = JSON.stringify(
|
||||
contactChannels(email, socials, false),
|
||||
);
|
||||
expect(json).not.toContain(address);
|
||||
expect(json).not.toContain('mailto:');
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('has as many channels as when assembling (invariant)', () => {
|
||||
fc.assert(
|
||||
fc.property(anyEmail, socialLinks, (email, socials) => {
|
||||
expect(contactChannels(email, socials, false)).toHaveLength(
|
||||
contactChannels(email, socials, true).length,
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -2,13 +2,16 @@ import socialPlatforms, {
|
||||
type SocialPlatform,
|
||||
} from '../content/socialPlatforms.ts';
|
||||
import type { EmailAddress, SocialLink } from '../content/types.ts';
|
||||
import { emailAddress } from './emailAddress.ts';
|
||||
import { emailAddress, isEmailAddressValid } from './emailAddress.ts';
|
||||
import { mailSubject, mailtoLink } from './mailLink.ts';
|
||||
import { visibleSocials } from './visibleSocials.ts';
|
||||
|
||||
// One way to reach Andrea, as the contact card shows it
|
||||
export type ContactChannel =
|
||||
| { kind: 'email'; href: string; label: string; external: false }
|
||||
// Stands in for the e-mail item until the address may be assembled
|
||||
// (BR-MAIL-07): no href and no label, so nothing readable or clickable
|
||||
| { kind: 'email-pending' }
|
||||
| {
|
||||
kind: 'social';
|
||||
platform: SocialPlatform;
|
||||
@@ -21,22 +24,28 @@ export type ContactChannel =
|
||||
// The channels of the contact card (BR-CD-01..05): the e-mail address first
|
||||
// when it is valid, then the valid social links in content order, each with
|
||||
// its label or else the platform name. Only mailto: and https: links come
|
||||
// out, because both helpers already drop everything else.
|
||||
// out, because both helpers already drop everything else. Without `assemble`
|
||||
// (prerender and hydrating render) a valid address gives an `email-pending`
|
||||
// placeholder, so the address stays out of the HTML (BR-MAIL-01).
|
||||
export function contactChannels(
|
||||
email: EmailAddress,
|
||||
socials: readonly SocialLink[],
|
||||
assemble: boolean,
|
||||
): ContactChannel[] {
|
||||
const address = emailAddress(email);
|
||||
const mail: ContactChannel[] = address
|
||||
? [
|
||||
{
|
||||
kind: 'email',
|
||||
href: mailtoLink(address, mailSubject()),
|
||||
label: address,
|
||||
external: false,
|
||||
},
|
||||
]
|
||||
: [];
|
||||
const mail: ContactChannel[] = [];
|
||||
if (isEmailAddressValid(email)) {
|
||||
if (assemble) {
|
||||
const address = emailAddress(email)!;
|
||||
mail.push({
|
||||
kind: 'email',
|
||||
href: mailtoLink(address, mailSubject()),
|
||||
label: address,
|
||||
external: false,
|
||||
});
|
||||
} else {
|
||||
mail.push({ kind: 'email-pending' });
|
||||
}
|
||||
}
|
||||
const social = visibleSocials(socials).map((link): ContactChannel => ({
|
||||
kind: 'social',
|
||||
platform: link.platform,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import fc from 'fast-check';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { anyEmail, validEmail } from '../test/arbitraries';
|
||||
import { emailAddress } from './emailAddress';
|
||||
import { emailAddress, isEmailAddressValid } from './emailAddress';
|
||||
|
||||
describe('emailAddress', () => {
|
||||
it('voegt geldige delen samen', () => {
|
||||
@@ -46,3 +46,33 @@ describe('emailAddress', () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isEmailAddressValid', () => {
|
||||
it('is waar voor geldige delen', () => {
|
||||
expect(
|
||||
isEmailAddressValid({ user: 'info', domain: 'andreaslop.nl' }),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('is onwaar bij ongeldige delen', () => {
|
||||
for (const parts of [
|
||||
{ user: '', domain: 'andreaslop.nl' },
|
||||
{ user: 'info', domain: '' },
|
||||
{ user: 'in fo', domain: 'andreaslop.nl' },
|
||||
{ user: 'info', domain: 'andreaslop' },
|
||||
{ user: 'info', domain: 'andrea@slop.nl' },
|
||||
]) {
|
||||
expect(isEmailAddressValid(parts)).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it('is precies dan waar als emailAddress een adres geeft (oracle)', () => {
|
||||
fc.assert(
|
||||
fc.property(anyEmail, (parts) => {
|
||||
expect(isEmailAddressValid(parts)).toBe(
|
||||
emailAddress(parts) !== null,
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,11 +2,14 @@ import type { EmailAddress } from '../content/types';
|
||||
|
||||
const invalidPart = (part: string) => part === '' || /[\s@]/.test(part);
|
||||
|
||||
// Zegt of de delen een geldig adres geven, zonder het samen te voegen. Zo
|
||||
// weten de pagina's al voor de hydratatie of er een adres is (BR-MAIL-08).
|
||||
export function isEmailAddressValid({ user, domain }: EmailAddress): boolean {
|
||||
return !invalidPart(user) && !invalidPart(domain) && domain.includes('.');
|
||||
}
|
||||
|
||||
// Voegt het e-mailadres pas in de browser samen (BR-EMAIL-01). Geeft null bij
|
||||
// ongeldige delen, zodat de footer de Contact-kolom kan weglaten (BR-EMAIL-02).
|
||||
export function emailAddress({ user, domain }: EmailAddress): string | null {
|
||||
if (invalidPart(user) || invalidPart(domain) || !domain.includes('.')) {
|
||||
return null;
|
||||
}
|
||||
return `${user}@${domain}`;
|
||||
export function emailAddress(parts: EmailAddress): string | null {
|
||||
return isEmailAddressValid(parts) ? `${parts.user}@${parts.domain}` : null;
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import contactContent from '../content/contactContent';
|
||||
import packages from '../content/packages';
|
||||
import siteContent from '../content/siteContent';
|
||||
import { withReplyTime } from '../lib/withReplyTime';
|
||||
import useHydrated from '../hooks/useHydrated';
|
||||
import { contactPage, pageHead, structuredDataScript } from '../seo';
|
||||
|
||||
// ?pakket= from a link elsewhere on the site. Only text is kept; the panel
|
||||
@@ -34,7 +35,10 @@ export const Route = createFileRoute('/contact')({
|
||||
// form (BR-CP-01..04). The card is in the page twice, one per layout, so the
|
||||
// reading order always matches what is shown.
|
||||
function Contact() {
|
||||
const { pakket } = Route.useSearch();
|
||||
const { pakket: searched } = Route.useSearch();
|
||||
// The search only counts after hydration, so the prerendered HTML and the
|
||||
// first browser render agree (BR-HYD-10)
|
||||
const pakket = useHydrated() ? searched : undefined;
|
||||
const navigate = useNavigate();
|
||||
const { head, formTitle, detailsTitle, image, portrait } = contactContent;
|
||||
const { email, socials, contactForm } = siteContent;
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { screen, waitFor, within } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { FakeIntersectionObserver } from '@/test/fakeIntersectionObserver';
|
||||
import { hydrateApp } from '@/test/hydrate';
|
||||
|
||||
// A direct load of a page with a search: the HTML was prerendered without it,
|
||||
// so the first browser render must ignore it and the page applies it right
|
||||
// after hydrating (BR-HYD-10 to 12). React reports a mismatch through
|
||||
// onRecoverableError, which hydrate() collects.
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('IntersectionObserver', FakeIntersectionObserver);
|
||||
Element.prototype.scrollTo = () => {};
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
FakeIntersectionObserver.reset();
|
||||
// @ts-expect-error -- jsdom has no Element.scrollTo of its own
|
||||
delete Element.prototype.scrollTo;
|
||||
});
|
||||
|
||||
describe('portfolio ?shoot= on a direct load', () => {
|
||||
it('hydrates without a mismatch and then applies the filter', async () => {
|
||||
const { errors } = await hydrateApp(
|
||||
'/portfolio',
|
||||
'/portfolio?shoot=gezin',
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.getByRole('button', { name: 'Gezin', pressed: true }),
|
||||
).toBeInTheDocument(),
|
||||
);
|
||||
expect(
|
||||
within(screen.getByTestId('portfolio-grid')).getAllByRole('link'),
|
||||
).toHaveLength(2);
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
|
||||
it('hydrates a plain /portfolio with the whole list', async () => {
|
||||
const { errors } = await hydrateApp('/portfolio', '/portfolio');
|
||||
expect(
|
||||
await screen.findByRole('button', { name: 'Alles', pressed: true }),
|
||||
).toBeInTheDocument();
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('contact ?pakket= on a direct load', () => {
|
||||
it('hydrates without a mismatch and then preselects the package', async () => {
|
||||
const { errors } = await hydrateApp(
|
||||
'/contact',
|
||||
'/contact?pakket=newborn',
|
||||
);
|
||||
expect(
|
||||
await screen.findByTestId('contact-form-shoot', undefined, {
|
||||
timeout: 10_000,
|
||||
}),
|
||||
).toHaveValue('newborn');
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('homepage ?pakket= on a direct load', () => {
|
||||
it('hydrates without a mismatch and then preselects the package', async () => {
|
||||
const { errors } = await hydrateApp('/', '/?pakket=newborn');
|
||||
expect(
|
||||
await screen.findByTestId('contact-form-shoot', undefined, {
|
||||
timeout: 10_000,
|
||||
}),
|
||||
).toHaveValue('newborn');
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -13,6 +13,7 @@ import packages from '../content/packages';
|
||||
import testimonials from '../content/testimonials';
|
||||
import siteContent from '../content/siteContent';
|
||||
import { visibleSocials } from '../lib/visibleSocials';
|
||||
import useHydrated from '../hooks/useHydrated';
|
||||
import { pageHead } from '../seo';
|
||||
|
||||
// ?pakket= from a "Boek" link on a price card. Only text is kept; whether it
|
||||
@@ -28,7 +29,10 @@ export const Route = createFileRoute('/')({
|
||||
|
||||
// The homepage: the hero, then the sections in the order of LAYOUT.md
|
||||
function Index() {
|
||||
const { pakket } = Route.useSearch();
|
||||
const { pakket: searched } = Route.useSearch();
|
||||
// The search only counts after hydration, so the prerendered HTML and the
|
||||
// first browser render agree (BR-HYD-10)
|
||||
const pakket = useHydrated() ? searched : undefined;
|
||||
// Without a valid https link the tiles would lead nowhere: no section
|
||||
const instagram = visibleSocials(siteContent.socials).find(
|
||||
(social) => social.platform === 'instagram',
|
||||
|
||||
@@ -9,6 +9,7 @@ import siteContent from '../content/siteContent';
|
||||
import type { ShootTypeId } from '../content/types';
|
||||
import { isShootTypeId } from '../lib/portfolioFilters';
|
||||
import { visibleSocials } from '../lib/visibleSocials';
|
||||
import useHydrated from '../hooks/useHydrated';
|
||||
import { galleryImages, pageHead, structuredDataScript, webPage } from '../seo';
|
||||
|
||||
// ?shoot= from a filter or a "Bekijk meer …foto's" link: only a known shoot
|
||||
@@ -42,7 +43,10 @@ export const Route = createFileRoute('/portfolio')({
|
||||
// The portfolio (LAYOUT.md: Intro → Portfolio → Instagram): the photos with
|
||||
// filters and lightbox, then the same Instagram block as on the homepage
|
||||
function Portfolio() {
|
||||
const { shoot } = Route.useSearch();
|
||||
const { shoot: searched } = Route.useSearch();
|
||||
// The filter only applies after hydration, so the prerendered HTML and the
|
||||
// first browser render agree (BR-HYD-10)
|
||||
const shoot = useHydrated() ? searched : undefined;
|
||||
const navigate = useNavigate({ from: Route.fullPath });
|
||||
const { intro, photos } = portfolioContent;
|
||||
// Without a valid https link the tiles would lead nowhere: no section
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
import type { ReactElement, ReactNode } from 'react';
|
||||
import { ChakraProvider } from '@chakra-ui/react';
|
||||
import {
|
||||
createMemoryHistory,
|
||||
createRoute,
|
||||
createRootRoute,
|
||||
createRouter,
|
||||
HeadContent,
|
||||
RouterContextProvider,
|
||||
RouterProvider,
|
||||
rootRouteId,
|
||||
} from '@tanstack/react-router';
|
||||
import { act } from '@testing-library/react';
|
||||
import { hydrateRoot } from 'react-dom/client';
|
||||
import { renderToString } from 'react-dom/server';
|
||||
import { afterEach } from 'vitest';
|
||||
import { routerOptions } from '../router';
|
||||
import system from '../theme';
|
||||
|
||||
// Roots still mounted at the end of a test: Testing Library does not know them
|
||||
const mounted = new Set<() => void>();
|
||||
afterEach(() => {
|
||||
for (const unmount of [...mounted]) unmount();
|
||||
});
|
||||
|
||||
// Plays what the browser does with a prerendered page: the server markup goes
|
||||
// into a container and React hydrates it. `errors` collects what React
|
||||
// reports as a mismatch (it recovers by client rendering and calls
|
||||
// onRecoverableError), so tests can state that there was none (BR-HYD-20).
|
||||
// The first render of the hydrating pass uses the server snapshots; the
|
||||
// effects and store updates that follow run inside act.
|
||||
export function hydrate(ui: ReactElement, markup = renderToString(ui)) {
|
||||
const container = document.createElement('div');
|
||||
container.innerHTML = markup;
|
||||
document.body.append(container);
|
||||
const errors: unknown[] = [];
|
||||
let root!: ReturnType<typeof hydrateRoot>;
|
||||
act(() => {
|
||||
root = hydrateRoot(container, ui, {
|
||||
onRecoverableError: (error) => errors.push(error),
|
||||
});
|
||||
});
|
||||
const unmount = () => {
|
||||
mounted.delete(unmount);
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
};
|
||||
mounted.add(unmount);
|
||||
return { container, errors, unmount };
|
||||
}
|
||||
|
||||
export { renderToString };
|
||||
|
||||
// A server router at the path of the prerendered file, a browser router at
|
||||
// the URL the visitor opened: `/404` for the 404 page, the page itself with
|
||||
// the query stripped for the others. Same test shell as renderApp.
|
||||
const TestShell = ({ children }: { children: ReactNode }) => (
|
||||
<>
|
||||
<HeadContent />
|
||||
{children}
|
||||
</>
|
||||
);
|
||||
|
||||
async function appRouterAt(path: string) {
|
||||
const router = createRouter({
|
||||
...routerOptions(),
|
||||
history: createMemoryHistory({ initialEntries: [path] }),
|
||||
});
|
||||
const rootOptions = router.routesById[rootRouteId].options as {
|
||||
shellComponent?: typeof TestShell;
|
||||
};
|
||||
rootOptions.shellComponent = TestShell;
|
||||
await router.load();
|
||||
return (
|
||||
<ChakraProvider value={system}>
|
||||
<RouterProvider router={router} />
|
||||
</ChakraProvider>
|
||||
);
|
||||
}
|
||||
|
||||
// renderToString cannot wait for a lazy component: it emits the fallback and a
|
||||
// client-render marker. The real prerender waits, so render again until every
|
||||
// lazy chunk (the form, the dev-only devtools) has loaded.
|
||||
async function serverMarkup(ui: ReactElement) {
|
||||
let markup = renderToString(ui);
|
||||
for (
|
||||
let attempt = 0;
|
||||
markup.includes('<!--$!-->') && attempt < 100;
|
||||
attempt++
|
||||
) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
markup = renderToString(ui);
|
||||
}
|
||||
return markup;
|
||||
}
|
||||
|
||||
export async function hydrateApp(serverPath: string, clientPath: string) {
|
||||
const [server, client] = await Promise.all([
|
||||
appRouterAt(serverPath),
|
||||
appRouterAt(clientPath),
|
||||
]);
|
||||
return hydrate(client, await serverMarkup(server));
|
||||
}
|
||||
|
||||
// A component alone, inside the Chakra theme and a router that matches every
|
||||
// path (like renderWithProviders), for components that only need Link
|
||||
async function withProviders(ui: ReactElement, path: string) {
|
||||
const rootRoute = createRootRoute();
|
||||
const splat = createRoute({ getParentRoute: () => rootRoute, path: '$' });
|
||||
const router = createRouter({
|
||||
routeTree: rootRoute.addChildren([splat]),
|
||||
history: createMemoryHistory({ initialEntries: [path] }),
|
||||
});
|
||||
await router.load();
|
||||
return (
|
||||
<ChakraProvider value={system}>
|
||||
<RouterContextProvider router={router}>{ui}</RouterContextProvider>
|
||||
</ChakraProvider>
|
||||
);
|
||||
}
|
||||
|
||||
// The HTML the prerender would write for this component
|
||||
export async function serverHtml(ui: ReactElement, path = '/') {
|
||||
return serverMarkup(await withProviders(ui, path));
|
||||
}
|
||||
|
||||
// Hydrates that HTML, as the browser does
|
||||
export async function hydratePage(ui: ReactElement, path = '/') {
|
||||
return hydrate(await withProviders(ui, path), await serverHtml(ui, path));
|
||||
}
|
||||
Reference in New Issue
Block a user