Built-in statistics (cookieless, consent-gated visitor history); per-page meta descriptions, NoSnippet
Stats: ipalKit({ stats: true }) adds the stats-visits collection, POST /api/ipal/hit, the
/admin/stats view (30-day visits chart, top/entry pages, referrers, devices), a dashboard card
and a nav link. <PageStats> (or <SiteProviders stats>) sends one beacon per page view. Without
consent nothing is stored on the device and no IP is kept: page views are joined by a hash with
an in-memory salt replaced daily. With analytics consent an ipal_vid cookie links visits across
days (server re-checks the consent cookie and policy version; withdrawal deletes the cookie).
Bots, logged-in panel users and prefetches aren't counted. Retention 90 days.
@payloadcms/next added to peerDependencies (DefaultTemplate). Docs: stats.md with privacy text.
Also in this release: meta.description auto-filled from page blocks, <NoSnippet>,
MetaDescriptionCheck in the SEO tab, data-nosnippet on banner/language switcher, GA4 CSP
wildcards, consent version passed to Analytics' default consent.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
305c564d13
commit
4ec27d9ef0
@@ -0,0 +1,122 @@
|
||||
'use client'
|
||||
import { useConfig, useDocumentInfo, useFormFields, useLocale } from '@payloadcms/ui'
|
||||
import { useEffect, useState } from 'react'
|
||||
|
||||
export type MetaDescriptionCheckProps = {
|
||||
/** An empty description is filled from the page content on save (autoFill). */
|
||||
autoFill?: boolean
|
||||
/** SiteSettings global slug. */
|
||||
settingsSlug?: string
|
||||
/** Field on SiteSettings holding the site-wide fallback description. */
|
||||
siteDescriptionField?: string
|
||||
/** Field shown as the name of the page that has the same description. */
|
||||
titleField?: string
|
||||
}
|
||||
|
||||
type Warning = { text: string; tone: 'info' | 'warn' }
|
||||
|
||||
const norm = (v: unknown) => (typeof v === 'string' ? v.trim().replace(/\s+/g, ' ') : '')
|
||||
|
||||
/**
|
||||
* Hint under the meta description in the SEO tab. Google ignores a description
|
||||
* it sees on many pages and quotes page text instead (usually the footer), so
|
||||
* this flags a description that matches the site-wide fallback or another
|
||||
* document in the collection. Advisory only — saving is never blocked. Length
|
||||
* is already shown by plugin-seo's own counter.
|
||||
*/
|
||||
export function MetaDescriptionCheck({
|
||||
autoFill = true,
|
||||
settingsSlug = 'site-settings',
|
||||
siteDescriptionField = 'siteDescription',
|
||||
titleField = 'title',
|
||||
}: MetaDescriptionCheckProps) {
|
||||
const description = norm(useFormFields(([f]) => f['meta.description']?.value))
|
||||
const { id, collectionSlug } = useDocumentInfo()
|
||||
const { code: locale } = useLocale()
|
||||
const {
|
||||
config: {
|
||||
routes: { api },
|
||||
serverURL,
|
||||
},
|
||||
} = useConfig()
|
||||
const [warning, setWarning] = useState<null | Warning>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!description) {
|
||||
setWarning(
|
||||
autoFill
|
||||
? { text: 'Empty — on save it is filled from this page’s content. Writing your own is better.', tone: 'info' }
|
||||
: { text: 'Empty — the page gets the site-wide description, the same as every other page.', tone: 'warn' },
|
||||
)
|
||||
return
|
||||
}
|
||||
if (!collectionSlug) {return}
|
||||
|
||||
const controller = new AbortController()
|
||||
const base = `${serverURL ?? ''}${api}`
|
||||
const get = async (url: string) => {
|
||||
const res = await fetch(url, { credentials: 'include', signal: controller.signal })
|
||||
return res.ok ? ((await res.json()) as Record<string, unknown>) : null
|
||||
}
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
void (async () => {
|
||||
try {
|
||||
const settings = await get(`${base}/globals/${settingsSlug}?depth=0&locale=${locale}`)
|
||||
if (settings && norm(settings[siteDescriptionField]) === description) {
|
||||
setWarning({
|
||||
text: 'Same as the site-wide description. Google ignores a description repeated across pages — write one about this page.',
|
||||
tone: 'warn',
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
const query = new URLSearchParams({
|
||||
depth: '0',
|
||||
limit: '1',
|
||||
locale,
|
||||
'where[meta.description][equals]': description,
|
||||
})
|
||||
if (id !== undefined && id !== null) {query.set('where[id][not_equals]', String(id))}
|
||||
const found = await get(`${base}/${collectionSlug}?${query}`)
|
||||
const twin = (found?.docs as Record<string, unknown>[] | undefined)?.[0]
|
||||
if (twin) {
|
||||
const name = norm(twin[titleField]) || String(twin.id)
|
||||
setWarning({
|
||||
text: `Same description as “${name}”. Google ignores a description repeated across pages — make each one unique.`,
|
||||
tone: 'warn',
|
||||
})
|
||||
return
|
||||
}
|
||||
setWarning(null)
|
||||
} catch {
|
||||
// aborted or offline — a hint is not worth an error
|
||||
}
|
||||
})()
|
||||
}, 600)
|
||||
|
||||
return () => {
|
||||
clearTimeout(timer)
|
||||
controller.abort()
|
||||
}
|
||||
}, [api, autoFill, collectionSlug, description, id, locale, serverURL, settingsSlug, siteDescriptionField, titleField])
|
||||
|
||||
if (!warning) {return null}
|
||||
|
||||
return (
|
||||
<div
|
||||
role="status"
|
||||
style={{
|
||||
background:
|
||||
warning.tone === 'warn' ? 'var(--theme-warning-50, rgba(255, 178, 36, 0.1))' : 'var(--theme-elevation-50)',
|
||||
border: `1px solid ${warning.tone === 'warn' ? 'var(--theme-warning-400, #ffb224)' : 'var(--theme-elevation-150)'}`,
|
||||
borderRadius: 4,
|
||||
fontSize: '0.85rem',
|
||||
marginBottom: '1.5rem',
|
||||
padding: '0.6rem 0.9rem',
|
||||
}}
|
||||
>
|
||||
{warning.text}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import type { HTMLAttributes, ReactNode } from 'react'
|
||||
|
||||
export type NoSnippetProps = {
|
||||
/**
|
||||
* Wrapper element. Only div, section and span — Google honours
|
||||
* `data-nosnippet` on those and ignores it on footer, nav, aside and the rest.
|
||||
* Default 'div'.
|
||||
*/
|
||||
as?: 'div' | 'section' | 'span'
|
||||
children?: ReactNode
|
||||
} & HTMLAttributes<HTMLElement>
|
||||
|
||||
/**
|
||||
* Keeps its contents out of Google's search snippets (`data-nosnippet`). The
|
||||
* text is still crawled and indexed — Google just won't quote it under a
|
||||
* result.
|
||||
*
|
||||
* Use it for text that repeats on every page: the footer's address, hours and
|
||||
* phone, a contact strip, a "book a visit" call to action. Google picks snippet
|
||||
* text itself when it thinks it fits the query better than the meta
|
||||
* description; for a brand search that is the contact block, so every sitelink
|
||||
* ends up showing the same address. The address stays available to Google
|
||||
* through the LocalBusiness JSON-LD.
|
||||
*
|
||||
* Never wrap <main> — that's the text the snippet should come from.
|
||||
*
|
||||
* <footer>
|
||||
* <NoSnippet>…address, hours, phone, links…</NoSnippet>
|
||||
* </footer>
|
||||
*/
|
||||
export function NoSnippet({ as: Tag = 'div', children, ...rest }: NoSnippetProps) {
|
||||
return (
|
||||
<Tag {...rest} data-nosnippet="">
|
||||
{children}
|
||||
</Tag>
|
||||
)
|
||||
}
|
||||
@@ -1,12 +1,22 @@
|
||||
import type { CollectionBeforeChangeHook } from 'payload'
|
||||
|
||||
import { blocksToMarkdown } from '../content/blocksToMarkdown.js'
|
||||
import { describeFromMarkdown } from './plainText.js'
|
||||
|
||||
/**
|
||||
* Maps document fields to SEO meta fields for auto-fill.
|
||||
* Defaults match the Payload website template (title → meta.title).
|
||||
*/
|
||||
export type AutoFillMapping = {
|
||||
/** Document field used to fill meta.description when empty. */
|
||||
/**
|
||||
* Block layout field to derive meta.description from when it's empty and the
|
||||
* `description` field gives nothing. Default 'layout'; false turns it off.
|
||||
*/
|
||||
content?: false | string
|
||||
/** Document field used to fill meta.description when empty. Tried before `content`. */
|
||||
description?: string
|
||||
/** Target length of a description derived from `content`. Default 155. */
|
||||
descriptionLength?: number
|
||||
/** Document field used to fill meta.title when empty. Default: 'title'. */
|
||||
title?: string
|
||||
}
|
||||
@@ -27,32 +37,49 @@ function readString(value: unknown): string | undefined {
|
||||
* editor typed. This runs server-side on every create/update, so editors get
|
||||
* sensible meta without clicking "auto-generate".
|
||||
*
|
||||
* Every page gets its own description: from the `description` field when one
|
||||
* is mapped, otherwise from the page's own blocks. Without it, pages fall back
|
||||
* to the one site-wide description, and Google — seeing the same text on every
|
||||
* page — ignores it and quotes the footer instead.
|
||||
*
|
||||
* The plugin doesn't know the client's collection shape, so the field mapping
|
||||
* is configurable; defaults follow the website template.
|
||||
*/
|
||||
export function buildAutoFillMetaHook(mapping: AutoFillMapping = {}): CollectionBeforeChangeHook {
|
||||
const titleField = mapping.title ?? 'title'
|
||||
const descriptionField = mapping.description
|
||||
const contentField = mapping.content === undefined ? 'layout' : mapping.content
|
||||
const descriptionLength = mapping.descriptionLength ?? 155
|
||||
|
||||
return ({ data }) => {
|
||||
return ({ data, originalDoc }) => {
|
||||
if (!data) {return data}
|
||||
|
||||
// plugin-seo stores meta as a group under `meta`
|
||||
const meta = (data.meta as Record<string, unknown> | undefined) ?? {}
|
||||
// A partial update (REST PATCH, payload.update with a few fields) carries
|
||||
// only what changed — read the rest from the stored document, so a saved
|
||||
// description isn't treated as empty and replaced.
|
||||
const stored = (originalDoc?.meta as Record<string, unknown> | undefined) ?? {}
|
||||
const current = (key: string) => (key in meta ? meta[key] : stored[key])
|
||||
const source = (field: string) => (field in data ? data[field] : originalDoc?.[field])
|
||||
|
||||
// Fill meta.title from the document title when empty
|
||||
if (!readString(meta.title)) {
|
||||
const sourceTitle = readString(data[titleField])
|
||||
if (!readString(current('title'))) {
|
||||
const sourceTitle = readString(source(titleField))
|
||||
if (sourceTitle) {meta.title = sourceTitle}
|
||||
}
|
||||
|
||||
// Fill meta.description from a configured field when empty
|
||||
if (descriptionField && !readString(meta.description)) {
|
||||
const sourceDescription = readString(data[descriptionField])
|
||||
// Fill meta.description from a configured field, else from the page content
|
||||
if (!readString(current('description'))) {
|
||||
const sourceDescription =
|
||||
(descriptionField && readString(source(descriptionField))) ||
|
||||
(contentField &&
|
||||
describeFromMarkdown(blocksToMarkdown(source(contentField)), descriptionLength)) ||
|
||||
undefined
|
||||
if (sourceDescription) {meta.description = sourceDescription}
|
||||
}
|
||||
|
||||
data.meta = meta
|
||||
if (data.meta !== undefined || Object.keys(meta).length) {data.meta = meta}
|
||||
return data
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { Field, FieldHook, TextareaField } from 'payload'
|
||||
|
||||
import { blocksToMarkdown } from '../content/blocksToMarkdown.js'
|
||||
import { mdToPlain, truncate } from './plainText.js'
|
||||
|
||||
type BuildSummaryFieldArgs = {
|
||||
/** Auto-fill from page content when the editor leaves it empty. Default true. */
|
||||
@@ -19,26 +20,6 @@ type BuildSummaryFieldArgs = {
|
||||
overrides?: Partial<TextareaField>
|
||||
}
|
||||
|
||||
/** Rough Markdown → plain text, enough for a summary (drops syntax, keeps words). */
|
||||
function mdToPlain(md: string): string {
|
||||
return md
|
||||
.replace(/!\[[^\]]*\]\([^)]*\)/g, '') // images
|
||||
.replace(/\[([^\]]*)\]\([^)]*\)/g, '$1') // links → their text
|
||||
.replace(/^#{1,6}\s+/gm, '') // heading markers
|
||||
.replace(/^[>\-*]\s+/gm, '') // quote/list markers
|
||||
.replace(/[*_~`]/g, '') // inline emphasis/code marks
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim()
|
||||
}
|
||||
|
||||
/** Truncate at a word boundary, adding an ellipsis when cut. */
|
||||
function truncate(text: string, max: number): string {
|
||||
if (text.length <= max) {return text}
|
||||
const slice = text.slice(0, max)
|
||||
const lastSpace = slice.lastIndexOf(' ')
|
||||
return `${(lastSpace > max * 0.6 ? slice.slice(0, lastSpace) : slice).trimEnd()}…`
|
||||
}
|
||||
|
||||
/**
|
||||
* A localized `aiSummary` textarea — a concise, human-written (or auto-derived)
|
||||
* description of the page, richer than the SEO meta description. It's the
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
/** Rough Markdown → plain text, enough for a summary (drops syntax, keeps words). */
|
||||
export function mdToPlain(md: string): string {
|
||||
return md
|
||||
.replace(/!\[[^\]]*\]\([^)]*\)/g, '') // images
|
||||
.replace(/\[([^\]]*)\]\([^)]*\)/g, '$1') // links → their text
|
||||
.replace(/^#{1,6}\s+/gm, '') // heading markers
|
||||
.replace(/^[>\-*]\s+/gm, '') // quote/list markers
|
||||
.replace(/[*_~`]/g, '') // inline emphasis/code marks
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim()
|
||||
}
|
||||
|
||||
/** Truncate at a word boundary, adding an ellipsis when cut. */
|
||||
export function truncate(text: string, max: number): string {
|
||||
if (text.length <= max) {return text}
|
||||
const slice = text.slice(0, max)
|
||||
const lastSpace = slice.lastIndexOf(' ')
|
||||
return `${(lastSpace > max * 0.6 ? slice.slice(0, lastSpace) : slice).trimEnd()}…`
|
||||
}
|
||||
|
||||
/** Ensure a fragment ends like a sentence, so joined fragments don't run together. */
|
||||
function terminate(text: string): string {
|
||||
return /[.!?…:]$/.test(text) ? text : `${text}.`
|
||||
}
|
||||
|
||||
/**
|
||||
* A meta description from a page's Markdown (blocksToMarkdown output).
|
||||
*
|
||||
* Headings are skipped while there's body text — they usually repeat the page
|
||||
* title, which Google already shows above the snippet. Whole sentences are
|
||||
* kept up to `max`; a first sentence longer than that is cut at a word
|
||||
* boundary. Returns '' when the content has no text.
|
||||
*/
|
||||
export function describeFromMarkdown(md: string, max = 155): string {
|
||||
const parts = md.split(/\n{2,}/).map((p) => p.trim()).filter(Boolean)
|
||||
const body = parts.filter((p) => !/^#{1,6}\s/.test(p) && !/^!\[/.test(p))
|
||||
const source = (body.length ? body : parts).map(mdToPlain).filter(Boolean).map(terminate)
|
||||
const text = source.join(' ')
|
||||
if (!text) {return ''}
|
||||
if (text.length <= max) {return text}
|
||||
|
||||
// Longest run of whole sentences that fits.
|
||||
const sentences = text.match(/[^.!?…]+[.!?…]+(?=\s|$)/g) ?? []
|
||||
let out = ''
|
||||
for (const s of sentences) {
|
||||
const next = `${out} ${s.trim()}`.trim()
|
||||
if (next.length > max) {break}
|
||||
out = next
|
||||
}
|
||||
return out || truncate(text, max)
|
||||
}
|
||||
@@ -25,6 +25,39 @@ const titleOverrideField: Field = {
|
||||
localized: true,
|
||||
}
|
||||
|
||||
/**
|
||||
* Admin hint right under meta.description (MetaDescriptionCheck): empty,
|
||||
* same as the site-wide description, or same as another document's.
|
||||
*/
|
||||
function descriptionCheckField(seo: SeoOption): Field | null {
|
||||
if (seo.descriptionCheck === false) {return null}
|
||||
const autoFill =
|
||||
seo.autoFill !== false && (seo.autoFill?.content !== false || Boolean(seo.autoFill?.description))
|
||||
return {
|
||||
name: 'descriptionCheck',
|
||||
type: 'ui',
|
||||
admin: {
|
||||
components: {
|
||||
Field: {
|
||||
clientProps: {
|
||||
autoFill,
|
||||
titleField: (seo.autoFill && seo.autoFill.title) || 'title',
|
||||
...(seo.descriptionCheck ?? {}),
|
||||
},
|
||||
path: '@intecion/ipal-kit/admin#MetaDescriptionCheck',
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/** Puts `extra` right after the description field (end of the group if it's missing). */
|
||||
function afterDescription(fields: Field[], extra: Field | null): Field[] {
|
||||
if (!extra) {return fields}
|
||||
const at = fields.findIndex((f) => 'name' in f && f.name === 'description')
|
||||
return at === -1 ? [...fields, extra] : [...fields.slice(0, at + 1), extra, ...fields.slice(at + 1)]
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures @payloadcms/plugin-seo from IPAL's SeoOption.
|
||||
*
|
||||
@@ -37,7 +70,11 @@ const titleOverrideField: Field = {
|
||||
export function buildSeoPlugin({ seo, uploadsCollection = 'media' }: BuildSeoPluginArgs): Plugin {
|
||||
return seoPlugin({
|
||||
collections: seo.collections,
|
||||
fields: ({ defaultFields }) => [...defaultFields, titleOverrideField, ...(seo.fields ?? [])],
|
||||
fields: ({ defaultFields }) => [
|
||||
...afterDescription(defaultFields, descriptionCheckField(seo)),
|
||||
titleOverrideField,
|
||||
...(seo.fields ?? []),
|
||||
],
|
||||
uploadsCollection,
|
||||
...(seo.generateTitle && { generateTitle: seo.generateTitle }),
|
||||
...(seo.generateDescription && { generateDescription: seo.generateDescription }),
|
||||
|
||||
@@ -17,6 +17,19 @@ export type SeoOption = {
|
||||
autoFill?: AutoFillMapping | false
|
||||
/** Collection slugs that receive SEO meta fields, e.g. ['pages', 'posts']. */
|
||||
collections: string[]
|
||||
/**
|
||||
* Hint under the meta description in the admin when it's empty, or the same
|
||||
* as the site-wide description or another document's. Advisory, never blocks
|
||||
* saving. Point it at your SiteSettings when the slugs differ; false hides it.
|
||||
*/
|
||||
descriptionCheck?:
|
||||
| {
|
||||
/** SiteSettings global slug. Default 'site-settings'. */
|
||||
settingsSlug?: string
|
||||
/** Field holding the site-wide description. Default 'siteDescription'. */
|
||||
siteDescriptionField?: string
|
||||
}
|
||||
| false
|
||||
/** Extra fields appended to the SEO group in the admin. */
|
||||
fields?: Field[]
|
||||
/** Optional: customize how meta descriptions are generated. */
|
||||
|
||||
Reference in New Issue
Block a user