Files
ipal-kit/test/builderForm.test.ts
Radosław SmolińskiandClaude Opus 5.5 f809526f1d Page-filled form fields, links to entries, entry JSON-LD, R2-optional dev
Forms: `values` on RenderForm / BuilderForm / useBuilderForm fills fields the
page knows (chosen product variant, category) — read-only <output>, in the
SSR HTML, sent and validated like any field. prepareBuilderForm (/rsc) is the
server half of RenderForm for client components whose values change in the
browser; publicForm is exported so projects stop copying it.

Links: buildLinkField({ relationTo: ['pages', 'categories', …] }) — a
polymorphic relation; resolveLinkHref builds /{locale}/{archive}/{entry} from
`archives`, which getLinkOptions in createContentHelpers fills from Site
Settings.

SEO: pageJsonLd.entries — the main JSON-LD node per content collection
instead of BlogPosting; buildProductJsonLd emits an Offer only for a real
price from the panel.

Pages: createPageRoute / createNotFoundPage pass isFirst to blocks, so the
first section carries the page's only h1.

Fixes: ipalEnvRules({ storage: true }) requires R2_* in production only
(development: optional, all or none); buildImagesConfig allows the app's own
media on localhost outside production.

Docs, CHANGELOG, PROGRAMISTA §6 (34–37), ipal-form and ipal-upgrade skills.
Tests: builderForm, links, drafts (entries + archives), seo, media, env.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-19 19:38:28 +02:00

182 lines
8.5 KiB
TypeScript

