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]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
46d30d4ecd
commit
f809526f1d
Vendored
+14
-5
@@ -16,7 +16,12 @@ export type IpalEnvFeatures = {
|
||||
secretVar?: string
|
||||
/** Override the site-URL var. Default 'NEXT_PUBLIC_SERVER_URL'. */
|
||||
serverUrlVar?: string
|
||||
/** R2 object storage (buildR2Storage). Adds the R2_* vars. */
|
||||
/**
|
||||
* R2 object storage (buildR2Storage). Adds the R2_* vars — required in
|
||||
* production (media on a container disk vanish on redeploy). Outside
|
||||
* production they're optional (media go to the local disk), but a partial
|
||||
* set is an error: buildR2Storage needs all of them.
|
||||
*/
|
||||
storage?: boolean
|
||||
/**
|
||||
* Cloudflare Turnstile. true uses the common var names
|
||||
@@ -69,14 +74,18 @@ export function ipalEnvRules(features: IpalEnvFeatures = {}): EnvRule[] {
|
||||
]
|
||||
|
||||
if (storage) {
|
||||
const r2Vars = ['R2_BUCKET', 'R2_ACCESS_KEY_ID', 'R2_SECRET_ACCESS_KEY', 'R2_ENDPOINT', 'R2_PUBLIC_URL']
|
||||
// Production: always. Development: only once any R2_* is set (all or nothing).
|
||||
const r2Required = process.env.NODE_ENV === 'production' || r2Vars.some((name) => Boolean(process.env[name]))
|
||||
rules.push(
|
||||
{ name: 'R2_BUCKET', description: 'R2 bucket name' },
|
||||
{ name: 'R2_ACCESS_KEY_ID', description: 'R2 access key id' },
|
||||
{ name: 'R2_SECRET_ACCESS_KEY', description: 'R2 secret access key' },
|
||||
{ name: 'R2_ENDPOINT', description: 'R2 S3 API endpoint URL', kind: 'url' },
|
||||
{ name: 'R2_BUCKET', description: 'R2 bucket name', required: r2Required },
|
||||
{ name: 'R2_ACCESS_KEY_ID', description: 'R2 access key id', required: r2Required },
|
||||
{ name: 'R2_SECRET_ACCESS_KEY', description: 'R2 secret access key', required: r2Required },
|
||||
{ name: 'R2_ENDPOINT', description: 'R2 S3 API endpoint URL', kind: 'url', required: r2Required },
|
||||
{
|
||||
name: 'R2_PUBLIC_URL',
|
||||
description: 'Public base URL media is served from (custom domain of the bucket)',
|
||||
required: r2Required,
|
||||
// Production: absolute URL (https://media.example.com). Outside production a
|
||||
// site-relative path ('/media') is accepted — buildR2Storage prefixes it with
|
||||
// NEXT_PUBLIC_SERVER_URL (e.g. a dev rewrite /media → bucket).
|
||||
|
||||
@@ -18,7 +18,7 @@ import { useBuilderForm } from './useBuilderForm.js'
|
||||
export type BuilderFormClassNames = Partial<
|
||||
Record<
|
||||
| 'actions' | 'back' | 'checkbox' | 'checkboxLabel' | 'choice' | 'choiceInput' | 'choiceLabel' | 'choices'
|
||||
| 'error' | 'field' | 'fieldFull' | 'fieldHalf' | 'fields' | 'form' | 'formError' | 'input' | 'label'
|
||||
| 'error' | 'field' | 'fieldFull' | 'fieldHalf' | 'fields' | 'fixed' | 'form' | 'formError' | 'input' | 'label'
|
||||
| 'legend' | 'message' | 'next' | 'progress' | 'required' | 'select' | 'step' | 'stepDescription'
|
||||
| 'stepTitle' | 'submit' | 'success' | 'textarea' | 'turnstile',
|
||||
string
|
||||
@@ -51,6 +51,9 @@ export type BuilderFormProps = {
|
||||
turnstileTheme?: 'auto' | 'dark' | 'light'
|
||||
} & UseBuilderFormOptions
|
||||
|
||||
/** A page-supplied value (always a string from `values`) as text. */
|
||||
const fixedText = (value: unknown) => (typeof value === 'string' ? value : '')
|
||||
|
||||
const cx = (...c: (false | null | string | undefined)[]) => c.filter(Boolean).join(' ') || undefined
|
||||
|
||||
/**
|
||||
@@ -108,6 +111,18 @@ export function BuilderForm({
|
||||
|
||||
const defaultField = (field: BuilderField, index: number): ReactNode => {
|
||||
if (field.blockType === 'message') {return <div className={cn.message}>{messages[index]}</div>}
|
||||
if (f.isFixed(field)) {
|
||||
// Filled by the page (`values`): visible, not editable, sent with the form.
|
||||
const id = f.fieldId(field)
|
||||
return (
|
||||
<>
|
||||
<span className={cn.label} id={`${id}-label`}>{field.label}</span>
|
||||
<output aria-labelledby={`${id}-label`} className={cn.fixed} data-ipal="form-fixed" id={id}>
|
||||
{fixedText(f.values[field.name ?? ''])}
|
||||
</output>
|
||||
</>
|
||||
)
|
||||
}
|
||||
switch (field.blockType) {
|
||||
case 'checkbox': {
|
||||
const props = f.getInputProps(field)
|
||||
|
||||
@@ -38,11 +38,13 @@ export type RenderFormProps = {
|
||||
/** Notifications → form texts in this locale (getNotificationTexts(...).form). */
|
||||
texts: BuilderFormTexts
|
||||
turnstileTheme?: 'auto' | 'dark' | 'light'
|
||||
/** Values of fields the page already knows, by field name — read-only for the visitor, sent with the form. */
|
||||
values?: Record<string, string>
|
||||
}
|
||||
|
||||
/** Only what the browser needs. The Local API reads with overrideAccess, so the
|
||||
* document still carries Emails (recipient addresses) — those never leave the server. */
|
||||
function publicForm(form: BuilderFormDoc): BuilderFormDoc {
|
||||
export function publicForm(form: BuilderFormDoc): BuilderFormDoc {
|
||||
return {
|
||||
id: form.id,
|
||||
analytics: form.analytics,
|
||||
@@ -54,27 +56,42 @@ function publicForm(form: BuilderFormDoc): BuilderFormDoc {
|
||||
}
|
||||
}
|
||||
|
||||
export type PrepareBuilderFormArgs = Pick<
|
||||
RenderFormProps,
|
||||
'action' | 'converters' | 'form' | 'linkOptions' | 'locale' | 'richTextClassName'
|
||||
>
|
||||
|
||||
/** What the browser gets for a panel form — spread it into <BuilderForm> (plus texts, classNames, values). */
|
||||
export type PreparedBuilderForm = {
|
||||
action: (values: Record<string, unknown>, turnstileToken?: string) => Promise<SubmitActionResult>
|
||||
confirmation: ReactNode
|
||||
form: BuilderFormDoc
|
||||
messages: Record<number, ReactNode>
|
||||
redirectHref: null | string
|
||||
}
|
||||
|
||||
/**
|
||||
* A panel form inside a block, in one line — server part of BuilderForm:
|
||||
* The server half of RenderForm without the markup: the public part of the form,
|
||||
* rendered message blocks and confirmation, the action bound to form + locale,
|
||||
* the redirect target. For a client component that renders <BuilderForm> itself —
|
||||
* e.g. with `values` that change in the browser (a product configurator):
|
||||
*
|
||||
* <RenderForm form={form} action={sendForm} locale={locale} texts={formTexts} classNames={formClasses} />
|
||||
* // server
|
||||
* const prepared = prepareBuilderForm({ form, action: sendForm, locale })
|
||||
* <ProductConfigurator form={prepared} texts={formTexts} />
|
||||
* // client
|
||||
* <BuilderForm {...form} texts={texts} classNames={formClasses} values={{ subject: chosenVariant }} />
|
||||
*
|
||||
* Renders `message` blocks and the confirmation with RenderRichText, binds the
|
||||
* action to the form and locale, resolves the redirect target, and passes the
|
||||
* client only the public part of the form (never the Emails tab).
|
||||
* Returns null for an unpopulated form (an id or nothing).
|
||||
*/
|
||||
export function RenderForm({
|
||||
export function prepareBuilderForm({
|
||||
action,
|
||||
classNames,
|
||||
converters,
|
||||
form,
|
||||
linkOptions,
|
||||
locale,
|
||||
requiredMark,
|
||||
richTextClassName,
|
||||
texts,
|
||||
turnstileTheme,
|
||||
}: RenderFormProps) {
|
||||
}: PrepareBuilderFormArgs): null | PreparedBuilderForm {
|
||||
if (!form || typeof form !== 'object') {return null} // never a placeholder form
|
||||
|
||||
const rich = (data: unknown) =>
|
||||
@@ -93,17 +110,51 @@ export function RenderForm({
|
||||
: safeHref(form.redirect?.url)
|
||||
: null
|
||||
|
||||
return {
|
||||
action: action.bind(null, String(form.id), locale),
|
||||
confirmation: rich(form.confirmationMessage),
|
||||
form: publicForm(form),
|
||||
messages,
|
||||
redirectHref,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A panel form inside a block, in one line — server part of BuilderForm:
|
||||
*
|
||||
* <RenderForm form={form} action={sendForm} locale={locale} texts={formTexts} classNames={formClasses} />
|
||||
*
|
||||
* Renders `message` blocks and the confirmation with RenderRichText, binds the
|
||||
* action to the form and locale, resolves the redirect target, and passes the
|
||||
* client only the public part of the form (never the Emails tab).
|
||||
*
|
||||
* `values` fill fields the page already knows (`{ subject: 'Brooches' }`): shown
|
||||
* read-only and sent with the submission. Values that change in the browser:
|
||||
* prepareBuilderForm + <BuilderForm values>.
|
||||
*/
|
||||
export function RenderForm({
|
||||
action,
|
||||
classNames,
|
||||
converters,
|
||||
form,
|
||||
linkOptions,
|
||||
locale,
|
||||
requiredMark,
|
||||
richTextClassName,
|
||||
texts,
|
||||
turnstileTheme,
|
||||
values,
|
||||
}: RenderFormProps) {
|
||||
const prepared = prepareBuilderForm({ action, converters, form, linkOptions, locale, richTextClassName })
|
||||
if (!prepared) {return null}
|
||||
return (
|
||||
<BuilderForm
|
||||
action={action.bind(null, String(form.id), locale)}
|
||||
{...prepared}
|
||||
classNames={classNames}
|
||||
confirmation={rich(form.confirmationMessage)}
|
||||
form={publicForm(form)}
|
||||
messages={messages}
|
||||
redirectHref={redirectHref}
|
||||
requiredMark={requiredMark}
|
||||
texts={texts}
|
||||
turnstileTheme={turnstileTheme}
|
||||
values={values}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -23,6 +23,12 @@ export type UseBuilderFormOptions = {
|
||||
/** Redirect target resolved on the server (RenderForm). Falls back to the form's custom URL. */
|
||||
redirectHref?: null | string
|
||||
texts: BuilderFormTexts
|
||||
/**
|
||||
* Fields the page fills, by name (e.g. `{ subject: 'Ring · white gold · 0.70 ct' }`):
|
||||
* kept in sync when the prop changes, read-only in BuilderForm, sent like any
|
||||
* field. Names not in the form are ignored (the server rejects unknown fields).
|
||||
*/
|
||||
values?: Record<string, string>
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -40,7 +46,7 @@ export type UseBuilderFormOptions = {
|
||||
* <button type="submit">{f.isLast ? form.submitButtonLabel : texts.next}</button>
|
||||
* </form>
|
||||
*/
|
||||
export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref, texts }: UseBuilderFormOptions) {
|
||||
export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref, texts, values: pageValues }: UseBuilderFormOptions) {
|
||||
const fields = useMemo(() => form.fields ?? [], [form.fields])
|
||||
// Fields behind a failed "Show only when" are neither shown, validated nor sent.
|
||||
const visibleInputs = useCallback((values: Record<string, unknown>) => inputFields(visibleFields(fields, values)), [fields])
|
||||
@@ -65,7 +71,11 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref
|
||||
|
||||
const f = useForm<Record<string, unknown>>({
|
||||
errorFallback: texts.error,
|
||||
initialValues: initialBuilderValues(fields),
|
||||
// Page values are in the first render too — server HTML shows them before hydration.
|
||||
initialValues: {
|
||||
...initialBuilderValues(fields),
|
||||
...Object.fromEntries(Object.entries(pageValues ?? {}).filter(([name]) => fields.some((field) => field.name === name))),
|
||||
},
|
||||
onSuccess: (_result, values) => {
|
||||
formAnalyticsOnSuccess(form.analytics)(_result, values)
|
||||
onSuccess?.(values)
|
||||
@@ -78,7 +88,19 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref
|
||||
submitAction,
|
||||
validate,
|
||||
})
|
||||
const { setErrors, setTurnstileToken } = f
|
||||
const { setErrors, setField, setTurnstileToken } = f
|
||||
|
||||
// Page-supplied values follow the prop (a configurator changes them in the browser).
|
||||
const fixedNames = useMemo(
|
||||
() => new Set(Object.keys(pageValues ?? {}).filter((name) => fields.some((field) => field.name === name))),
|
||||
[pageValues, fields],
|
||||
)
|
||||
const fixedKey = JSON.stringify(pageValues ?? {})
|
||||
useEffect(() => {
|
||||
for (const name of fixedNames) {setField(name, pageValues?.[name] ?? '')}
|
||||
}, [fixedKey, fixedNames, setField])
|
||||
/** True for a field whose value comes from the page (`values`) — show it, don't let the visitor edit it. */
|
||||
const isFixed = useCallback((field: BuilderField) => Boolean(field.name && fixedNames.has(field.name)), [fixedNames])
|
||||
// Steps follow the answers: a Step whose condition fails drops out, later steps renumber.
|
||||
const steps = useMemo(() => {
|
||||
const shown = new Set(visibleFields(fields, f.values))
|
||||
@@ -258,6 +280,7 @@ export function useBuilderForm({ action, form, navigate, onSuccess, redirectHref
|
||||
getTextareaProps,
|
||||
goTo,
|
||||
isFirst,
|
||||
isFixed,
|
||||
isLast,
|
||||
next,
|
||||
/** Message the server returned on success (Notifications → success). */
|
||||
|
||||
@@ -19,6 +19,7 @@ import { createMarkdownRoute } from '../content/createMarkdownRenderer.js'
|
||||
import { getArchiveEntries, resolveRoute as resolveRouteRaw } from '../content/index.js'
|
||||
import { MARKDOWN_PREFIX, markdownHref } from '../content/markdownNegotiation.js'
|
||||
import { resolveRedirect as resolveRedirectRaw } from '../content/resolveRedirect.js'
|
||||
import { archiveFieldName } from '../content/types.js'
|
||||
import { createHealthRoute } from '../health/createHealthRoute.js'
|
||||
import { homeSlugFrom, resolveLink as resolveLinkRaw, resolveNav as resolveNavRaw, resolveSystemLinks } from '../links/resolveNav.js'
|
||||
import { createMcpRoute } from '../mcp/createMcpRoute.js'
|
||||
@@ -94,9 +95,30 @@ type CreateContentHelpersArgs = {
|
||||
summaryField?: string
|
||||
}
|
||||
|
||||
/** What an entry's own JSON-LD builder gets (PageJsonLdOptions.entries). */
|
||||
export type EntryJsonLdContext = {
|
||||
/** Archive page of the entry (title, slug). */
|
||||
archive: Record<string, unknown>
|
||||
/** Meta description (SEO tab or the site's description). */
|
||||
description?: string
|
||||
doc: Record<string, unknown>
|
||||
/** Absolute share-image URL. */
|
||||
image?: string
|
||||
locale: string
|
||||
siteName?: string
|
||||
/** Absolute canonical URL of the entry. */
|
||||
url: string
|
||||
}
|
||||
|
||||
export type PageJsonLdOptions = {
|
||||
/** BreadcrumbList (home › archive › page) from the real route. Default true. */
|
||||
breadcrumbs?: boolean
|
||||
/**
|
||||
* The main node per content collection, instead of the article (`entryType`):
|
||||
* `{ products: (ctx) => buildProductJsonLd({…}), categories: (ctx) => buildWebPageJsonLd({ type: 'CollectionPage', … }) }`.
|
||||
* Return null to emit no main node. Breadcrumbs and FAQ still follow.
|
||||
*/
|
||||
entries?: Record<string, (ctx: EntryJsonLdContext) => null | Record<string, unknown>>
|
||||
/** schema.org type of archive entries. Default 'BlogPosting'. */
|
||||
entryType?: 'Article' | 'BlogPosting' | 'NewsArticle'
|
||||
/**
|
||||
@@ -270,7 +292,10 @@ export function createContentHelpers({
|
||||
const image = meta.openGraph?.images?.[0]?.url
|
||||
const nodes: (null | Record<string, unknown>)[] = []
|
||||
|
||||
if (route.type === 'entry') {
|
||||
const entryNode = route.type === 'entry' ? opts.entries?.[route.collection] : undefined
|
||||
if (route.type === 'entry' && entryNode) {
|
||||
nodes.push(entryNode({ archive: route.archive, description: meta.description, doc, image, locale, siteName, url }))
|
||||
} else if (route.type === 'entry') {
|
||||
nodes.push(
|
||||
buildArticleJsonLd({
|
||||
type: opts.entryType ?? 'BlogPosting',
|
||||
@@ -572,8 +597,23 @@ export function createContentHelpers({
|
||||
|
||||
/** Options for resolveLinkHref / resolveLink / RenderForm `linkOptions` in this locale. */
|
||||
const getLinkOptions = async (locale: string): Promise<ResolveLinkHrefOptions> => {
|
||||
const homeSlug = await getHomeSlug(locale)
|
||||
return { config: needI18n('getLinkOptions'), locale, ...(homeSlug ? { homeSlug } : {}) }
|
||||
const settings = await getSettings(locale)
|
||||
const homeSlug = homeSlugFrom(settings)
|
||||
// Archive page per content collection → links to entries (categories, products…) resolve too.
|
||||
const archives = Object.fromEntries(
|
||||
(content?.collections ?? []).flatMap(({ slug }) => {
|
||||
const archive = (settings as Record<string, unknown>)[archiveFieldName(slug)]
|
||||
const archiveSlug = archive && typeof archive === 'object' ? (archive as { slug?: unknown }).slug : undefined
|
||||
return typeof archiveSlug === 'string' && archiveSlug ? [[slug, archiveSlug]] : []
|
||||
}),
|
||||
)
|
||||
return {
|
||||
config: needI18n('getLinkOptions'),
|
||||
locale,
|
||||
pagesSlug,
|
||||
...(homeSlug ? { homeSlug } : {}),
|
||||
...(Object.keys(archives).length ? { archives } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -17,7 +17,11 @@ type Helpers = Partial<Pick<ContentHelpers, 'getConstructionMode'>> & Pick<
|
||||
type BlockPropsContext = { doc: Record<string, unknown>; locale: string }
|
||||
|
||||
export type PageRouteOptions = {
|
||||
/** Props for every block on top of `locale`, computed once per page — e.g. `{ formTexts, sendForm }` for form blocks. */
|
||||
/**
|
||||
* Props for every block on top of `locale` and `isFirst` (true for the first
|
||||
* section — its heading is the page's only h1), computed once per page —
|
||||
* e.g. `{ formTexts, sendForm }` for form blocks.
|
||||
*/
|
||||
blockProps?: (ctx: BlockPropsContext) => Promise<Record<string, unknown>> | Record<string, unknown>
|
||||
/** blockType → component (the project's registry). */
|
||||
blocks: BlockComponentMap
|
||||
@@ -97,7 +101,7 @@ export function createPageRoute(helpers: Helpers, options: PageRouteOptions) {
|
||||
<RenderBlocks
|
||||
blocks={doc[layoutField] as BlockData[] | undefined}
|
||||
components={blocks}
|
||||
enhanceProps={() => ({ locale, ...extra })}
|
||||
enhanceProps={({ index }) => ({ locale, ...extra, isFirst: index === 0 })}
|
||||
/>
|
||||
)
|
||||
const custom = render ? await render({ blocks: rendered, locale, route, segments }) : undefined
|
||||
@@ -142,7 +146,7 @@ export function createNotFoundPage(helpers: Helpers, options: NotFoundPageOption
|
||||
const fb = typeof fallback === 'function' ? fallback(locale) : fallback
|
||||
if (!doc || !layout?.length) {return [locale, fb] as const}
|
||||
const extra = blockProps ? await blockProps({ doc, locale }) : {}
|
||||
return [locale, <RenderBlocks blocks={layout} components={blocks} enhanceProps={() => ({ locale, ...extra })} key={locale} />] as const
|
||||
return [locale, <RenderBlocks blocks={layout} components={blocks} enhanceProps={({ index }) => ({ locale, ...extra, isFirst: index === 0 })} key={locale} />] as const
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
@@ -20,7 +20,7 @@ export type BuildLinkFieldOptions = {
|
||||
/** Field name. Default 'link'. */
|
||||
name?: string
|
||||
/** Collection the "Page" option points at. Default 'pages'. */
|
||||
relationTo?: string
|
||||
relationTo?: readonly string[] | string
|
||||
required?: boolean
|
||||
/** Upload collection for "File" links (PDF, documents). Default 'media'. */
|
||||
uploadTo?: string
|
||||
@@ -50,6 +50,7 @@ export function buildLinkField({
|
||||
required = false,
|
||||
uploadTo = 'media',
|
||||
}: BuildLinkFieldOptions = {}): GroupField {
|
||||
const pageAdmin = { condition: (_: unknown, s: SiblingWithType) => s?.type === 'internal' }
|
||||
const fields: Field[] = [
|
||||
{
|
||||
type: 'row',
|
||||
@@ -73,13 +74,10 @@ export function buildLinkField({
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'page',
|
||||
type: 'relationship',
|
||||
admin: { condition: (_: unknown, s: SiblingWithType) => s?.type === 'internal' },
|
||||
relationTo,
|
||||
required,
|
||||
},
|
||||
// One collection → plain relation; several (pages + content entries) → polymorphic.
|
||||
typeof relationTo === 'string'
|
||||
? { name: 'page', type: 'relationship', admin: pageAdmin, relationTo, required }
|
||||
: { name: 'page', type: 'relationship', admin: pageAdmin, relationTo: [...relationTo], required },
|
||||
{
|
||||
name: 'url',
|
||||
type: 'text',
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { I18nConfig } from '../i18n/index.js'
|
||||
|
||||
import { buildEntryPath } from '../content/paths.js'
|
||||
import { buildLocalizedPath } from '../i18n/index.js'
|
||||
|
||||
/**
|
||||
@@ -32,6 +33,12 @@ export type LinkValue = {
|
||||
}
|
||||
|
||||
export type ResolveLinkHrefOptions = {
|
||||
/**
|
||||
* Archive page slug per content collection in this locale (`{ categories: 'kategorie' }`) —
|
||||
* links to entries (buildLinkField({ relationTo: ['pages', 'categories'] })) become
|
||||
* /{locale}/{archive}/{entry}. getLinkOptions in lib/content fills it from Site Settings.
|
||||
*/
|
||||
archives?: Record<string, string>
|
||||
config: I18nConfig
|
||||
/**
|
||||
* Slug(s) of the homepage so it collapses to /{locale}. A per-locale map or a
|
||||
@@ -39,6 +46,8 @@ export type ResolveLinkHrefOptions = {
|
||||
*/
|
||||
homeSlug?: Record<string, string> | string
|
||||
locale: string
|
||||
/** The pages collection — links to it are page paths, other collections are entries. Default 'pages'. */
|
||||
pagesSlug?: string
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -54,7 +63,7 @@ export type ResolveLinkHrefOptions = {
|
||||
*/
|
||||
export function resolveLinkHref(
|
||||
link: LinkValue | null | undefined,
|
||||
{ config, homeSlug, locale }: ResolveLinkHrefOptions,
|
||||
{ archives, config, homeSlug, locale, pagesSlug = 'pages' }: ResolveLinkHrefOptions,
|
||||
): null | string {
|
||||
if (!link) {return null}
|
||||
|
||||
@@ -69,12 +78,22 @@ export function resolveLinkHref(
|
||||
return null
|
||||
}
|
||||
|
||||
// internal (default)
|
||||
const page = link.page
|
||||
// internal (default) — a page, or (polymorphic relation) an entry of a content collection
|
||||
let page = link.page
|
||||
let collection = pagesSlug
|
||||
if (page && typeof page === 'object' && 'relationTo' in page && 'value' in page) {
|
||||
collection = String((page as { relationTo: unknown }).relationTo)
|
||||
page = (page as { value: unknown }).value
|
||||
}
|
||||
if (!page || typeof page !== 'object') {return null}
|
||||
const slug = (page as { slug?: unknown }).slug
|
||||
if (typeof slug !== 'string' || !slug) {return null}
|
||||
|
||||
if (collection !== pagesSlug) {
|
||||
const archiveSlug = archives?.[collection]
|
||||
return archiveSlug ? buildEntryPath({ archiveSlug, entrySlug: slug, locale }) : null
|
||||
}
|
||||
|
||||
return (
|
||||
buildLocalizedPath({
|
||||
config,
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
type ProductPrice = {
|
||||
amount: number
|
||||
currency: string
|
||||
/** 'exact' → Offer.price; 'from' → minPrice (a starting price, not a promise). */
|
||||
kind?: 'exact' | 'from'
|
||||
}
|
||||
|
||||
type ProductJsonLdArgs = {
|
||||
/** schema.org availability, e.g. 'MadeToOrder', 'InStock'. Default 'InStock' when a price is given. */
|
||||
availability?: string
|
||||
brand?: string
|
||||
category?: string
|
||||
description?: string
|
||||
/** Absolute image URL. */
|
||||
image?: string
|
||||
name: string
|
||||
/** Only a real price from the panel — no price (on request) → no Offer at all. */
|
||||
price?: null | ProductPrice
|
||||
sku?: string
|
||||
/** Absolute URL of the product page (also its @id). */
|
||||
url: string
|
||||
}
|
||||
|
||||
/**
|
||||
* schema.org Product for a catalog entry: name, SKU, image, category, brand and —
|
||||
* only when the panel has one — an Offer. A product "on request" gets no Offer:
|
||||
* an invented or estimated price in structured data misleads search results.
|
||||
*
|
||||
* createContentHelpers({ pageJsonLd: { entries: {
|
||||
* products: ({ doc, url, image }) => buildProductJsonLd({ name: doc.title, sku: doc.sku, url, image, … }),
|
||||
* } } })
|
||||
*/
|
||||
export function buildProductJsonLd({
|
||||
name,
|
||||
availability,
|
||||
brand,
|
||||
category,
|
||||
description,
|
||||
image,
|
||||
price,
|
||||
sku,
|
||||
url,
|
||||
}: ProductJsonLdArgs): Record<string, unknown> {
|
||||
const offer =
|
||||
price && Number.isFinite(price.amount) && price.currency
|
||||
? {
|
||||
'@type': 'Offer',
|
||||
availability: `https://schema.org/${availability ?? 'InStock'}`,
|
||||
priceCurrency: price.currency,
|
||||
url,
|
||||
...(price.kind === 'from'
|
||||
? { priceSpecification: { '@type': 'PriceSpecification', minPrice: price.amount, priceCurrency: price.currency } }
|
||||
: { price: price.amount }),
|
||||
}
|
||||
: undefined
|
||||
return {
|
||||
name,
|
||||
'@context': 'https://schema.org',
|
||||
'@id': url,
|
||||
'@type': 'Product',
|
||||
url,
|
||||
...(sku ? { sku } : {}),
|
||||
...(description ? { description } : {}),
|
||||
...(image ? { image } : {}),
|
||||
...(category ? { category } : {}),
|
||||
...(brand ? { brand: { name: brand, '@type': 'Brand' } } : {}),
|
||||
...(offer ? { offers: offer } : {}),
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ export { buildMetadata } from './buildMetadata.js'
|
||||
export type { PageMetadata } from './buildMetadata.js'
|
||||
export { buildNoindexField } from './buildNoindexField.js'
|
||||
export { buildOrganizationJsonLd, sameAsUrls } from './buildOrganizationJsonLd.js'
|
||||
export { buildProductJsonLd } from './buildProductJsonLd.js'
|
||||
export { AI_ASSISTANT_BOTS, AI_TRAINING_BOTS, buildRobots } from './buildRobots.js'
|
||||
export type { RobotsOptions, RobotsRules } from './buildRobots.js'
|
||||
export { buildServiceJsonLd } from './buildServiceJsonLd.js'
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
type RemotePattern = { hostname: string; pathname?: string; port?: string; protocol?: 'http' | 'https' }
|
||||
|
||||
export type ImagesConfig = {
|
||||
/** Development only: lets next/image optimize files served by the app itself on localhost. */
|
||||
dangerouslyAllowLocalIP?: boolean
|
||||
formats: ('image/avif' | 'image/webp')[]
|
||||
minimumCacheTTL: number
|
||||
remotePatterns: RemotePattern[]
|
||||
@@ -11,15 +13,20 @@ export type ImagesConfig = {
|
||||
* - AVIF first, WebP fallback — ~20–50 % smaller than JPEG at the same quality;
|
||||
* - remotePatterns for the media domain (R2_PUBLIC_URL) so next/image may
|
||||
* optimize R2 files — otherwise it refuses them;
|
||||
* - optimized images cached for 31 days (uploads get new names when replaced).
|
||||
* - optimized images cached for 31 days (uploads get new names when replaced);
|
||||
* - outside production, media served by the app itself (`/api/media/file/**` on
|
||||
* NEXT_PUBLIC_SERVER_URL — local disk, no R2), including localhost, which
|
||||
* Next 16 otherwise refuses as a private IP.
|
||||
*
|
||||
* import { buildImagesConfig } from '@intecion/ipal-kit'
|
||||
* export default withPayload({ images: { ...buildImagesConfig(), /* your overrides *\/ } })
|
||||
*/
|
||||
export function buildImagesConfig({
|
||||
extraHosts = [],
|
||||
production = process.env.NODE_ENV === 'production',
|
||||
publicUrl = process.env.R2_PUBLIC_URL,
|
||||
}: { extraHosts?: string[]; publicUrl?: string } = {}): ImagesConfig {
|
||||
serverUrl = process.env.NEXT_PUBLIC_SERVER_URL,
|
||||
}: { extraHosts?: string[]; production?: boolean; publicUrl?: string; serverUrl?: string } = {}): ImagesConfig {
|
||||
const remotePatterns: RemotePattern[] = []
|
||||
if (publicUrl && /^https?:\/\//i.test(publicUrl)) {
|
||||
const u = new URL(publicUrl)
|
||||
@@ -31,5 +38,21 @@ export function buildImagesConfig({
|
||||
})
|
||||
}
|
||||
for (const host of extraHosts) {remotePatterns.push({ hostname: host, protocol: 'https' })}
|
||||
return { formats: ['image/avif', 'image/webp'], minimumCacheTTL: 60 * 60 * 24 * 31, remotePatterns }
|
||||
let localMedia = false
|
||||
if (!production && serverUrl && /^https?:\/\//i.test(serverUrl)) {
|
||||
const u = new URL(serverUrl)
|
||||
remotePatterns.push({
|
||||
hostname: u.hostname,
|
||||
protocol: u.protocol.replace(':', '') as 'http' | 'https',
|
||||
...(u.port ? { port: u.port } : {}),
|
||||
pathname: '/api/media/file/**',
|
||||
})
|
||||
localMedia = /^(?:localhost|127\.|10\.|192\.168\.|\[::1\])/.test(u.hostname)
|
||||
}
|
||||
return {
|
||||
formats: ['image/avif', 'image/webp'],
|
||||
minimumCacheTTL: 60 * 60 * 24 * 31,
|
||||
remotePatterns,
|
||||
...(localMedia ? { dangerouslyAllowLocalIP: true } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user