Added module Links

This commit is contained in:
2026-10-13 18:04:37 +02:00
parent db05fe814b
commit 3d467d7350
57 changed files with 1786 additions and 777 deletions
+14 -5
View File
@@ -39,6 +39,12 @@ type ResolveRouteArgs = {
payload: BasePayload
/** Route segments after the locale, e.g. ['artykuly', 'moj-post']. */
segments?: string[]
/**
* SiteSettings already read for this locale (depth ≥ 1). Pass it to skip the
* read — createContentHelpers does, so layout, metadata and page share ONE
* settings query per request.
*/
settings?: null | Record<string, unknown>
/** SiteSettings global slug. Defaults to 'site-settings'. */
settingsSlug?: string
}
@@ -73,13 +79,16 @@ export async function resolveRoute({
pagesSlug = 'pages',
payload,
segments,
settings: preloaded,
settingsSlug = 'site-settings',
}: ResolveRouteArgs): Promise<null | ResolvedRoute> {
const settings = (await payload.findGlobal({
slug: settingsSlug,
depth: 1,
locale: locale as never,
})) as Record<string, unknown>
const settings =
preloaded ??
((await payload.findGlobal({
slug: settingsSlug,
depth: 1,
locale: locale as never,
})) as Record<string, unknown>)
// Locale root → Homepage from System Pages.
// settings.homepage is a shallow relation (depth: 1 above) — it identifies
+87 -11
View File
@@ -5,14 +5,10 @@ import { cache } from 'react'
import type { ArchiveEntries, ContentOption, ResolvedRoute } from '../content/index.js'
import type { I18nConfig } from '../i18n/index.js'
import type { RobotsRules, SitemapEntry } from '../seo/index.js'
import type { PageMetadata, RobotsOptions, RobotsRules, SitemapEntry } from '../seo/index.js'
import {
getArchiveEntries,
resolveNotFoundPage,
resolveRoute as resolveRouteRaw,
} from '../content/index.js'
import { buildRobots, buildSitemapEntries } from '../seo/index.js'
import { getArchiveEntries, resolveRoute as resolveRouteRaw } from '../content/index.js'
import { buildRobots, buildSitemapEntries, createPageMetadata } from '../seo/index.js'
type CreateContentHelpersArgs = {
/**
@@ -35,6 +31,12 @@ type CreateContentHelpersArgs = {
i18n?: I18nConfig
/** Pages collection slug. Defaults to 'pages'. */
pagesSlug?: string
/**
* Options for the ready-made `robots` handler, e.g.
* `{ disallowParams: ['s', 'meter'], aiBots: 'block-training' }`, or
* `{ adminRoute: false }` when the admin path is hidden (ipalKit adminRoute).
*/
robots?: RobotsOptions
/** SiteSettings global slug. Defaults to 'site-settings'. */
settingsSlug?: string
}
@@ -71,6 +73,7 @@ export function createContentHelpers({
content,
i18n,
pagesSlug = 'pages',
robots: robotsOptions,
settingsSlug = 'site-settings',
}: CreateContentHelpersArgs) {
const origin = baseUrl ?? process.env.NEXT_PUBLIC_SERVER_URL ?? ''
@@ -83,6 +86,10 @@ export function createContentHelpers({
return c.localization ? c.localization.locales.map((l) => l.code) : []
})
/**
* SiteSettings for a locale — ONE query per locale per request, shared by the
* layout, generatePageMetadata, resolveRoute and anything else that asks.
*/
const getSettings = cache(async (locale: string) => {
const payload = await getCachedPayload()
return payload.findGlobal({ slug: settingsSlug as never, depth: 2, locale: locale as never })
@@ -96,10 +103,70 @@ export function createContentHelpers({
page: number,
): Promise<null | ResolvedRoute> => {
const payload = await getCachedPayload()
return resolveRouteRaw({ content, locale, page, pagesSlug, payload, segments, settingsSlug })
const settings = (await getSettings(locale)) as Record<string, unknown>
return resolveRouteRaw({
content,
locale,
page,
pagesSlug,
payload,
segments,
settings,
settingsSlug,
})
},
)
/**
* generateMetadata for the catch-all page, sharing the request cache with
* the page component: the same settings read and the same resolveRoute call
* (React cache spans generateMetadata and the page within one request), so
* metadata costs no extra route/settings queries.
*
* export async function generateMetadata({ params }) {
* const { locale, slug } = await params
* return generatePageMetadata(locale, slug)
* }
*/
let pageMetadata: ReturnType<typeof createPageMetadata> | undefined
const generatePageMetadata = async (
locale: string,
segments: string[] | undefined,
page = 1,
): Promise<PageMetadata> => {
if (!i18n) {
throw new Error('[ipal] createContentHelpers: pass `i18n` to use generatePageMetadata.')
}
pageMetadata ??= createPageMetadata({
baseUrl: origin || undefined,
collection: pagesSlug,
config: i18n,
content,
loaders: {
getSettings: async (l) => (await getSettings(l)) as Record<string, unknown>,
resolveRoute,
},
settingsSlug,
})
return pageMetadata({ slug: segments, locale, page, payload: await getCachedPayload() })
}
/** ID of the page assigned as 404 — the relation isn't localized, so one read serves every locale. */
const getNotFoundPageId = cache(async (): Promise<null | number | string> => {
const payload = await getCachedPayload()
const settings = (await payload.findGlobal({
slug: settingsSlug as never,
depth: 0,
})) as { notFound?: unknown }
const rel = settings.notFound
if (typeof rel === 'string' || typeof rel === 'number') {return rel}
if (rel && typeof rel === 'object') {
const id = (rel as { id?: unknown }).id
if (typeof id === 'string' || typeof id === 'number') {return id}
}
return null
})
/**
* The page assigned as 404 in System Pages (or null → built-in fallback).
* For app/not-found.tsx; never throws. not-found.tsx receives no params and
@@ -108,10 +175,18 @@ export function createContentHelpers({
*/
const getNotFoundPage = cache(async (locale: string) => {
try {
const id = await getNotFoundPageId()
if (id === null) {return null}
const payload = await getCachedPayload()
return await resolveNotFoundPage({ locale, pagesSlug, payload, settingsSlug })
const doc = await payload.findByID({
id,
collection: pagesSlug as never,
depth: 2,
locale: locale as never,
})
return (doc as null | Record<string, unknown>) ?? null
} catch {
return null // DB unreachable (container build) — fallback view
return null // DB unreachable (container build) or page deleted — fallback view
}
})
@@ -186,7 +261,7 @@ export function createContentHelpers({
* export { robots as default } from '@/lib/content'
* ```
*/
const robots = (): RobotsRules => buildRobots({ baseUrl: origin })
const robots = (): RobotsRules => buildRobots({ ...robotsOptions, baseUrl: origin })
/**
* Next.js generateStaticParams for the [[...slug]] route (or
@@ -310,6 +385,7 @@ export function createContentHelpers({
}
return {
generatePageMetadata,
generateStaticParams,
getCachedPayload,
getConfiguredLocales,
+141
View File
@@ -0,0 +1,141 @@
import type { ArrayField, Field, GroupField } from 'payload'
export type LinkAppearance = 'link' | 'primary' | 'secondary'
export type BuildLinkFieldOptions = {
/** Visual styles the editor may pick. `false` → no appearance select. Default all three. */
appearances?: false | LinkAppearance[]
/** Hide the label — for links that wrap something (a whole card, an image). */
disableLabel?: boolean
/** Field name. Default 'link'. */
name?: string
/** Collection the "Page" option points at. Default 'pages'. */
relationTo?: string
required?: boolean
/** Upload collection for "File" links (PDF, documents). Default 'media'. */
uploadTo?: string
}
const URL_PATTERN = /^(https?:\/\/|mailto:|tel:|#)/
type SiblingWithType = { type?: string } | undefined
/**
* The ONE link shape for a project: a page, an external URL (also mailto:,
* tel:, #anchor) or an uploaded file — plus label, new-tab flag and visual
* style. Every CTA, card link and download in every block uses this field, so
* there is no zoo of ctaLabel / buttonUrl / pdfUrl fields and one renderer
* (resolveLinkHref + the project's CMSLink) handles them all.
*
* Generates a named TypeScript type `CmsLink` in payload-types.ts.
*
* fields: [buildLinkField()] // single link
* fields: [buildLinkField({ disableLabel: true, appearances: false })] // clickable card
*/
export function buildLinkField({
name = 'link',
appearances = ['primary', 'secondary', 'link'],
disableLabel = false,
relationTo = 'pages',
required = false,
uploadTo = 'media',
}: BuildLinkFieldOptions = {}): GroupField {
const fields: Field[] = [
{
type: 'row',
fields: [
{
name: 'type',
type: 'radio',
admin: { layout: 'horizontal', width: '50%' },
defaultValue: 'internal',
options: [
{ label: 'Page', value: 'internal' },
{ label: 'URL', value: 'external' },
{ label: 'File', value: 'file' },
],
},
{
name: 'newTab',
type: 'checkbox',
admin: { style: { alignSelf: 'flex-end' }, width: '50%' },
label: 'Open in new tab',
},
],
},
{
name: 'page',
type: 'relationship',
admin: { condition: (_: unknown, s: SiblingWithType) => s?.type === 'internal' },
relationTo,
required,
},
{
name: 'url',
type: 'text',
admin: {
condition: (_: unknown, s: SiblingWithType) => s?.type === 'external',
description: 'Full URL (https://…), mailto:, tel: or #section-anchor.',
},
required,
validate: (v: null | string | undefined) =>
!v || URL_PATTERN.test(v) || 'Use https://…, mailto:, tel: or #anchor',
},
{
name: 'file',
type: 'upload',
admin: {
condition: (_: unknown, s: SiblingWithType) => s?.type === 'file',
description: 'Upload a PDF / document / image. Never paste a file URL.',
},
relationTo: uploadTo,
required,
},
]
if (!disableLabel) {
fields.push({ name: 'label', type: 'text', localized: true, required })
}
if (appearances && appearances.length) {
fields.push({
name: 'appearance',
type: 'select',
defaultValue: appearances[0],
options: appearances.map((a) => ({ label: a, value: a })),
})
}
return {
name,
type: 'group',
admin: { hideGutter: true },
fields,
interfaceName: 'CmsLink',
}
}
export type BuildLinksFieldOptions = {
/** Max number of buttons. Default 2. */
maxRows?: number
/** Field name. Default 'links'. */
name?: string
} & Omit<BuildLinkFieldOptions, 'disableLabel' | 'name'>
/**
* 0..N buttons — use for every "CTA(s)" of a section. Each row holds one
* `link` (buildLinkField). Render: `links.map(({ id, link }) => <CMSLink … />)`.
*/
export function buildLinksField({
name = 'links',
maxRows = 2,
...linkOptions
}: BuildLinksFieldOptions = {}): ArrayField {
return {
name,
type: 'array',
admin: { initCollapsed: true },
fields: [buildLinkField(linkOptions)],
maxRows,
}
}
+4
View File
@@ -0,0 +1,4 @@
export { buildLinkField, buildLinksField } from './buildLinkField.js'
export type { BuildLinkFieldOptions, BuildLinksFieldOptions, LinkAppearance } from './buildLinkField.js'
export { resolveLinkHref } from './resolveLinkHref.js'
export type { LinkValue, ResolveLinkHrefOptions } from './resolveLinkHref.js'
+71
View File
@@ -0,0 +1,71 @@
import type { I18nConfig } from '../i18n/index.js'
import { buildLocalizedPath } from '../i18n/index.js'
/**
* Minimal shape of a link value (the project's generated `CmsLink` fits it).
* The plugin doesn't know the project's types — only this contract.
*/
export type LinkValue = {
appearance?: null | string
file?: unknown
label?: null | string
newTab?: boolean | null
page?: unknown
type?: 'external' | 'file' | 'internal' | null
url?: null | string
}
export type ResolveLinkHrefOptions = {
config: I18nConfig
/**
* Slug(s) of the homepage so it collapses to /{locale}. A per-locale map or a
* string. Usually from SiteSettings.homepage.
*/
homeSlug?: Record<string, string> | string
locale: string
}
/**
* Turns a link value (buildLinkField) into an href — the single place that
* knows the link types. Returns null when the link is empty or its target is
* missing in this locale (deleted page, page not populated, no file).
*
* Internal links need the related page POPULATED (block depth ≥ 2) — a bare ID
* resolves to null.
*
* resolveLinkHref(link, { locale, config: i18nConfig, homeSlug })
* // internal → '/en/about' · external → 'https://…' · file → media URL
*/
export function resolveLinkHref(
link: LinkValue | null | undefined,
{ config, homeSlug, locale }: ResolveLinkHrefOptions,
): null | string {
if (!link) {return null}
if (link.type === 'external') {return link.url?.trim() || null}
if (link.type === 'file') {
const file = link.file
if (file && typeof file === 'object' && 'url' in file) {
const url = (file as { url?: unknown }).url
return typeof url === 'string' && url ? url : null
}
return null
}
// internal (default)
const page = link.page
if (!page || typeof page !== 'object') {return null}
const slug = (page as { slug?: unknown }).slug
if (typeof slug !== 'string' || !slug) {return null}
return (
buildLocalizedPath({
config,
locale,
slugs: { [locale]: slug },
...(homeSlug ? { homeSlug } : {}),
}) ?? null
)
}
+39 -7
View File
@@ -30,7 +30,13 @@ export const AI_TRAINING_BOTS = [
type AiBotsPolicy = 'allow' | 'block-training' | 'disallow' | false
type BuildRobotsArgs = {
export type RobotsOptions = {
/**
* Admin path to disallow. Default '/admin'. With a hidden panel
* (ipalKit adminRoute) pass `false`: robots.txt is public, so listing the
* path would reveal it — the admin is noindex anyway.
*/
adminRoute?: false | string
/** Override the assistant/search bot list. */
aiAssistantAgents?: readonly string[]
/**
@@ -47,14 +53,29 @@ type BuildRobotsArgs = {
aiBots?: AiBotsPolicy
/** Override the training crawler list. */
aiTrainingAgents?: readonly string[]
/** Absolute origin, e.g. 'https://example.com'. */
baseUrl: string
/** Paths to disallow. Defaults to Payload's admin and API. */
/**
* Full disallow list — REPLACES the defaults ([adminRoute, '/api']). Prefer
* `extraDisallow` / `disallowParams`, which add to the defaults instead.
*/
disallow?: string[]
/**
* Query parameters whose URLs crawlers should skip (thin/duplicate pages that
* waste crawl budget), e.g. ['s', 'meter', 'utm_source']. Each becomes
* `/*?name=` and `/*&name=` (the parameter may not be first).
* Don't list `page` — paginated archives are real, canonical-to-self pages.
*/
disallowParams?: string[]
/** Paths added to the default disallow list, e.g. ['/koszyk']. */
extraDisallow?: string[]
/** Whether to advertise the sitemap. Defaults to true. */
sitemap?: boolean
}
type BuildRobotsArgs = {
/** Absolute origin, e.g. 'https://example.com'. */
baseUrl: string
} & RobotsOptions
/**
* Shape for Next's `app/robots.ts`. `rules` may be a single rule or an array
* (Next accepts both) — it becomes an array when AI-bot rules are added.
@@ -86,21 +107,32 @@ export type RobotsRules = {
* PerplexityBot, Google-Extended and friends. To keep AI answers but opt out of
* model training, use `aiBots: 'block-training'`. To block them all, 'disallow'.
*
* Pass custom disallow to block parametrized/thin URLs that waste crawl budget:
* Block parametrized/thin URLs that waste crawl budget — added to the defaults:
* ```ts
* buildRobots({ baseUrl, disallow: ['/admin', '/api', '/*?meter=*', '/*?s=*'] })
* buildRobots({ baseUrl, disallowParams: ['s', 'meter'] })
* // Disallow: /admin, /api, /*?s=, /*&s=, /*?meter=, /*&meter=
* ```
*/
export function buildRobots({
adminRoute = '/admin',
aiAssistantAgents = AI_ASSISTANT_BOTS,
aiBots = 'allow',
aiTrainingAgents = AI_TRAINING_BOTS,
baseUrl,
disallow = ['/admin', '/api'],
disallow: disallowOverride,
disallowParams = [],
extraDisallow = [],
sitemap = true,
}: BuildRobotsArgs): RobotsRules {
const origin = baseUrl.replace(/\/$/, '')
const defaults = [...(adminRoute ? [adminRoute] : []), '/api']
const paramRules = disallowParams
.map((p) => p.trim())
.filter(Boolean)
.flatMap((p) => [`/*?${p}=`, `/*&${p}=`])
const disallow = [...new Set([...(disallowOverride ?? defaults), ...extraDisallow, ...paramRules])]
const baseRule: RobotRule = { allow: '/', disallow, userAgent: '*' }
const aiRules: RobotRule[] = []
+36 -11
View File
@@ -1,6 +1,6 @@
import type { BasePayload } from 'payload'
import type { ContentOption } from '../content/index.js'
import type { ContentOption, ResolvedRoute } from '../content/index.js'
import type { I18nConfig } from '../i18n/index.js'
import type { PageMetadata } from './buildMetadata.js'
import type { SeoMeta } from './types.js'
@@ -22,6 +22,19 @@ type CreatePageMetadataArgs = {
* omit it and only pages are handled.
*/
content?: ContentOption
/**
* Request-cached loaders (createContentHelpers passes its own), so metadata
* reuses the SAME settings read and route resolution as the layout and the
* page component instead of querying again. Omit → plain queries.
*/
loaders?: {
getSettings?: (locale: string) => Promise<null | Record<string, unknown>>
resolveRoute?: (
locale: string,
segments: string[] | undefined,
page: number,
) => Promise<null | ResolvedRoute>
}
/** SiteSettings global slug. Defaults to 'site-settings'. */
settingsSlug?: string
/** Field on SiteSettings holding the site name. Defaults to 'siteName'. */
@@ -89,6 +102,7 @@ export function createPageMetadata(args: CreatePageMetadataArgs) {
collection = 'pages',
config,
content,
loaders,
settingsSlug = 'site-settings',
siteNameField = 'siteName',
} = args
@@ -99,7 +113,15 @@ export function createPageMetadata(args: CreatePageMetadataArgs) {
page,
payload,
}: PageMetadataContext): Promise<PageMetadata> {
const site = await readSiteMetaConfig({ locale, payload, settingsSlug, siteNameField })
const settings = loaders?.getSettings ? await loaders.getSettings(locale) : undefined
const site = await readSiteMetaConfig({
locale,
pagesSlug: collection,
payload,
settings,
settingsSlug,
siteNameField,
})
const base = {
baseUrl,
@@ -111,15 +133,18 @@ export function createPageMetadata(args: CreatePageMetadataArgs) {
siteName: site.siteName,
}
const route = await resolveRoute({
content,
locale,
page,
pagesSlug: collection,
payload,
segments: slug,
settingsSlug,
})
const route = loaders?.resolveRoute
? await loaders.resolveRoute(locale, slug, page ?? 1)
: await resolveRoute({
content,
locale,
page,
pagesSlug: collection,
payload,
segments: slug,
settings,
settingsSlug,
})
// Unknown route (the page component will 404) — still return something
// coherent rather than throwing during metadata generation.
+1 -1
View File
@@ -12,7 +12,7 @@ export type { PageMetadata } from './buildMetadata.js'
export { buildNoindexField } from './buildNoindexField.js'
export { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js'
export { AI_ASSISTANT_BOTS, AI_TRAINING_BOTS, buildRobots } from './buildRobots.js'
export type { RobotsRules } from './buildRobots.js'
export type { RobotsOptions, RobotsRules } from './buildRobots.js'
export { buildServiceJsonLd } from './buildServiceJsonLd.js'
export { buildSitemapEntries } from './buildSitemapEntries.js'
export type { SitemapEntry } from './buildSitemapEntries.js'
+13 -6
View File
@@ -35,22 +35,29 @@ export type SiteMetaConfig = {
*/
export async function readSiteMetaConfig({
locale,
pagesSlug = 'pages',
payload,
settings: preloaded,
settingsSlug = 'site-settings',
siteNameField = 'siteName',
}: {
locale: string
/** Collection holding the homepage. Default 'pages'. */
pagesSlug?: string
payload: BasePayload
/** SiteSettings already read for this locale (depth ≥ 1) — skips the read. */
settings?: null | Record<string, unknown>
settingsSlug?: string
siteNameField?: string
}): Promise<SiteMetaConfig> {
// depth 1 populates the homepage relationship, so its slug is available
// without a second query.
const settings = (await payload.findGlobal({
slug: settingsSlug as never,
depth: 1,
locale: locale as never,
})) as SettingsShape
const settings = (preloaded ??
(await payload.findGlobal({
slug: settingsSlug as never,
depth: 1,
locale: locale as never,
}))) as SettingsShape
const homepage =
settings.homepage && typeof settings.homepage === 'object' ? settings.homepage : null
@@ -64,7 +71,7 @@ export async function readSiteMetaConfig({
try {
const homeDoc = (await payload.findByID({
id: homepage.id,
collection: 'pages' as never,
collection: pagesSlug as never,
depth: 0,
locale: 'all' as never,
})) as { slug?: unknown }