import { createElement, isValidElement } from 'react'
import { renderToStaticMarkup } from 'react-dom/server'
import { describe, expect, test, vi } from 'vitest'
import type { BuilderField, BuilderFormDoc } from '../src/modules/forms/builderTypes.js'
import { BuilderForm } from '../src/modules/forms/BuilderForm.js'
import { autoCompleteFor, initialBuilderValues, splitSteps, stepOfField, validateBuilderFields } from '../src/modules/forms/builderLogic.js'
import { prepareBuilderForm, publicForm, RenderForm } from '../src/modules/forms/RenderForm.js'
vi.mock('server-only', () => ({}))
const fields: BuilderField[] = [
{ name: 'name', blockType: 'text', label: 'Imię', required: true },
{ name: 'email', blockType: 'email', label: 'E-mail', required: true },
{ blockType: 'step', title: 'Szczegóły' },
{ name: 'budget', blockType: 'radio', label: 'Budżet', options: [{ label: 'Mały', value: 's' }, { label: 'Duży', value: 'l' }], required: true },
{ name: 'services', blockType: 'checkboxGroup', label: 'Usługi', maxSelected: 2, options: [{ value: 'www' }, { value: 'seo' }, { value: 'ads' }] },
{ blockType: 'message', message: { root: {} } },
{ name: 'deadline', blockType: 'date', label: 'Termin' },
{ name: 'consent', blockType: 'checkbox', label: 'Zgoda', required: true },
]
const texts = { back: 'Wstecz', next: 'Dalej', stepOf: 'Krok {current} z {total}', validation: 'Sprawdź pole {field}' }
describe('panel form logic', () => {
test('Step blocks split the form into screens; fields before the first Step are screen 1', () => {
const steps = splitSteps(fields)
expect(steps.map((s) => ({ names: s.fields.map(({ field }) => field.name ?? field.blockType), title: s.title }))).toEqual([
{ names: ['name', 'email'], title: undefined },
{ names: ['budget', 'services', 'message', 'deadline', 'consent'], title: 'Szczegóły' },
])
expect(stepOfField(steps, 'consent')).toBe(1)
})
test('no Steps → one screen; trailing or doubled Steps leave no empty screens', () => {
expect(splitSteps(fields.filter((f) => f.blockType !== 'step'))).toHaveLength(1)
expect(splitSteps([{ blockType: 'step' }, { blockType: 'step' }, { name: 'a', blockType: 'text' }, { blockType: 'step' }])).toHaveLength(1)
})
test('initial values by type', () => {
expect(initialBuilderValues(fields)).toEqual({ name: '', budget: '', consent: false, deadline: '', email: '', services: [] })
})
test('validation: required, e-mail, choice limits — only for the fields given (one step)', () => {
const values = { ...initialBuilderValues(fields), email: 'zły', services: ['www', 'seo', 'ads'] }
expect(validateBuilderFields(splitSteps(fields)[0].fields.map(({ field }) => field), values, texts)).toEqual({
name: 'Sprawdź pole Imię',
email: 'Sprawdź pole E-mail',
})
expect(validateBuilderFields(fields, values, texts)).toMatchObject({ budget: expect.any(String), consent: expect.any(String), services: expect.any(String) })
})
test('autofill hints', () => {
expect(autoCompleteFor({ name: 'phone', blockType: 'text' })).toBe('tel')
expect(autoCompleteFor({ name: 'x', blockType: 'email' })).toBe('email')
expect(autoCompleteFor({ name: 'message', blockType: 'text' })).toBeUndefined()
})
})
const form: BuilderFormDoc = { id: 7, fields, submitButtonLabel: 'Wyślij' }
const action = async () => ({ success: true })
describe('BuilderForm markup', () => {
test('unstyled by default: no class attributes, data hooks, honeypot, progress and Next on step 1', () => {
const html = renderToStaticMarkup(createElement(BuilderForm, { action, form, texts }))
expect(html).not.toMatch(/class="/)
expect(html).toContain('data-ipal="form"')
expect(html).toContain('name="company_url"')
expect(html).toContain('Krok 1 z 2')
expect(html).toContain('>Dalej</button>')
expect(html).not.toContain('Wyślij')
expect(html).toMatch(/<label for="ipal-f-7-name">Imię<\/label><input[^>]*id="ipal-f-7-name"[^>]*required=""/)
expect(html).toContain('autoComplete="email"')
})
test('classNames go where they belong; a single-screen form shows the submit label', () => {
const html = renderToStaticMarkup(
createElement(BuilderForm, {
action,
classNames: { fieldHalf: 'half', form: 'f', input: 'in', submit: 'btn' },
form: { ...form, fields: [{ name: 'a', blockType: 'text', label: 'A', width: 50 }] },
texts,
}),
)
expect(html).toContain('<form class="f"')
expect(html).toContain('class="half"')
expect(html).toContain('class="in"')
expect(html).toContain('<button class="btn" type="submit">Wyślij</button>')
expect(html).not.toContain('Krok')
})
test('radio and checkbox groups are fieldsets with a legend', () => {
const html = renderToStaticMarkup(
createElement(BuilderForm, { action, form: { ...form, fields: fields.slice(3, 5) }, texts }),
)
expect(html).toMatch(/<fieldset[^>]*id="ipal-f-7-budget"><legend>Budżet<\/legend>/)
expect(html).toMatch(/type="radio"[^>]*value="s"|value="s"[^>]*type="radio"/)
expect(html).toMatch(/<fieldset[^>]*id="ipal-f-7-services"><legend>Usługi<\/legend>/)
})
test('renderField replaces chosen fields and can reuse the default', () => {
const html = renderToStaticMarkup(
createElement(BuilderForm, {
action,
form: { ...form, fields: fields.slice(0, 2) },
renderField: ({ defaultRender, field }) => (field.name === 'email' ? createElement('div', { 'data-x': 'wrap' }, defaultRender()) : undefined),
texts,
}),
)
expect(html).toMatch(/<div data-x="wrap"><label for="ipal-f-7-email">/)
})
})
describe('RenderForm', () => {
test('passes only the public part of the form to the browser — never the Emails tab', () => {
const doc = {
...form,
confirmationType: 'redirect' as const,
emails: [{ emailTo: '[email protected]' }],
redirect: { type: 'custom' as const, url: 'javascript:alert(1)' },
}
const el = RenderForm({ action: async () => ({ message: '', success: true }), form: doc, locale: 'pl', texts })
expect(isValidElement(el)).toBe(true)
const props = (el as { props: { form: Record<string, unknown>; redirectHref: unknown } }).props
expect(JSON.stringify(props.form)).not.toContain('[email protected]')
expect(props.form).not.toHaveProperty('emails')
expect(props.redirectHref).toBeNull() // unsafe scheme dropped
})
test('a bare id or null renders nothing (no placeholder form)', () => {
expect(RenderForm({ action: async () => ({ message: '', success: true }), form: 5, locale: 'pl', texts })).toBeNull()
})
})
describe('page values (values prop) and prepareBuilderForm', () => {
const withSubject: BuilderFormDoc = {
id: 9,
fields: [
{ name: 'subject', blockType: 'text', label: 'Dotyczy' },
{ name: 'email', blockType: 'email', label: 'E-mail', required: true },
],
submitButtonLabel: 'Wyślij',
}
test('a field filled by the page is read-only output in the first HTML, others stay inputs', () => {
const html = renderToStaticMarkup(
createElement(BuilderForm, {
action: async () => ({ message: 'ok', success: true }),
classNames: { fixed: 'fx' },
form: withSubject,
texts,
values: { subject: 'Pierścionek · białe złoto', unknown: 'x' },
}),
)
expect(html).toContain('<output')
expect(html).toContain('class="fx"')
expect(html).toContain('Pierścionek · białe złoto')
expect(html).not.toMatch(/<input[^>]*name="subject"/)
expect(html).toMatch(/<input[^>]*name="email"/)
expect(html).not.toContain('unknown')
})
test('RenderForm passes values through', () => {
const action = async () => ({ message: 'ok', success: true })
const html = renderToStaticMarkup(
createElement(RenderForm, { action, form: withSubject, locale: 'pl', texts, values: { subject: 'Broszki' } }),
)
expect(html).toContain('Broszki')
})
test('prepareBuilderForm: public part only, bound action, null for an id', () => {
const doc = { ...withSubject, emails: [{ emailTo: '[email protected]' }] } as BuilderFormDoc
const action = vi.fn(async () => ({ message: 'ok', success: true }))
const prepared = prepareBuilderForm({ action, form: doc, locale: 'pl' })
expect(JSON.stringify(prepared?.form)).not.toContain('[email protected]')
expect(prepared?.form).toEqual(publicForm(doc))
void prepared?.action({ email: '[email protected]' })
expect(action).toHaveBeenCalledWith('9', 'pl', { email: '[email protected]' })
expect(prepareBuilderForm({ action, form: '9', locale: 'pl' })).toBeNull()
})
})