Import instead of code: panel forms (steps, choice lists, dates), layout, page route, GEO routes, links, section fields
- Forms: step and checkboxGroup field types (radio, date on), server validation for them, useBuilderForm (logic) + BuilderForm (unstyled default) + RenderForm (/rsc: rich text, bound action, public part of the form only — the Emails tab never reaches the browser) - Notifications: next / back / stepOf texts - createContentHelpers: getSiteShell, getFormTexts, getLinkOptions, resolveLink, resolveNav, resolvePageRedirect, one-line route handlers (llms, llms-full, md, mcp, health, indexnow, manifest) - /rsc: SiteProviders, createPageRoute, createNotFoundPage - resolveLink / resolveNav / homeSlugFrom, buildSectionHeaderField / buildSectionSettingsField - Dev sandbox frontend built on these imports; tests (unit + real Payload) Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -0,0 +1,133 @@
|
||||
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 { 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()
|
||||
})
|
||||
})
|
||||
@@ -65,3 +65,38 @@ describe('form validation — injection and abuse', () => {
|
||||
expect(await check({ count: ' 42 ' })).toMatchObject({ cleaned: { count: 42 }, ok: true })
|
||||
})
|
||||
})
|
||||
|
||||
describe('form validation — choice lists and dates', () => {
|
||||
const { payload: p } = fakePayload({
|
||||
forms: {
|
||||
g: {
|
||||
fields: [
|
||||
{ name: 'services', blockType: 'checkboxGroup', maxSelected: 2, minSelected: 1, options: [{ value: 'www' }, { value: 'seo' }, { value: 'ads' }] },
|
||||
{ name: 'size', blockType: 'radio', options: [{ value: 's' }, { value: 'l' }] },
|
||||
{ name: 'deadline', blockType: 'date' },
|
||||
{ blockType: 'step' },
|
||||
],
|
||||
},
|
||||
},
|
||||
})
|
||||
const v = (data: Record<string, unknown>) => validateSubmission(p, 'g', data)
|
||||
|
||||
test('checkbox group: only configured values, deduplicated, within min/max', async () => {
|
||||
expect(await v({ services: ['www', 'seo', 'www'] })).toMatchObject({ cleaned: { services: ['www', 'seo'] }, ok: true })
|
||||
expect(await v({ services: ['www', '<b>x</b>'] })).toMatchObject({ field: 'services', kind: 'invalid_format' })
|
||||
expect(await v({ services: ['www', 'seo', 'ads'] })).toMatchObject({ field: 'services', kind: 'invalid_format' })
|
||||
expect(await v({ services: 'www' })).toMatchObject({ field: 'services', kind: 'invalid_format' })
|
||||
expect(await v({ services: [{ $ne: 1 }] })).toMatchObject({ field: 'services', kind: 'invalid_format' })
|
||||
})
|
||||
|
||||
test('radio accepts only its options; date must be a real date', async () => {
|
||||
expect(await v({ deadline: '2026-11-30', size: 'l' })).toMatchObject({ cleaned: { deadline: '2026-11-30', size: 'l' }, ok: true })
|
||||
expect(await v({ size: 'xl' })).toMatchObject({ field: 'size', kind: 'invalid_format' })
|
||||
expect(await v({ deadline: 'jutro' })).toMatchObject({ field: 'deadline', kind: 'invalid_format' })
|
||||
expect(await v({ deadline: '2026-13-45' })).toMatchObject({ field: 'deadline', kind: 'invalid_format' })
|
||||
})
|
||||
|
||||
test('a Step block carries no value and is not an unknown field', async () => {
|
||||
expect(await v({})).toMatchObject({ ok: true })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -16,6 +16,7 @@ import { buildConsentLogEndpoint } from '../src/modules/consent/consentLog.js'
|
||||
import { getCookieTable } from '../src/modules/consent/getConsentTexts.js'
|
||||
import { submitForm } from '../src/modules/forms/submitForm.js'
|
||||
import { createContentHelpers } from '../src/modules/frontend/createContentHelpers.js'
|
||||
import { createPageRoute } from '../src/modules/frontend/pageRoute.js'
|
||||
import { ipalKit } from '../src/plugin.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
@@ -117,6 +118,41 @@ describe('forms against a real Payload', () => {
|
||||
expect(await send({ name: 'Ala', consent: true, role: 'admin' })).toMatchObject({ kind: 'unknown_fields' })
|
||||
})
|
||||
|
||||
test('step-by-step form with a checkbox group, radio and date: built in the panel, stored readable', async () => {
|
||||
const multi = await payload.create({
|
||||
collection: 'forms' as never,
|
||||
data: {
|
||||
confirmationType: 'redirect',
|
||||
fields: [
|
||||
{ name: 'name', blockType: 'text', label: 'Imię', required: true },
|
||||
{ blockType: 'step', title: 'Szczegóły' },
|
||||
{ name: 'services', blockType: 'checkboxGroup', label: 'Usługi', options: [{ label: 'Strona', value: 'www' }, { label: 'SEO', value: 'seo' }], required: true },
|
||||
{ name: 'size', blockType: 'radio', label: 'Wielkość', options: [{ label: 'Mała', value: 's' }, { label: 'Duża', value: 'l' }] },
|
||||
{ name: 'deadline', blockType: 'date', label: 'Termin' },
|
||||
],
|
||||
redirect: { url: '/dziekujemy' },
|
||||
title: 'Wycena',
|
||||
} as never,
|
||||
})
|
||||
const result = await submitForm({
|
||||
data: { name: 'Ala', deadline: '2026-12-01', services: ['www', 'seo'], size: 'l' },
|
||||
formId: String(multi.id),
|
||||
ip: '10.7.0.9',
|
||||
payload,
|
||||
})
|
||||
expect(result).toMatchObject({ success: true })
|
||||
if (!result.success) {return}
|
||||
const stored = (await payload.findByID({ id: result.submissionId, collection: 'form-submissions' as never, depth: 0 })) as unknown as {
|
||||
submissionData: { field: string; value: string }[]
|
||||
}
|
||||
expect(stored.submissionData.map(({ field, value }) => [field, value])).toEqual([
|
||||
['name', 'Ala'],
|
||||
['services', 'www, seo'],
|
||||
['size', 'l'],
|
||||
['deadline', '2026-12-01'],
|
||||
])
|
||||
})
|
||||
|
||||
test('REST/anonymous creation of submissions is closed (only submitForm writes)', async () => {
|
||||
await expect(
|
||||
payload.create({
|
||||
@@ -178,6 +214,51 @@ describe('getPageJsonLd', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('one-call helpers — layout, page, GEO routes', () => {
|
||||
const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] } as const
|
||||
const h = () => createContentHelpers({ baseUrl: 'https://acme.pl', config: configPromise, i18n, mcp: { serverName: 'acme-site' } })
|
||||
|
||||
test('getSiteShell: consent, analytics, Turnstile, form texts and site JSON-LD in one call', async () => {
|
||||
await payload.updateGlobal({ slug: 'site-settings' as never, data: { siteName: 'Acme' } as never })
|
||||
const shell = await h().getSiteShell('pl')
|
||||
expect(shell.turnstileSiteKey).toBeNull()
|
||||
expect(shell.consent.buttons.acceptAll).toEqual(expect.any(String))
|
||||
expect(shell.formTexts).toMatchObject({ next: 'Next', stepOf: 'Step {current} of {total}' })
|
||||
expect(shell.jsonLd.map((n) => n['@type'])).toEqual(['WebSite', 'Organization'])
|
||||
expect(shell.jsonLd.every((n) => !('@context' in n))).toBe(true)
|
||||
const custom = createContentHelpers({ baseUrl: 'https://acme.pl', config: configPromise, i18n, siteJsonLd: false })
|
||||
expect((await custom.getSiteShell('pl')).jsonLd).toEqual([])
|
||||
})
|
||||
|
||||
test('createPageRoute: renders a page with its JSON-LD, 404s an unknown slug', async () => {
|
||||
await payload.create({ collection: 'pages' as never, data: { slug: 'uslugi', title: 'Usługi' } as never })
|
||||
const notFound = vi.fn(() => {
|
||||
throw new Error('NEXT_NOT_FOUND')
|
||||
}) as unknown as () => never
|
||||
const permanentRedirect = vi.fn() as unknown as (url: string) => never
|
||||
const route = createPageRoute(h(), { blocks: {}, notFound, permanentRedirect })
|
||||
const el = (await route.Page({ params: Promise.resolve({ slug: ['uslugi'] }) })) as { props: { children: unknown[] } }
|
||||
expect(JSON.stringify(el.props.children[0])).toContain('Usługi')
|
||||
await expect(route.Page({ params: Promise.resolve({ slug: ['nie-ma'] }) })).rejects.toThrow('NEXT_NOT_FOUND')
|
||||
expect((await route.generateMetadata({ params: Promise.resolve({ slug: ['uslugi'] }) })).alternates?.canonical).toBe('https://acme.pl/uslugi')
|
||||
})
|
||||
|
||||
test('route handlers answer without per-file configuration', async () => {
|
||||
const helpers = h()
|
||||
const llms = await helpers.llmsRoute()
|
||||
expect(llms.status).toBe(200)
|
||||
expect(await llms.text()).toContain('https://acme.pl/uslugi')
|
||||
expect((await helpers.healthRoute()).status).toBe(200)
|
||||
expect((await helpers.indexNowKeyRoute()).status).toBe(404) // no key configured
|
||||
const mcp = await helpers.mcpPOST(
|
||||
new Request('https://acme.pl/api/mcp', { body: JSON.stringify({ id: 1, jsonrpc: '2.0', method: 'initialize' }), headers: { 'content-type': 'application/json' }, method: 'POST' }),
|
||||
)
|
||||
expect(JSON.stringify(await mcp.json())).toContain('acme-site')
|
||||
const md = await helpers.markdownRoute(new Request('https://acme.pl/md/uslugi'), { params: Promise.resolve({ slug: ['uslugi'], locale: 'pl' }) })
|
||||
expect(md.status).toBe(200)
|
||||
})
|
||||
})
|
||||
|
||||
describe('consent log', () => {
|
||||
const post = (body: unknown, ip = '10.6.0.1') =>
|
||||
buildConsentLogEndpoint().handler({
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import { describe, expect, test } from 'vitest'
|
||||
|
||||
import { buildSectionHeaderField, buildSectionSettingsField } from '../src/modules/blocks/sectionFields.js'
|
||||
import { homeSlugFrom, resolveLink, resolveNav } from '../src/modules/links/resolveNav.js'
|
||||
|
||||
const config = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'PL' }, { code: 'en', label: 'EN' }] }
|
||||
const opts = { config, homeSlug: 'start', locale: 'pl' }
|
||||
const page = (slug: string) => ({ type: 'internal' as const, label: slug, page: { slug } })
|
||||
|
||||
describe('resolveLink', () => {
|
||||
test('internal page → next/link, no target', () => {
|
||||
expect(resolveLink(page('kontakt'), opts)).toEqual({ href: '/pl/kontakt', internal: true, label: 'kontakt', newTab: false, targetProps: {} })
|
||||
})
|
||||
|
||||
test('files always open in a new tab with rel; appearance is passed through', () => {
|
||||
expect(resolveLink({ type: 'file', appearance: 'primary', file: { url: '/media/cennik.pdf' }, label: 'Cennik' }, opts)).toMatchObject({
|
||||
appearance: 'primary',
|
||||
href: '/media/cennik.pdf',
|
||||
internal: false,
|
||||
targetProps: { rel: 'noopener noreferrer', target: '_blank' },
|
||||
})
|
||||
})
|
||||
|
||||
test('nowhere → null: unsafe URL, missing page, empty link', () => {
|
||||
expect(resolveLink({ type: 'external', url: 'javascript:alert(1)' }, opts)).toBeNull()
|
||||
expect(resolveLink({ type: 'internal', page: 5 }, opts)).toBeNull()
|
||||
expect(resolveLink(null, opts)).toBeNull()
|
||||
})
|
||||
|
||||
test('the homepage collapses to the locale root', () => {
|
||||
expect(resolveLink(page('start'), opts)?.href).toBe('/pl')
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveNav', () => {
|
||||
test('nested items resolved; dead or unlabeled items dropped', () => {
|
||||
const items = [
|
||||
{ link: page('oferta'), subItems: [{ link: page('www') }, { link: { type: 'internal', label: 'x', page: null } }] },
|
||||
{ link: { type: 'external', url: 'https://x.pl' } }, // no label
|
||||
{ link: page('kontakt') },
|
||||
]
|
||||
const nav = resolveNav(items, opts)
|
||||
expect(nav.map((i) => [i.href, i.children.map((c) => c.href)])).toEqual([
|
||||
['/pl/oferta', ['/pl/www']],
|
||||
['/pl/kontakt', []],
|
||||
])
|
||||
})
|
||||
|
||||
test('custom item shape and junk input', () => {
|
||||
expect(resolveNav([{ children: [{ to: page('a') }], to: page('b') }], { ...opts, childrenField: 'children', linkField: 'to' })[0].children[0].href).toBe('/pl/a')
|
||||
expect(resolveNav(null, opts)).toEqual([])
|
||||
expect(resolveNav('x', opts)).toEqual([])
|
||||
})
|
||||
|
||||
test('homeSlugFrom reads a populated homepage only', () => {
|
||||
expect(homeSlugFrom({ homepage: { slug: 'start' } })).toBe('start')
|
||||
expect(homeSlugFrom({ homepage: 3 })).toBeUndefined()
|
||||
expect(homeSlugFrom(null)).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('section fields', () => {
|
||||
test('defaults match the documented shape (types SectionHeaderData / SectionSettings)', () => {
|
||||
const header = buildSectionHeaderField()
|
||||
expect(header).toMatchObject({ name: 'header', interfaceName: 'SectionHeaderData' })
|
||||
expect(header.fields.map((f) => ('name' in f ? f.name : ''))).toEqual(['eyebrow', 'heading', 'intro'])
|
||||
const settings = buildSectionSettingsField()
|
||||
expect(settings).toMatchObject({ name: 'settings', admin: { position: 'sidebar' }, interfaceName: 'SectionSettings' })
|
||||
expect(settings.fields.map((f) => ('name' in f ? f.name : ''))).toEqual(['anchor', 'background'])
|
||||
})
|
||||
|
||||
test('the project decides: own backgrounds, no anchor, extra fields', () => {
|
||||
const s = buildSectionSettingsField({ anchor: false, backgrounds: [{ label: 'Brand', value: 'brand' }], fields: [{ name: 'spacing', type: 'text' }] })
|
||||
expect(s.fields.map((f) => ('name' in f ? f.name : ''))).toEqual(['background', 'spacing'])
|
||||
expect(s.fields[0]).toMatchObject({ defaultValue: 'brand' })
|
||||
expect(buildSectionSettingsField({ backgrounds: false }).fields.map((f) => ('name' in f ? f.name : ''))).toEqual(['anchor'])
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user