Compare commits
@@ -25,3 +25,81 @@ jobs:
|
||||
- run: pnpm lint
|
||||
- run: pnpm test:int
|
||||
- run: pnpm build
|
||||
|
||||
# The reference site (reference/, docs/dev/reference-site-proposal.md). Fast part on every push and PR:
|
||||
# install against the freshly built plugin, committed generated files current, typecheck.
|
||||
reference:
|
||||
runs-on: ubuntu-latest
|
||||
needs: check
|
||||
env:
|
||||
PAYLOAD_SECRET: ci-reference-secret-0123456789abcdef
|
||||
DATABASE_URI: mongodb://127.0.0.1:27017/example-studiopl_dev
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 10
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile --ignore-scripts
|
||||
- run: pnpm build
|
||||
# file:.. + injected: the site gets a copy of the built plugin with its peers from the site (README.md)
|
||||
- run: pnpm --dir reference install --frozen-lockfile --ignore-workspace
|
||||
- run: pnpm --dir reference exec ipal-tokens --check
|
||||
- run: pnpm --dir reference generate:importmap && git diff --exit-code reference/src/app
|
||||
- run: pnpm --dir reference generate:types && git diff --exit-code reference/src/payload-types.ts
|
||||
- run: pnpm --dir reference typecheck
|
||||
# ipal-doctor (static, docs/doctor.md): the reference site is the zero-findings example — any unsilenced finding fails
|
||||
- run: node bin/ipal-doctor.mjs reference --strict --offline
|
||||
|
||||
# Full run on main (and before a release): MongoDB, seed, production build, smoke tests.
|
||||
reference-full:
|
||||
if: github.ref == 'refs/heads/main'
|
||||
runs-on: ubuntu-latest
|
||||
needs: reference
|
||||
services:
|
||||
mongo:
|
||||
image: mongo:7
|
||||
ports: ['27017:27017']
|
||||
env:
|
||||
CI: '1'
|
||||
DATABASE_URI: mongodb://127.0.0.1:27017/example-studiopl_dev
|
||||
PAYLOAD_SECRET: ci-reference-secret-0123456789abcdef
|
||||
NEXT_PUBLIC_SERVER_URL: http://localhost:3100
|
||||
IPAL_IP_HEADER: x-forwarded-for
|
||||
# cookieScanner.crawl → ipalEnvRules({ cookieCrawl }) requires both in production; CI never starts a crawl
|
||||
IPAL_COOKIE_SCAN_URL: http://127.0.0.1:9/crawl
|
||||
IPAL_COOKIE_SCAN_TOKEN: ci-cookie-scan-token-0123456789
|
||||
NEXT_PUBLIC_TURNSTILE_SITE_KEY: 1x00000000000000000000AA
|
||||
TURNSTILE_SECRET_KEY: 1x0000000000000000000000000000000AA
|
||||
ALLOW_LOCAL_MEDIA: '1'
|
||||
E2E_BASE_URL: http://localhost:3100
|
||||
E2E_ADMIN_EMAIL: [email protected]
|
||||
E2E_ADMIN_PASSWORD: ci-e2e-password-not-secret
|
||||
E2E_TOTP_SECRET: JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 10
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile --ignore-scripts
|
||||
- run: pnpm build
|
||||
- run: pnpm --dir reference install --frozen-lockfile --ignore-workspace
|
||||
- run: pnpm --dir reference seed
|
||||
# the documented production seed path (Coolify Terminal): one named record, dry run
|
||||
- run: SEED_ONLY="pages:kontakt" SEED_DRY_RUN=1 pnpm --dir reference seed
|
||||
- run: pnpm --dir reference payload run e2e/create-test-admin.ts
|
||||
- run: pnpm --dir reference build
|
||||
- run: pnpm --dir reference exec playwright install --with-deps chromium
|
||||
- run: pnpm --dir reference test:e2e
|
||||
# ipal-doctor (deep + HTTP): read-only database counts, the import map, the env rules, and the running site
|
||||
- run: |
|
||||
PORT=3100 pnpm --dir reference start &
|
||||
for i in $(seq 1 60); do curl -sf http://localhost:3100/api/health >/dev/null && break; sleep 2; done
|
||||
node bin/ipal-doctor.mjs reference --strict --offline --deep --url http://localhost:3100
|
||||
|
||||
@@ -53,3 +53,6 @@ next-env.d.ts
|
||||
|
||||
# build output — produced by `pnpm build` (prepare/prepublishOnly), not committed
|
||||
/dist
|
||||
|
||||
# pnpm starter:gate work folder
|
||||
.starter-gate/
|
||||
|
||||
@@ -61,16 +61,28 @@ quick throwaway test it works. But prefer the registry for real projects:
|
||||
Keep the git install only for pulling a specific unreleased commit during
|
||||
plugin development.
|
||||
|
||||
### A new site in one command
|
||||
|
||||
```bash
|
||||
pnpm --config.auto-install-peers=false dlx @intecion/ipal-kit@<version> create intecion.com
|
||||
```
|
||||
|
||||
Asks the architecture questions (or reads `--answers answers.json`), generates the site from the reference
|
||||
site with every team convention, installs it from a shipped lockfile and makes the first commit. Needs the
|
||||
`@intecion` registry line in `~/.npmrc`. Details: [docs/project-starter.md](./docs/project-starter.md).
|
||||
|
||||
---
|
||||
|
||||
## Finish setting up your project
|
||||
|
||||
`nodemailer`, `lucide-react`, `slugify` and `server-only` are regular
|
||||
`dependencies` of the plugin — they install with it; don't add them yourself.
|
||||
The plugin's `nodemailer` 10 needs **Node.js 20 or later**.
|
||||
The plugin's `nodemailer` 10 needs **Node.js 20 or later**; Payload 3.94 itself needs **Node.js 22.23.5 or later**
|
||||
on the 22 line.
|
||||
|
||||
What you provide are the **peer dependencies** — packages the plugin shares with
|
||||
your project — in a version matching your Payload:
|
||||
your project — in a version matching your Payload. The plugin accepts Payload `^3.90.2`; the reference site and the starter use
|
||||
**3.94.1** (with `react` / `react-dom` 19.3.1, which Payload 3.94 requires):
|
||||
|
||||
| Peer | Range | Notes |
|
||||
|---|---|---|
|
||||
@@ -81,16 +93,17 @@ your project — in a version matching your Payload:
|
||||
| `@payloadcms/storage-s3` | `^3.90.2` | optional — only when media go to Cloudflare R2 ([docs/storage.md](./docs/storage.md)) |
|
||||
|
||||
```bash
|
||||
pnpm add @payloadcms/[email protected]0.2 @payloadcms/[email protected]0.2 \
|
||||
pnpm add @payloadcms/[email protected]4.1 @payloadcms/[email protected]4.1 \
|
||||
@clocklimited/payload-2fa
|
||||
pnpm add @payloadcms/[email protected]0.2 # only with R2 media
|
||||
pnpm add @payloadcms/[email protected]4.1 # only with R2 media
|
||||
```
|
||||
|
||||
Keep every `@payloadcms/*` at exactly the same version as `payload`
|
||||
(`pnpm.overrides` — see PROGRAMISTA.md §1). Then run `pnpm audit --prod`: with
|
||||
`payload` 3.90.x, Payload's own tree pins a vulnerable `undici` and `dompurify` —
|
||||
add the two overrides from [AGENT.md §4 item 12](./docs/agent/AGENT.md) (recommended, not
|
||||
required by the plugin). Upload optimization and image
|
||||
(`pnpm.overrides` — see PROGRAMISTA.md §1). Then run `pnpm audit --prod`: even
|
||||
Payload 3.94.1 brings a vulnerable `happy-dom` (via Lexical) and `dompurify` — add
|
||||
the two overrides from [AGENT.md §4 item 12](./docs/agent/AGENT.md); an older Payload
|
||||
also needs the `mongoose` (MongoDB adapter, up to 3.93) and `undici` (up to 3.91)
|
||||
ones listed there (recommended, not required by the plugin). Upload optimization and image
|
||||
placeholders also use the `sharp` you pass to `buildConfig({ sharp })`
|
||||
(standard in a `create-payload-app` project).
|
||||
|
||||
@@ -111,6 +124,16 @@ have none) pointing the agent at the full guide: `AGENT.md`, the `ipal-reference
|
||||
(every option, env var, route and export) and the `ipal-setup` skill. Only the text between
|
||||
the markers is ever rewritten. `--no-pointer` skips that step. There is no `postinstall` script.
|
||||
|
||||
`pnpm exec ipal-skills --external` also adds a few well-known third-party skills as `ext-*` folders — Vercel's
|
||||
React best practices and composition patterns, Addy Osmani's accessibility skill, Anthropic's frontend-design
|
||||
skill and the official Payload 3 skill. They are vendored into the package at pinned commits (text only, each
|
||||
with its licence and source), so nothing is downloaded, and each starts with a note that ipal-kit's rules win.
|
||||
Pick some with `--external ext-accessibility,ext-payload`.
|
||||
|
||||
*Updating the pins (plugin maintainers):* change the commit in `scripts/vendor-external-skills.mjs`, run
|
||||
`node scripts/vendor-external-skills.mjs`, review `git diff docs/agent/external`, and run
|
||||
`pnpm vitest run test/externalSkills.test.ts`.
|
||||
|
||||
From here, the guide takes over: **[docs/dev/PROGRAMISTA.md](./docs/dev/PROGRAMISTA.md)** —
|
||||
from an empty project to a working site.
|
||||
|
||||
|
||||
Executable
+102
@@ -0,0 +1,102 @@
|
||||
#!/usr/bin/env node
|
||||
// ipal-blocks — the block library's command line.
|
||||
// pnpm exec ipal-blocks list → the library blocks
|
||||
// pnpm exec ipal-blocks eject faq → src/blocks/Faq/{config.ts,Component.tsx}
|
||||
// pnpm exec ipal-blocks eject faq --dest src/blocks --dry-run
|
||||
// Eject copies one block's source into the project, with its imports pointing at the
|
||||
// package entries, so the project owns it: same slug and data shape, no migration.
|
||||
// Then: use the ejected builder in Pages.layout instead of the library one, pass the ejected
|
||||
// component as createBlockRegistry({ components: { faq: FaqBlock } }), record it in AGENTS.md.
|
||||
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { dirname, join, relative, resolve } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const args = process.argv.slice(2)
|
||||
const [command, slug] = args
|
||||
const dryRun = args.includes('--dry-run')
|
||||
const destArg = args.indexOf('--dest')
|
||||
const dest = resolve(process.cwd(), destArg >= 0 ? args[destArg + 1] : 'src/blocks')
|
||||
|
||||
const pkgRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const libRoot = join(pkgRoot, 'src/modules/block-library')
|
||||
const blocksRoot = join(libRoot, 'blocks')
|
||||
|
||||
if (!command || command === '--help' || command === '-h') {
|
||||
console.log('Usage: ipal-blocks list | ipal-blocks eject <block> [--dest src/blocks] [--dry-run]')
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
const slugs = existsSync(blocksRoot) ? readdirSync(blocksRoot).sort() : []
|
||||
|
||||
if (command === 'list') {
|
||||
console.log(slugs.join('\n'))
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
if (command !== 'eject' || !slug) {
|
||||
console.error('Usage: ipal-blocks eject <block>')
|
||||
process.exit(1)
|
||||
}
|
||||
if (!slugs.includes(slug)) {
|
||||
console.error(`Unknown block "${slug}". Blocks: ${slugs.join(', ')}`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
/**
|
||||
* Where an import inside the library goes in a project, by the file it points at.
|
||||
* Config files (no React) take the Payload-side entries; components take /rsc and /client.
|
||||
*/
|
||||
const ROOT = '@intecion/ipal-kit'
|
||||
const BLOCKS = '@intecion/ipal-kit/blocks'
|
||||
const RSC = '@intecion/ipal-kit/blocks/rsc'
|
||||
function target(file, isComponent) {
|
||||
const rel = relative(join(pkgRoot, 'src/modules'), file).replace(/\\/g, '/').replace(/\.js$/, '')
|
||||
if (rel.startsWith('block-library/')) {
|
||||
const inner = rel.slice('block-library/'.length)
|
||||
if (/^(define|fields|options|shared|types|faq|library|manifest|thumbnails)$/.test(inner)) {return BLOCKS}
|
||||
return RSC // context, data, texts, ui/*
|
||||
}
|
||||
if (rel === 'lightbox/LightboxProvider' || rel === 'richtext/TableOfContents') {return '@intecion/ipal-kit/client'}
|
||||
if (rel === 'forms/RenderForm' || rel === 'richtext/RenderRichText') {return '@intecion/ipal-kit/rsc'}
|
||||
if (rel === 'richtext/headings') {return isComponent ? '@intecion/ipal-kit/rsc' : ROOT}
|
||||
return ROOT
|
||||
}
|
||||
|
||||
/** Rewrites relative imports to package entries and merges imports of the same entry. */
|
||||
function rewrite(source, file) {
|
||||
const isComponent = file.endsWith('.tsx')
|
||||
const merged = new Map()
|
||||
const body = source.replace(/^import (type )?\{([^}]*)\} from '(\.[^']+)'\n/gm, (_, type, names, spec) => {
|
||||
const entry = target(resolve(dirname(file), spec), isComponent)
|
||||
const key = `${type ? 'type ' : ''}${entry}`
|
||||
const set = merged.get(key) ?? new Set()
|
||||
for (const n of names.split(',').map((s) => s.trim()).filter(Boolean)) {set.add(n)}
|
||||
merged.set(key, set)
|
||||
return ''
|
||||
})
|
||||
const lines = [...merged].map(([key, set]) => {
|
||||
const [type, entry] = key.startsWith('type ') ? ['type ', key.slice(5)] : ['', key]
|
||||
return `import ${type}{ ${[...set].sort().join(', ')} } from '${entry}'`
|
||||
})
|
||||
return body.replace(/^((?:import [^\n]*\n)*)/, (head) => `${head}${lines.join('\n')}\n`).replace(/\n{3,}/g, '\n\n')
|
||||
}
|
||||
|
||||
const folder = slug[0].toUpperCase() + slug.slice(1)
|
||||
const outDir = join(dest, folder)
|
||||
const files = readdirSync(join(blocksRoot, slug)).filter((f) => /\.(ts|tsx)$/.test(f))
|
||||
for (const name of files) {
|
||||
const from = join(blocksRoot, slug, name)
|
||||
const to = join(outDir, name)
|
||||
if (existsSync(to)) {
|
||||
console.error(`skip ${relative(process.cwd(), to)} (exists — delete it first to eject again)`)
|
||||
continue
|
||||
}
|
||||
const out = `// Ejected from @intecion/ipal-kit (block library: ${slug}). The project owns this file now.\n${rewrite(readFileSync(from, 'utf8'), from)}`
|
||||
console.log(`${dryRun ? 'would write' : 'write'} ${relative(process.cwd(), to)}`)
|
||||
if (!dryRun) {
|
||||
mkdirSync(outDir, { recursive: true })
|
||||
writeFileSync(to, out)
|
||||
}
|
||||
}
|
||||
console.log(`\nNext: Pages.layout → the ejected build${folder}Block; registry → components: { ${slug}: ${folder}Block }; AGENTS.md → "Project decisions".`)
|
||||
Executable
+17
@@ -0,0 +1,17 @@
|
||||
#!/usr/bin/env node
|
||||
// ipal-doctor — checks a site against the ipal-kit team rules and lists every gap with a fix hint
|
||||
// (docs/doctor.md). Static by default: reads files, writes nothing (except a first-seen date in
|
||||
// ipal-doctor.json outside CI).
|
||||
// pnpm exec ipal-doctor → this project, human-readable
|
||||
// pnpm exec ipal-doctor --strict --offline → CI on a new site: any finding fails
|
||||
// pnpm exec ipal-doctor --deep --url http://localhost:3000
|
||||
// pnpm exec ipal-doctor --json > doctor.json
|
||||
// pnpm dlx --package=@intecion/ipal-kit@latest ipal-doctor → the newest rules
|
||||
// Exit: 0 ok · 1 findings · 2 could not run · 3 a rule crashed.
|
||||
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url'
|
||||
|
||||
const pkgRoot = join(dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const { runDoctorCli } = await import(pathToFileURL(join(pkgRoot, 'dist', 'modules', 'doctor', 'cli.js')).href)
|
||||
process.exit(await runDoctorCli(process.argv.slice(2), { packageRoot: pkgRoot }))
|
||||
Executable
+23
@@ -0,0 +1,23 @@
|
||||
#!/usr/bin/env node
|
||||
// ipal-kit — the plugin's command line.
|
||||
// pnpm dlx @intecion/ipal-kit@<version> create intecion.com → a new client site (docs/project-starter.md)
|
||||
// pnpm exec ipal-kit create intecion.com --dir ../intecioncom-web --answers answers.json
|
||||
// `pnpm dlx <package>` runs the bin named after the package, so every subcommand lives here.
|
||||
// The other tools keep their own bins: ipal-skills, ipal-blocks, ipal-tokens.
|
||||
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url'
|
||||
|
||||
const USAGE = `Usage: ipal-kit <command> [options]
|
||||
create <domain> a new client site from the reference site (ipal-kit create --help)
|
||||
|
||||
Other tools: ipal-skills, ipal-blocks, ipal-tokens`
|
||||
|
||||
const [command, ...args] = process.argv.slice(2)
|
||||
if (command !== 'create') {
|
||||
console.log(USAGE)
|
||||
process.exit(command === undefined || command === '--help' || command === '-h' ? 0 : 1)
|
||||
}
|
||||
const pkgRoot = join(dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const { runCreateCli } = await import(pathToFileURL(join(pkgRoot, 'dist', 'modules', 'starter', 'cli.js')).href)
|
||||
process.exit(await runCreateCli(args))
|
||||
+57
-3
@@ -4,22 +4,30 @@
|
||||
// pnpm ipal-skills --dry-run → show what would change
|
||||
// pnpm ipal-skills --dest .claude/skills
|
||||
// pnpm ipal-skills --no-pointer → skills only, leave AGENTS.md / CLAUDE.md alone
|
||||
// pnpm ipal-skills --external → also the vendored third-party skills (ext-*, pinned, text only)
|
||||
// pnpm ipal-skills --external ext-accessibility,ext-payload → only those
|
||||
// Only folders named ipal-* are touched; the project's own skills stay as they are.
|
||||
// ipal-* folders that no longer exist in the package are removed (renamed/retired skills).
|
||||
// ext-* folders are touched only with --external, and only those carrying ipal-kit's SOURCE.md.
|
||||
// AGENTS.md (and CLAUDE.md) get a marked ipal-kit block pointing at the guide — only the
|
||||
// text between the markers is ever rewritten; the project's own content stays as it is.
|
||||
|
||||
import { createHash } from 'node:crypto'
|
||||
import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
||||
import { dirname, join, relative, resolve } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const args = process.argv.slice(2)
|
||||
if (args.includes('--help') || args.includes('-h')) {
|
||||
console.log('Usage: ipal-skills [--dest <dir>] [--dry-run] [--no-pointer]\nDefault dest: .agents/skills')
|
||||
console.log('Usage: ipal-skills [--dest <dir>] [--dry-run] [--no-pointer] [--external [ext-a,ext-b]]\nDefault dest: .agents/skills')
|
||||
process.exit(0)
|
||||
}
|
||||
const dryRun = args.includes('--dry-run')
|
||||
const pointer = !args.includes('--no-pointer')
|
||||
const externalArg = args.indexOf('--external')
|
||||
const externalPick = externalArg >= 0 && args[externalArg + 1] && !args[externalArg + 1].startsWith('-')
|
||||
? args[externalArg + 1].split(',').map((n) => n.trim()).filter(Boolean)
|
||||
: null
|
||||
const destArg = args.indexOf('--dest')
|
||||
const destValue = destArg >= 0 ? args[destArg + 1] : '.agents/skills'
|
||||
// A missing value would resolve to cwd and remove every ipal-* folder there.
|
||||
@@ -40,6 +48,16 @@ if (!existsSync(src)) {
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
// Validate --external before anything is copied.
|
||||
const extSrc = join(pkgRoot, 'docs', 'agent', 'external')
|
||||
const manifest = externalArg >= 0 ? JSON.parse(readFileSync(join(extSrc, 'manifest.json'), 'utf8')) : { skills: [] }
|
||||
const known = manifest.skills.map((skill) => skill.name)
|
||||
const unknown = (externalPick ?? []).filter((name) => !known.includes(name))
|
||||
if (unknown.length) {
|
||||
console.error(`ipal-skills: unknown external skill(s): ${unknown.join(', ')} — available: ${known.join(', ')}`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const isSkillDir = (base, name) => name.startsWith('ipal-') && statSync(join(base, name)).isDirectory()
|
||||
const shipped = readdirSync(src).filter((n) => isSkillDir(src, n))
|
||||
const existing = existsSync(dest) ? readdirSync(dest).filter((n) => isSkillDir(dest, n)) : []
|
||||
@@ -60,6 +78,41 @@ for (const name of retired) {
|
||||
}
|
||||
console.log(`${dryRun ? '[dry-run] ' : ''}${shipped.length} skill(s) → ${dest}`)
|
||||
|
||||
// Third-party skills, vendored into the package at pinned commits (docs/agent/external,
|
||||
// scripts/vendor-external-skills.mjs). Nothing is downloaded here: every file is checked
|
||||
// against manifest.json before it is copied.
|
||||
if (externalArg >= 0) {
|
||||
const MARK = 'Vendored by @intecion/ipal-kit'
|
||||
const ours = (name) => existsSync(join(dest, name, 'SOURCE.md')) && readFileSync(join(dest, name, 'SOURCE.md'), 'utf8').includes(MARK)
|
||||
const filesOf = (dir) => readdirSync(dir).flatMap((n) => (statSync(join(dir, n)).isDirectory() ? filesOf(join(dir, n)).map((f) => `${n}/${f}`) : [n]))
|
||||
for (const skill of manifest.skills.filter((s) => !externalPick || externalPick.includes(s.name))) {
|
||||
const from = join(extSrc, skill.name)
|
||||
const files = filesOf(from).sort()
|
||||
const tampered = files.filter((f) => skill.files[f] !== createHash('sha256').update(readFileSync(join(from, f))).digest('hex'))
|
||||
if (tampered.length || files.length !== Object.keys(skill.files).length) {
|
||||
console.error(`ipal-skills: ${skill.name} does not match manifest.json (${tampered.join(', ') || 'file list'}) — skipped`)
|
||||
process.exitCode = 1
|
||||
continue
|
||||
}
|
||||
if (existsSync(join(dest, skill.name)) && !ours(skill.name)) {
|
||||
console.warn(`skip ${skill.name} (a folder of that name exists and is not from ipal-kit)`)
|
||||
continue
|
||||
}
|
||||
console.log(`${existsSync(join(dest, skill.name)) ? 'update' : 'add '} ${skill.name} (${skill.publisher}, ${skill.license}, ${skill.commit.slice(0, 12)})`)
|
||||
if (!dryRun) {
|
||||
rmSync(join(dest, skill.name), { recursive: true, force: true })
|
||||
cpSync(from, join(dest, skill.name), { recursive: true })
|
||||
}
|
||||
}
|
||||
const retiredExt = existsSync(dest)
|
||||
? readdirSync(dest).filter((n) => n.startsWith('ext-') && !known.includes(n) && ours(n))
|
||||
: []
|
||||
for (const name of retiredExt) {
|
||||
console.log(`remove ${name} (no longer in ipal-kit)`)
|
||||
if (!dryRun) rmSync(join(dest, name), { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
// Pointer block: an agent opening the project must find the guide without being told.
|
||||
// AGENTS.md is read by Codex/Cursor/Antigravity, CLAUDE.md by Claude Code (which also
|
||||
// follows `@AGENTS.md` imports, so a CLAUDE.md that imports AGENTS.md needs no copy).
|
||||
@@ -79,8 +132,9 @@ if (pointer) {
|
||||
`2. Everything the plugin provides (options, env vars, routes, layout, hooks, collections, globals, every export): the \`ipal-reference\` skill — \`${skillsDir}/ipal-reference/SKILL.md\`.`,
|
||||
`3. New project or missing foundation: the \`ipal-setup\` skill; a whole site: \`ipal-site\`. All skills: \`${skillsDir}/\`.`,
|
||||
'4. Module details: `node_modules/@intecion/ipal-kit/docs/<module>.md`.',
|
||||
'5. If the plugin has it, use it. If an option is missing, use the `ipal-plugin-gap` skill — never patch `node_modules`.',
|
||||
'6. ipal-kit docs, this guide and the skills are in English; write rules, AGENTS.md entries and gap reports in English.',
|
||||
'5. ipal-kit first: if the plugin has it, use it. Broken or not enough → report it with the `ipal-plugin-gap` skill and wait for the owner — no hand-built replacement, never patch `node_modules`.',
|
||||
'6. Before you set up a site: ask the owner the architecture questions (AGENT.md "Ask before you build") and wait for the answers; record them under "Project decisions".',
|
||||
'7. ipal-kit docs, this guide and the skills are in English; write rules, AGENTS.md entries and gap reports in English.',
|
||||
END,
|
||||
].join('\n')
|
||||
const upsert = (file, { create }) => {
|
||||
|
||||
Executable
+13
@@ -0,0 +1,13 @@
|
||||
#!/usr/bin/env node
|
||||
// ipal-tokens — the brand's design tokens: src/design/tokens.ts → src/design/tokens.css,
|
||||
// plus a WCAG contrast check (docs/design-tokens.md).
|
||||
// pnpm exec ipal-tokens → write src/design/tokens.css, print the contrast report
|
||||
// pnpm exec ipal-tokens --check → fail when the CSS is out of date (CI, ipal-doctor)
|
||||
// pnpm exec ipal-tokens --in x.ts --out y.css --warn-only
|
||||
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url'
|
||||
|
||||
const pkgRoot = join(dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const { runTokensCli } = await import(pathToFileURL(join(pkgRoot, 'dist', 'modules', 'tokens', 'cli.js')).href)
|
||||
process.exit(await runTokensCli(process.argv.slice(2)))
|
||||
@@ -15,6 +15,12 @@ export default async function LocaleLayout({ children, params }: Props) {
|
||||
<body>
|
||||
<SiteProviders banner={<CookieBanner controls="switch" equalChoice settings="detailed" />} logEndpoint="/api/ipal/consent" shell={await getSiteShell(locale)} stats={{ locale }}>
|
||||
<main>{children}</main>
|
||||
{/* A footer with links in the bottom-left corner: CookieButton must not cover them. */}
|
||||
<footer style={{ borderTop: '1px solid #e5e5e5', display: 'flex', gap: '1.5rem', marginTop: '60vh', padding: '1.5rem 1rem' }}>
|
||||
<a href={`/${locale}`}>Home</a>
|
||||
<a href={`/${locale}/kontakt`}>Kontakt</a>
|
||||
<a href={`/${locale}/polityka-prywatnosci`}>Polityka prywatności</a>
|
||||
</footer>
|
||||
</SiteProviders>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -34,6 +34,11 @@ import { IntegrationStatusBanner as IntegrationStatusBanner_7568fe47d582ff15ce85
|
||||
import { MaskedField as MaskedField_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
|
||||
import { TestEmailButton as TestEmailButton_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
|
||||
import { RowLabel as RowLabel_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
|
||||
import { CookieReviewTab as CookieReviewTab_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
|
||||
import { CookieSiteCheckTab as CookieSiteCheckTab_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
|
||||
import { AdminIcon as AdminIcon_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
|
||||
import { AdminLogo as AdminLogo_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
|
||||
import { IntecionCredit as IntecionCredit_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
|
||||
import { StatsNavLink as StatsNavLink_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
|
||||
import { CookieCrawlAlert as CookieCrawlAlert_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
|
||||
import { StatsWidget as StatsWidget_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
|
||||
@@ -41,6 +46,7 @@ import { IntegrationAlerts as IntegrationAlerts_7568fe47d582ff15ce85d2e1873c2c23
|
||||
import { TotpRedirectProvider as TotpRedirectProvider_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
|
||||
import { TOTPSetup as TOTPSetup_3eb2cc20d1a2569c2ccbafcee15bd128 } from '@clocklimited/payload-2fa/rsc'
|
||||
import { TOTPVerify as TOTPVerify_3eb2cc20d1a2569c2ccbafcee15bd128 } from '@clocklimited/payload-2fa/rsc'
|
||||
import { CookieApprovalView as CookieApprovalView_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
|
||||
import { StatsView as StatsView_7568fe47d582ff15ce85d2e1873c2c23 } from '@intecion/ipal-kit/admin'
|
||||
import { CollectionCards as CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1 } from '@payloadcms/next/rsc'
|
||||
|
||||
@@ -82,6 +88,11 @@ export const importMap = {
|
||||
"@intecion/ipal-kit/admin#MaskedField": MaskedField_7568fe47d582ff15ce85d2e1873c2c23,
|
||||
"@intecion/ipal-kit/admin#TestEmailButton": TestEmailButton_7568fe47d582ff15ce85d2e1873c2c23,
|
||||
"@intecion/ipal-kit/admin#RowLabel": RowLabel_7568fe47d582ff15ce85d2e1873c2c23,
|
||||
"@intecion/ipal-kit/admin#CookieReviewTab": CookieReviewTab_7568fe47d582ff15ce85d2e1873c2c23,
|
||||
"@intecion/ipal-kit/admin#CookieSiteCheckTab": CookieSiteCheckTab_7568fe47d582ff15ce85d2e1873c2c23,
|
||||
"@intecion/ipal-kit/admin#AdminIcon": AdminIcon_7568fe47d582ff15ce85d2e1873c2c23,
|
||||
"@intecion/ipal-kit/admin#AdminLogo": AdminLogo_7568fe47d582ff15ce85d2e1873c2c23,
|
||||
"@intecion/ipal-kit/admin#IntecionCredit": IntecionCredit_7568fe47d582ff15ce85d2e1873c2c23,
|
||||
"@intecion/ipal-kit/admin#StatsNavLink": StatsNavLink_7568fe47d582ff15ce85d2e1873c2c23,
|
||||
"@intecion/ipal-kit/admin#CookieCrawlAlert": CookieCrawlAlert_7568fe47d582ff15ce85d2e1873c2c23,
|
||||
"@intecion/ipal-kit/admin#StatsWidget": StatsWidget_7568fe47d582ff15ce85d2e1873c2c23,
|
||||
@@ -89,6 +100,7 @@ export const importMap = {
|
||||
"@intecion/ipal-kit/admin#TotpRedirectProvider": TotpRedirectProvider_7568fe47d582ff15ce85d2e1873c2c23,
|
||||
"@clocklimited/payload-2fa/rsc#TOTPSetup": TOTPSetup_3eb2cc20d1a2569c2ccbafcee15bd128,
|
||||
"@clocklimited/payload-2fa/rsc#TOTPVerify": TOTPVerify_3eb2cc20d1a2569c2ccbafcee15bd128,
|
||||
"@intecion/ipal-kit/admin#CookieApprovalView": CookieApprovalView_7568fe47d582ff15ce85d2e1873c2c23,
|
||||
"@intecion/ipal-kit/admin#StatsView": StatsView_7568fe47d582ff15ce85d2e1873c2c23,
|
||||
"@payloadcms/next/rsc#CollectionCards": CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1
|
||||
}
|
||||
|
||||
@@ -1238,7 +1238,7 @@ export interface SiteSetting {
|
||||
/**
|
||||
* Separates the page title from the site name in browser tabs.
|
||||
*/
|
||||
titleSeparator?: ('|' | '–' | '-' | '·' | '/') | null;
|
||||
titleSeparator?: ('pipe' | 'endash' | 'hyphen' | 'middot' | 'slash') | null;
|
||||
/**
|
||||
* Primary site logo.
|
||||
*/
|
||||
|
||||
@@ -76,6 +76,8 @@ export default buildConfig({
|
||||
// 2FA is enforced by default; the dev sandbox opts out so it boots without an authenticator.
|
||||
// IPAL_DEV_2FA=1 turns it on (first-login setup and verify screens).
|
||||
twoFactor: process.env.IPAL_DEV_2FA ? { issuer: 'ipal-kit dev', plugin: payloadTotp } : false,
|
||||
// Panel logo/icon from Site settings and the technology support credit.
|
||||
whiteLabel: true,
|
||||
}),
|
||||
],
|
||||
secret: process.env.PAYLOAD_SECRET || 'test-secret_key',
|
||||
|
||||
@@ -8,6 +8,687 @@ versions at once, go through every "Requires project changes" section in order,
|
||||
version you have. A new release = a new section at the top; we remove the oldest ones only
|
||||
once there are more than 20.
|
||||
|
||||
## 1.16.3
|
||||
|
||||
### Changed
|
||||
- **Payload 3.94.1** in the reference site and the project starter (was 3.90.2), with `react` / `react-dom` 19.3.1 and
|
||||
Node.js `>=22.23.5 <23` in the reference `engines`. The plugin is built and tested against 3.94.1; its peer range is
|
||||
unchanged (`^3.90.2`), so a project on 3.90.x is not forced to move. What Payload 3.91–3.94 change that a project
|
||||
notices: Node.js 22.23.5 or later (24.22.3 / 26.13.1 on newer lines), `react` ^19.3.1, Next.js 16.4.5 or later,
|
||||
`@payloadcms/db-mongodb` ships `mongoose` 8.24.7 (3.94.0), the `deepmerge` dependency is gone (3.94.1), field access
|
||||
now receives the document id, draft read access and block child read access are checked more strictly, and the slug
|
||||
field no longer fails required validation on create (a 3.90.2 bug). Nothing in the plugin needed a code change; the
|
||||
generated types and the import map of the reference site are unchanged.
|
||||
- **Overrides re-checked against Payload 3.94.1** (AGENT.md §4 item 12): `dompurify` and `happy-dom` are still needed
|
||||
(Lexical still brings `happy-dom` ^20.9.0: two highs). `mongoose` (MongoDB, Payload 3.90–3.93) and `undici` (Payload
|
||||
3.90–3.91) are needed only on an older Payload. **`graphql-scalars` needs no override any more**: GHSA-x8rm-f576-gq67
|
||||
now covers 1.24.1–2.0.0 only, and `@payloadcms/graphql` pins 1.22.2. The reference site and the starter keep only the
|
||||
`dompurify` and `happy-dom` lines.
|
||||
- **ipal-doctor `transitive-min`:** the `mongoose` finding names the Payload upgrade (3.94.1) as the first fix; the
|
||||
thresholds are unchanged.
|
||||
- Dependencies: `nodemailer` 10.6.1 (runtime). Dev tooling: Playwright 1.65.1 (run `pnpm exec playwright install
|
||||
chromium` once), Vitest 5.1.1, Prettier 3.10.1, `@swc/cli` 0.8.2 (with `piscina` 4.9.4 and `@xhmikosr/decompress` 11: clears the two critical dev
|
||||
advisories), `vite` 7.3.8 as a direct dev dependency (Vitest's peer; clears the vite high), `rimraf` 6,
|
||||
`cross-env` 10 (also in the reference site), `open` 11, `sort-package-json` 4, `@swc-node/register` 1.12.1,
|
||||
`vite-tsconfig-paths` 6.1.1, Tailwind 4.3.5 and PostCSS 8.5.33 in the reference site. `pnpm audit` of the plugin's
|
||||
dev tree: 31 → 4 (0 critical, 0 high; what is left sits under `drizzle-kit` and the ESLint toolchain). `--prod` stays
|
||||
at 0, and the reference site at 0.
|
||||
- Kept back, with the reason: TypeScript 7 (typescript-eslint supports TypeScript below 6.1 only), ESLint 10
|
||||
(`eslint-config-next` 16.4.6 plugins do not support it — the lint run crashes), `graphql` 17 (Payload requires
|
||||
^16.8.1), `@types/node` 26 (projects stay on Node 22), `lucide-react` 1.x (a runtime dependency: projects are told to
|
||||
keep their own lucide on 0.400.x; moving needs its own change and icon-map checks).
|
||||
|
||||
### What projects must update
|
||||
- **Nothing is required.** The plugin still works with Payload 3.90.2 and later.
|
||||
- **Recommended — move to Payload 3.94.1** (the `ipal-upgrade` skill, "Every upgrade — Payload"): every `payload` /
|
||||
`@payloadcms/*` to 3.94.1 (in `dependencies` and `pnpm.overrides`), `react` and `react-dom` 19.3.1, Node.js 22.23.5
|
||||
or later (`"engines": { "node": ">=22.23.5 <23" }`, `.nvmrc` stays `22`), `pnpm install`, `pnpm payload generate:types`,
|
||||
`pnpm payload generate:importmap`, `rm -rf .next`, build, redeploy on Coolify. Postgres/SQLite: run
|
||||
`pnpm payload migrate:create` and commit it if it is not empty (Payload 3.94.1 changes how long index and foreign
|
||||
key names are built). MongoDB: no migration.
|
||||
- **Node.js 22.23.5 or later everywhere the site runs — before you move to Payload 3.94.** Payload 3.94 refuses older
|
||||
Node (`engines`: `^22.23.5 || ^24.22.3 || >=26.13.1`). Locally: `node -v`. **Coolify:** Nixpacks picks the Node major
|
||||
from `engines` / `.nvmrc`, and the patch version comes from the Nixpacks release on the server — so after the first
|
||||
deploy open the app → Terminal and run `node -v` (the build log shows it too). If it is below 22.23.5, update Coolify
|
||||
(newer Nixpacks) before you deploy Payload 3.94; until then, stay on 3.90.x. CI images (`node:22` / `setup-node`
|
||||
with `22`) must resolve to 22.23.5 or later as well.
|
||||
- **Overrides** (`pnpm.overrides`): on 3.94.x keep `"dompurify@<3.4.17": "^3.4.17"` and
|
||||
`"happy-dom@<21.0.4": "^21.0.4"`; the `mongoose` and `undici` lines do nothing there — remove them. Remove
|
||||
`"graphql-scalars@<2.0.1": "^2.0.1"` if you have it (optional). Sites that stay on 3.90–3.93 keep the 1.16.2 lines.
|
||||
- **Verify:** `pnpm ls payload` → 3.94.1; `pnpm audit --prod` → no high or critical; `pnpm exec ipal-doctor` → no
|
||||
`versions` finding; the panel opens and a document saves; a form submission arrives.
|
||||
- `pnpm ipal:skills` for the updated `ipal-setup` / `ipal-upgrade` skills.
|
||||
|
||||
## 1.16.2
|
||||
|
||||
### Security
|
||||
- **`mongoose` and `happy-dom` overrides for Payload's own dependencies.** `@payloadcms/db-mongodb` pins `mongoose`
|
||||
8.24.1 exactly (still so in Payload 3.93.0). 8.x below 8.24.7 has five advisories published 2026-11-10:
|
||||
[GHSA-pcrw-h46h-c93h](https://github.com/advisories/GHSA-pcrw-h46h-c93h) (critical, `sanitizeFilter` not applied on
|
||||
`countDocuments`; fixed in 8.24.3), [GHSA-gg4r-jv3p-qx3c](https://github.com/advisories/GHSA-gg4r-jv3p-qx3c) and
|
||||
[GHSA-8332-j7wj-wjw4](https://github.com/advisories/GHSA-8332-j7wj-wjw4) (high),
|
||||
[GHSA-wr5m-5jph-8m96](https://github.com/advisories/GHSA-wr5m-5jph-8m96) and
|
||||
[GHSA-6972-9mcm-vhwj](https://github.com/advisories/GHSA-6972-9mcm-vhwj) (moderate) — all fixed in 8.24.7.
|
||||
`@payloadcms/richtext-lexical` → `@lexical/headless` 0.50 brings `happy-dom` 20.x, which has
|
||||
[GHSA-c8p4-j97h-3vg8](https://github.com/advisories/GHSA-c8p4-j97h-3vg8) (high, fixed in 21.0.0) and
|
||||
[GHSA-834v-8h66-3h79](https://github.com/advisories/GHSA-834v-8h66-3h79) (high, fixed in 21.0.4). The plugin has no
|
||||
part in either; only the project's lockfile can lift them. The reference site and the project starter now carry
|
||||
`"mongoose@>=8 <8.24.7": "~8.24.10"` and `"happy-dom@<21.0.4": "^21.0.4"` in `pnpm.overrides`; with them
|
||||
`pnpm audit --prod` on the reference site reports no known vulnerabilities, and its seed, production build, smoke
|
||||
tests and doctor pass. The plugin forces neither override on a project.
|
||||
|
||||
### Added
|
||||
- **ipal-doctor `transitive-min`** (group `versions`): reports a `mongoose` 8.x below 8.24.7 (error) and a `happy-dom`
|
||||
below 21.0.4 (warning) anywhere in the dependency tree, read from `pnpm-lock.yaml`, and prints the exact
|
||||
`pnpm.overrides` line. Silence it in `ipal-doctor.json` like any rule
|
||||
(`"transitive-min": { "off": true, "reason": "…" }`). `DoctorContext.installedAll(name)` is the building block for
|
||||
your own rules on transitive packages.
|
||||
|
||||
### Changed
|
||||
- AGENT.md §4 item 12, the `ipal-setup` and `ipal-upgrade` skills, doctor.md and the README list five overrides.
|
||||
|
||||
### What projects must update
|
||||
- **Every MongoDB site** (`@payloadcms/db-mongodb`): add the two lines to `pnpm.overrides` in `package.json`, next to
|
||||
the existing `dompurify` / `graphql-scalars` / `undici` entries:
|
||||
```json
|
||||
"happy-dom@<21.0.4": "^21.0.4",
|
||||
"mongoose@>=8 <8.24.7": "~8.24.10"
|
||||
```
|
||||
then `pnpm install`, `pnpm build`, commit `package.json` and `pnpm-lock.yaml`, redeploy on Coolify. No data change,
|
||||
no migration, no import map change. The selectors only touch the vulnerable versions: a mongoose 9 or a mongoose
|
||||
8.24.7 and later is left as it is.
|
||||
- **Postgres / SQLite sites:** only the `happy-dom` line (they have no mongoose).
|
||||
- **Verify:** `pnpm why mongoose happy-dom` → mongoose 8.24.10 (MongoDB sites), happy-dom 21.0.4; `pnpm audit --prod` →
|
||||
no high or critical; `pnpm exec ipal-doctor` → no `transitive-min` finding; open the panel and save a document.
|
||||
- `pnpm ipal:skills` for the updated `ipal-setup` / `ipal-upgrade` skills.
|
||||
|
||||
## 1.16.1
|
||||
|
||||
### Security
|
||||
- **Next.js 16.4.6; the minimum safe version is now 16.4.5.** Next.js 16.3.0–16.4.4 is affected by
|
||||
[GHSA-mfr8-8qww-v76h](https://github.com/advisories/GHSA-mfr8-8qww-v76h) (CVE-2026-119790, moderate): information
|
||||
disclosure across root params when a `'use cache'` function is called through `unstable_cache()`. Fixed in 16.4.5.
|
||||
This is the advisory behind the `pnpm dev` warning "Next.js 16.4.3 is affected by a known security vulnerability".
|
||||
The plugin's dev dependencies (`next`, `eslint-config-next`), the reference site and the project starter move to
|
||||
16.4.6. The Next.js 15 lines Payload 3.90 accepts are not affected by this advisory but still carry older critical
|
||||
ones, so 16.4.x stays the only safe line. The plugin's peer range is unchanged (`next >=15`).
|
||||
|
||||
### Changed
|
||||
- **ipal-doctor `next-min`** now reports `next` below 16.4.5 as an error, naming GHSA-mfr8-8qww-v76h (below 16.4.1 it
|
||||
still names the RCE and DoS advisories). The fix it prints: `pnpm add next@16.4.6 eslint-config-next@16.4.6`. It can
|
||||
be silenced in `ipal-doctor.json` as before (`"next-min": { "off": true, "reason": "…" }`).
|
||||
- AGENT.md §4 item 11, the `ipal-setup` and `ipal-upgrade` skills and doctor.md state 16.4.5 as the minimum.
|
||||
|
||||
### What projects must update
|
||||
- **Every client site below Next.js 16.4.5:** `pnpm add next@16.4.6 eslint-config-next@16.4.6`, `rm -rf .next`,
|
||||
`pnpm build`, commit the lockfile and redeploy on Coolify. `pnpm ls next` → 16.4.6; `pnpm exec ipal-doctor` → no
|
||||
`next-min` finding; `pnpm dev` prints no security warning. No plugin option, migration or import map change.
|
||||
- `pnpm ipal:skills` brings the updated `ipal-setup` / `ipal-upgrade` skills.
|
||||
|
||||
## 1.16.0
|
||||
|
||||
### Added
|
||||
- **Files on forms, sent by e-mail and never stored** (`forms: { attachments: true }`, [forms.md](./forms.md) "Files").
|
||||
A new **File** field in the form builder: label and help text per language, required, allowed file types,
|
||||
maximum size and number of files, "Show only when". A file a visitor attaches is checked, attached to the
|
||||
company notification e-mail and dropped. There is no upload collection, bucket, disk write or download route;
|
||||
the submission keeps the file's name, type and size and whether the mail server took the message.
|
||||
- **Checks, in order, before a file is accepted:** same origin, rate limit, declared size, a concurrency guard,
|
||||
honeypot, Turnstile, field validation and GDPR consent, then per file: count, name (double and refused
|
||||
extensions), size while reading, content signature, container and macro checks. An upload that breaks off,
|
||||
stalls (`submit.idleTimeoutMs`, 30 s) or runs too long (`submit.timeoutMs`, 5 minutes) is given up and frees
|
||||
everything it held. Programs, scripts,
|
||||
macro-enabled Office files, archives, HTML and SVG are refused unless the project allows the extension
|
||||
(`allowRisky`). **No antivirus is built in** — `attachments.scan` is the hook for one.
|
||||
- **E-mail:** the file goes to every e-mail of the form whose recipients are fixed addresses from the panel; an
|
||||
e-mail addressed with a placeholder (the confirmation to the visitor) never carries it. `{{field}}`, `{{*}}` and
|
||||
`{{*:table}}` show the file name.
|
||||
- **The visitor is told when the problem is the file:** too large (with the limit), a format the field does not
|
||||
take (with the formats), a refused file (a program, an archive, macros, content that does not match), too many
|
||||
files, or a file that could not be e-mailed. Each message names the file, says what to do, shows at the File
|
||||
field, and on an optional field adds "You can also send the form without the file." What the visitor typed
|
||||
stays in the form. A failure that is not about the file keeps its own message.
|
||||
- **A failed send is visible:** the visitor sees "We could not send the file …" and can retry, staff get the
|
||||
notification without the file, the submission is marked **File delivery: Not sent**. A repeated request
|
||||
(double click, a resend) sends nothing twice.
|
||||
- Browser: `RenderForm` / `BuilderForm` render a native file input with help text, the list of picked files and
|
||||
a "Remove" button; `useBuilderForm` gains `getFileProps`, `getFiles`, `removeFile`, `helpId`,
|
||||
`getHoneypotProps`; new `classNames` keys `file`, `help`, `fileList`, `fileItem`, `fileRemove`.
|
||||
- New texts in Form messages → **Files** (`fileTooLarge`, `fileType`, `fileRefused`, `fileCount`, `fileNotSent`,
|
||||
`fileOptional`, `fileRemove`), English and Polish defaults.
|
||||
- New exports: `buildFileBlock`, `fileBlock`, `FORM_FILE_TYPES`, `RISKY_FILE_EXTENSIONS`, `formatFileSize`,
|
||||
`mailAttachmentLimit` (root); `fileFieldRules`, `fileFieldError`, `formatFileSize` (`/client`);
|
||||
`splitFormFiles` (`/server`); `submitForm({ files, attemptKey })`; result codes `kind: 'file_too_large' |
|
||||
'file_type' | 'file_refused' | 'file_count'` and `reason: 'delivery'`.
|
||||
- **Attachments over both e-mail transports** ([email.md](./email.md) "Attachments"). SMTP passes them through.
|
||||
Microsoft Graph sends attachments under 3 MB in the one `sendMail` call; larger ones go through a draft and an
|
||||
upload session, and the copy the mailbox keeps is deleted afterwards. That path needs the `Mail.ReadWrite`
|
||||
application permission (limit it to the forms mailbox — steps in email.md). Without the permission the message
|
||||
goes over SMTP when the panel has SMTP settings; otherwise the form's file limit drops to about 2.8 MB.
|
||||
`mailAdapter({ graph: { largeAttachments: false } })` turns the large path off.
|
||||
- **Test e-mail with a 10 MB file:** a checkbox next to "Send test e-mail" (endpoint body `attachmentMB`) — shows
|
||||
whether the mail server takes a file of that size.
|
||||
|
||||
### Fixed
|
||||
- **A form can be sent again after the server refused it.** After a refused submission (a field error from the
|
||||
server, a failed e-mail) `useTurnstile().reset()` cleared the token but never asked the widget for a new one, so
|
||||
with Turnstile on, the next click on Send answered "The form could not be sent" without sending anything.
|
||||
`reset()` now makes the widget issue a new token (`Turnstile` takes a `resetSignal` prop for your own wiring).
|
||||
No project change.
|
||||
- **The honeypot of `BuilderForm` / `RenderForm` now reaches the server.** The hidden field was rendered, but its
|
||||
value was not part of what the form sent, so a bot that filled it was not dropped. It is now sent with the
|
||||
submission (`createSubmitAction` checks and strips it, as before). A hand-written action that calls `submitForm`
|
||||
directly must strip `HONEYPOT_FIELD` first, as the example in forms.md always did — otherwise a filled honeypot
|
||||
is answered with "unknown field" instead of the fake success.
|
||||
|
||||
### Changed
|
||||
- The Microsoft Graph access token is cached in the process until a minute before it expires (it was fetched on
|
||||
every send).
|
||||
|
||||
### What projects must update
|
||||
- **Nothing is required; existing forms need nothing.** Without `forms.attachments` the forms config, collections,
|
||||
routes and e-mails are unchanged, and a form without a File field behaves as before even with the option on.
|
||||
`pnpm ipal:skills` brings the updated `ipal-form` / `ipal-reference` skills.
|
||||
- **Import map:** no new admin component — `pnpm payload generate:importmap` changes nothing (running it is harmless).
|
||||
- To use files on forms: set `forms: { attachments: true }`, add a **File** field to the form (panel or seed), keep
|
||||
one e-mail with a fixed recipient on that form, run `pnpm generate:types`. **Postgres / SQLite:**
|
||||
`pnpm payload migrate:create` (the File block tables, three columns and one array table on submissions, the new
|
||||
Form messages columns — all additive). MongoDB: no migration.
|
||||
- Add the classes `file`, `help`, `fileList`, `fileItem`, `fileRemove` to `src/components/forms/formClasses.ts`
|
||||
(template in the `ipal-form` skill) and fill Form messages → Files for languages other than English and Polish.
|
||||
- **Proxy body limit** ([deployment.md](./deployment.md) "Form files"): the browser posts up to `maxTotalMB`
|
||||
(10 MB) plus the answers to `/api/ipal/forms/submit`. Coolify's Traefik and Caddy have no body limit by default; an
|
||||
nginx in front needs `client_max_body_size 12m;`; Cloudflare (proxied) allows 100 MB. Keep `/api` out of the i18n
|
||||
proxy matcher (the default one does).
|
||||
- **Mail transport for files:** with Microsoft Graph, grant `Mail.ReadWrite` (application permission) limited to the
|
||||
forms mailbox with an application access policy ([email.md](./email.md)), **or** fill SMTP settings in Site
|
||||
integrations (files of 3 MB and more then go over SMTP), **or** accept a limit of about 2.8 MB per form. With SMTP
|
||||
only, nothing to grant — the mail server's own size limit applies. Send the test e-mail with the 10 MB file once
|
||||
per site.
|
||||
|
||||
### Verify on your real systems
|
||||
The plugin's tests use a mock of Microsoft Graph and a local mail sink; check these once on the real setup:
|
||||
- [ ] **Graph, 10 MB file:** a form submission with a 10 MB file arrives with the attachment; the sender mailbox keeps
|
||||
**no draft and no copy in Sent Items** a minute later, and no draft after a failed send either. Checklist:
|
||||
[email.md](./email.md) "Verify on the real tenant".
|
||||
- [ ] **Traefik timeout on a slow upload:** a 10 MB upload over a throttled connection (browser dev tools, "Slow 4G")
|
||||
finishes; if it is cut, raise the entry point's `respondingTimeouts.readTimeout`.
|
||||
- [ ] **SMTP size limit:** the test e-mail with the 10 MB file is accepted by the SMTP server (many limit a message to
|
||||
10–25 MB, and base64 adds a third); if not, lower `maxSizeMB` / `maxTotalMB` or use Graph.
|
||||
|
||||
## 1.15.5
|
||||
|
||||
### Fixed
|
||||
- **Seeding a required field with references** (`createSeeder`, `upsertBySlug` / `upsertBy`): a page whose required
|
||||
`layout` holds a `{ $page }` or `{ $form }` reference can be created. The first pass used to leave the whole field out,
|
||||
so validation rejected the record ("The following field is invalid: … > Layout") while the dry run reported a create.
|
||||
Now references to records that exist are resolved in the first pass, so the field is written complete. A link to a
|
||||
page created later in the same call is filled in the second pass, and a record whose required field needs that page
|
||||
waits until it exists. Required links in a cycle, and links to a page or form that never appears, are an error with
|
||||
nothing written. The dry run now reports the same outcome, including a missing form. Seed scripts need no change.
|
||||
|
||||
### Changed
|
||||
- **A stricter dry run:** `SEED_DRY_RUN=1` with a `{ $form }` to a form that neither exists nor is seeded earlier in the
|
||||
same run is now an error, as the real run would be (before, the dry run printed a placeholder and reported a create).
|
||||
The same holds for a `{ $page }` that never appears.
|
||||
|
||||
### What projects must update
|
||||
- Nothing is required: seed scripts need no change.
|
||||
- A seed with a required reference cycle (two new pages whose required fields link to each other) now stops with a
|
||||
clear error naming the pages, and nothing is written for them; make one of the links optional or seed one page
|
||||
first. Before, such a run could look successful in the dry run and fail on validation in the real one.
|
||||
- A dry run that now reports a missing form or page: seed that record first (or create it in the panel), then run again.
|
||||
|
||||
## 1.15.4
|
||||
|
||||
### Fixed
|
||||
- **Seeding whole localized arrays** (`createSeeder`, `writeLocales`): a value written per language as a whole —
|
||||
`fields: { pl: [...], en: [...], de: [...] }`, a page `layout`, a global array — now keeps the stored row ids in every
|
||||
language. Before, each locale write made new shared rows and only the last language survived (form fields, nested
|
||||
select options, layouts, global arrays); an editor's later save could then fail validation. Fields that are
|
||||
themselves `localized: true` (a localized layout) keep rows per language, as before. Seed scripts need no change;
|
||||
repairing records an earlier seed already wrote: "What projects must update".
|
||||
|
||||
### What projects must update
|
||||
- Nothing is required: seed scripts need no change.
|
||||
- A project that seeded whole localized arrays (form fields with options, a page `layout`, a global array written as
|
||||
`{ pl: [...], en: [...] }`) and lost languages: a plain re-run skips existing records (create-only), so rewrite them
|
||||
with `SEED_UPDATE=1` — **locally first**, then check every language in the panel. On a live site only for the named
|
||||
records: `SEED_ONLY="forms:<title>,pages:<slug>" SEED_UPDATE=1 IPAL_SEED_ALLOW_PROD_UPDATE=1`, `SEED_DRY_RUN=1` first,
|
||||
after a backup (Coolify). Records an editor changed since seeding are skipped — fix those in the panel. A global
|
||||
array: `fillGlobal` fills empty fields only, so clear the field in the panel before the run, or fix it by hand.
|
||||
|
||||
## 1.15.3
|
||||
|
||||
### Fixed
|
||||
- **ipal-audit and ipal-doctor no longer report the panel's own bilingual labels as hardcoded text.** "Hardcoded Polish
|
||||
text in code" (`i18n-literals` in the doctor) flagged `adminText('Title', 'Tytuł')` and `{ en: 'Title', pl: 'Tytuł' }`,
|
||||
the labels AGENT.md §6.5a asks for. The check now reads the syntax tree (`polish-literals.mjs`, with the project's
|
||||
TypeScript; a plain grep without it). In a schema file — a `.ts` file under `collections/`, `globals/`, `fields/` or
|
||||
`blocks/`, or one importing Payload's schema types — it accepts `adminText()`, `{ en, pl }` as `label`, `singular`,
|
||||
`plural`, `description`, `placeholder` or `group`, a `rowLabel()` fallback and a `const x: AdminText`, also over several
|
||||
lines. Still reported: every `.tsx` file, a Polish-only label, other keys, anything under `defaultValue`.
|
||||
|
||||
### What projects must update
|
||||
- Nothing is required.
|
||||
- Run `pnpm ipal:skills` after upgrading, so the updated audit scripts reach the project: the **ipal-audit** skill runs
|
||||
the project's own copy in `.agents/skills/ipal-audit/scripts` (`audit.sh`, `polish-literals.mjs`); `ipal-doctor` already
|
||||
uses the plugin's.
|
||||
|
||||
## 1.15.2
|
||||
|
||||
### Fixed
|
||||
- **ipal-doctor finds the frontend by structure, not by the name `(frontend)`.** A site with its pages in another route
|
||||
group (`src/app/(site)/[locale]`) was treated as single-language: false "missing" routes and a demand for the
|
||||
single-language Markdown route. `layout-required` now takes any `app/(<group>)` (or `app` itself) that holds the
|
||||
catch-all page, a localized one first; two candidates give a warning naming both. The lazy 404's server action may be
|
||||
`notFoundView.ts` or `notFoundView.tsx` (pages.md), and the other required files accept their usual extensions
|
||||
(`.ts`/`.tsx`, route `.js`). New: `ipal-doctor.json` `"layout": { "frontend": "src/app/(site)" }` for a layout the
|
||||
doctor cannot tell; new export `findFrontend`.
|
||||
|
||||
### What projects must update
|
||||
- Nothing is required.
|
||||
- After upgrading, remove any temporary `layout-required` silence in `ipal-doctor.json` that was added for a route group
|
||||
with another name (e.g. `(site)`) or a `notFoundView.tsx`, then run `pnpm exec ipal-doctor` again. Only if the doctor
|
||||
reports two frontend candidates: set `"layout": { "frontend": "src/app/(<group>)" }`.
|
||||
- `pnpm ipal:skills` for the updated `ipal-doctor` and `ipal-reference` skills.
|
||||
|
||||
## 1.15.1
|
||||
|
||||
A seed run that stops early now fails loudly instead of looking like a success.
|
||||
|
||||
### New
|
||||
- `guardSeedExit()` in `@intecion/ipal-kit/seed` ([seeding.md](./seeding.md)): call it first in a seed script. A run that
|
||||
ends before Payload initializes or before `summary()` — `payload run` exits with code 0 and no output when the
|
||||
script's top-level await is left without anything that keeps Node running — now prints `[seed] ended before Payload
|
||||
initialized` / `… before the seed finished` and exits 1. `createSeeder` and `summary()` report to it; normal runs, dry
|
||||
runs, write errors and the production refusals keep their exit codes and messages. Also `activeSeedExitGuard()` and
|
||||
the types `SeedExitGuard`, `SeedExitGuardOptions`, `SeedExitProcess`.
|
||||
- The seed templates (`ipal-site`, `ipal-form`) and the reference site call it, so sites made with `ipal-kit create` have it.
|
||||
|
||||
### Changed
|
||||
- Reference site (not shipped): the Playwright smoke tests start their own server and fail when the port is taken
|
||||
(`reuseExistingServer` only with `E2E_REUSE_SERVER=1`), so another project's dev server is never tested by mistake.
|
||||
|
||||
### What projects must update
|
||||
- Nothing is required.
|
||||
- Recommended: add `guardSeedExit()` (imported from `@intecion/ipal-kit/seed`) as the first statement of every seed
|
||||
script, before `getPayload()`; without it nothing changes. A guarded script must end with `seed.summary()` (the seed
|
||||
templates do), otherwise it exits 1 as "ended before the seed finished".
|
||||
- **Check in Coolify:** after a seed in the app's Terminal, `echo $?` must print `0`; `1` with a `[seed] ended …` line
|
||||
means the run stopped early and nothing after that point was written — run it again.
|
||||
- `pnpm ipal:skills` for the updated `ipal-site` / `ipal-form` seed templates and `ipal-reference`.
|
||||
|
||||
|
||||
## 1.15.0
|
||||
|
||||
A new site in one command (`ipal-kit create`), built from a complete reference site; `ipal-doctor`, which checks any site
|
||||
against the team rules; a design-token standard; a block library of fifteen ready page sections and ten page templates.
|
||||
Database names follow one rule, and seeding a live site touches only the records you name. Everything new is opt-in for
|
||||
existing sites, except the few changes listed under "What projects must update".
|
||||
|
||||
### New
|
||||
- **`ipal-doctor`** ([doctor.md](./doctor.md)): one command, run in a site, that checks it against the team rules and
|
||||
lists every gap with a fix hint — plugin/Next/sharp/Node versions, the AGENT.md §3 layout and naming, database names,
|
||||
env rules, security headers, X-Powered-By, CSP, 2FA, the cookie scanner, adminMeta, AGENTS.md "Project decisions",
|
||||
current skills, seeds (`createSeeder`, no deletes, guard on), the block library (`blockLibraryManifest`), `pnpm audit
|
||||
--prod`, hardcoded texts (it runs `ipal-audit --quick`). `--url` checks the running site (and runs `ipal-seo-check`),
|
||||
`--deep` reads the database read-only through `payload run`. Human or `--json` output, `--strict`, exit codes 0/1/2/3,
|
||||
`--sites '../*-web'` for a read-only drift table. `ipal-doctor.json` silences, lowers or raises a rule with a reason
|
||||
(`until`, `files`). New bin `ipal-doctor`, new entry `@intecion/ipal-kit/doctor`, new skill **ipal-doctor**.
|
||||
- **`GET /api/ipal/doctor`**: read-only counts for the doctor (users without TOTP, cookies waiting for approval,
|
||||
versions). 404 until `IPAL_DOCTOR_TOKEN` (≥ 32 characters) is set; Bearer token, rate-limited. `ipalKit({ doctor: false })`
|
||||
removes it.
|
||||
- **`ipal-kit create` — a new site in one command** ([project-starter.md](./project-starter.md)):
|
||||
`pnpm --config.auto-install-peers=false dlx @intecion/ipal-kit@<version> create intecion.com` asks the architecture
|
||||
questions (or reads `--answers answers.json`), generates the site from the reference site (`reference/` through
|
||||
`starter.manifest.json`: placeholders, `@starter:if` variants, demo left out), writes the answers into `AGENTS.md` →
|
||||
Project decisions and `ipal-doctor.json`, installs from a shipped lockfile, runs `ipal-skills`, `ipal-tokens`,
|
||||
`generate:types`, `generate:importmap`, `typecheck`, checks for secrets and makes the first commit. New bin `ipal-kit`
|
||||
(subcommand `create`), new entry `@intecion/ipal-kit/starter` with the building blocks (`renderSite`,
|
||||
`validateAnswers`, `applyVariants`, `collectBundle` …). New scripts `build:starter` and `starter:gate` in
|
||||
`prepublishOnly`: a site made from the packed tarball must install frozen, seed, build, run the targeted seed in
|
||||
production mode and serve `/pl` before a publish. Adds ~180 KB to the tarball. Not yet: single-language sites and a
|
||||
default language other than `pl` — the command stops and points to the manual `ipal-setup` path.
|
||||
- **Design-token standard** ([design-tokens.md](./design-tokens.md)): one set of `--ipal-*` names for every site,
|
||||
only the values differ per brand. `@intecion/ipal-kit/tokens.css` (neutral defaults, light/dark on `data-theme`,
|
||||
`[data-surface="inverse"]` scope, reduced motion), `@intecion/ipal-kit/tailwind.css` (Tailwind 4 preset: `bg-surface`,
|
||||
`text-fg`, `text-on-primary`, `py-section`, `rounded-card`, `duration-fast`…), `@intecion/ipal-kit/a11y.css` (the
|
||||
accessibility widget's CSS through the tokens). New entry `@intecion/ipal-kit/tokens` (`defineTokens`, `tokensToCss`,
|
||||
`contrastReport`, `fluidClamp`, `IPAL_TOKENS`, `ipalVar`, `IPAL_BREAKPOINTS` …; the first four names also from the root).
|
||||
New bin `ipal-tokens`: `src/design/tokens.ts` → `src/design/tokens.css` + WCAG contrast check (`--check` for CI).
|
||||
Templates `DESIGN.md` and `tokens.ts` in `ipal-setup/resources`. `ipal-audit` checks the standard.
|
||||
- `fluid.css` / `fluid-wide.css`: `--ipal-fs-xs`, `--ipal-fs-h4`, `--ipal-space-stack`, `--ipal-space-section-sm`.
|
||||
- Design tokens: `data-theme="dark"` / `"light"` switches the tokens on any element (a dark panel, a styleguide), not
|
||||
only on `<html>` (`LIGHT_SELECTOR`, `DARK_SELECTOR`). Inside an inverted section `primary` reads the new
|
||||
`primary-inverse` / `primary-inverse-text` roles (default: the brand primary), and the contrast report checks primary
|
||||
buttons there. The `ipal-form` `formClasses.ts` template uses the token utilities and `buttonClass()`.
|
||||
- **Block library** ([block-library.md](./block-library.md)): `hero`, `textMedia`, `featureGrid`, `cta`, `richText`, `faq`,
|
||||
`contact`, `gallery`, `testimonials`, `stats`, `steps`, `logos`, `team`, `pricing`, `entryList` — Payload block +
|
||||
server component each, `{ en, pl }` panel, accessibility built in, styled only with design-token utilities.
|
||||
Opt in per block: `libraryBlocks({ hero: true, … })` (`@intecion/ipal-kit/blocks`); render with
|
||||
`createBlockRegistry(content, { Image, Link, sendForm })` (`@intecion/ipal-kit/blocks/rsc`). Nothing is on by default.
|
||||
Override fields, variants, slugs, labels, part classes, primitives or whole components; own blocks share the registry.
|
||||
- **Page templates:** `pageTemplates` (`@intecion/ipal-kit/templates`) — home, about, services, service, contact, blog
|
||||
index, post, legal pages, cookie policy, 404 — as `createSeeder` data in English and Polish; `systemPageRefs`.
|
||||
- **`ipal-blocks eject <block>`** copies a library block into `src/blocks/` (same slug and data shape).
|
||||
- **`blockLibraryManifest`** — the library's blocks, variants, fields and primitives as data, for checks.
|
||||
- **Seeder:** `{ $form: 'Contact form' }` references (by title, `formsCollection`, default `forms`).
|
||||
- **Database name rule:** `<domain without dots>_prod` / `_dev` (e.g. `acmepl_prod`), docs/deployment.md.
|
||||
`ipalEnvRules({ databaseName: true })` (domain from `NEXT_PUBLIC_SERVER_URL`, skipped on localhost) or
|
||||
`{ databaseName: { domain, warn } }` checks `DATABASE_URI` and **warns only** — never fails startup. Default off.
|
||||
Helpers: `databaseNamesFor(domain)`, `databaseNameFromUri(uri)`, `checkDatabaseName({ databaseUri, domain })`.
|
||||
- **Seeding after launch:** `createSeeder(payload, { only })` / `SEED_ONLY="pages:kontakt,global:header"` (also
|
||||
`forms:<title>`, `pages:*`) — the run touches only the listed records; the rest are reported as
|
||||
`skip (not listed)`. The seed templates (`ipal-site`, `ipal-form`) read it.
|
||||
- **Reference site for agents:** `docs/agent/reference-site/INDEX.md` (shipped) maps every plugin feature to a file
|
||||
in a complete example site built on ipal-kit, so an agent can copy a working pattern. The site itself lives in the
|
||||
plugin repo (`reference/`, not shipped) and is built, seeded and smoke-tested in the plugin's CI.
|
||||
- **2FA screens in plain English and Polish:** `TOTP_TEXTS` (en, pl) go over `@clocklimited/payload-2fa`'s texts, and
|
||||
the setup / verify screens get a tab title (`TOTP_VIEW_TITLE`, in the site's default language) instead of
|
||||
"Payload". The project's own `i18n.translations.<lang>.totpPlugin` still wins, a view's own `meta.title` stays, and
|
||||
`twoFactor: { …, texts: false }` keeps the package's texts. The admin language still follows the browser.
|
||||
- **`<CookieButton>` stays clear of the footer:** when the footer scrolls into view the button moves up above it
|
||||
(`avoid`, default `COOKIE_BUTTON_AVOID` = `footer, [role="contentinfo"]`; `avoid={false}` turns it off), `side`
|
||||
(`'left'` default / `'right'`), position tokens `--ipal-cookie-button-inset`; `bottomOverlap` for your own widget.
|
||||
Type `CookieButtonProps`.
|
||||
|
||||
### Fixed
|
||||
- Meta descriptions, `/md` pages and `llms-full.txt` now read the **section header** of blocks
|
||||
(`header: { heading, intro }` from `buildSectionHeaderField`, every library block) and testimonial `quote`s
|
||||
(`blocksToMarkdown`). Before, a page whose text sat only in its hero (an archive page, a form page, the 404) got no
|
||||
auto-filled meta description and fell back to the site description — the same text on several pages, which Google
|
||||
ignores. **Requires project changes:** none; pages saved before keep their stored description — re-save them (or seed
|
||||
`meta.description`) to fill an empty one.
|
||||
- **Block library — headings and the LCP image** (found by `ipal-doctor` live-seo on the archive pages): item headings
|
||||
follow the section — `h3` under a section heading, `h2` when the block shows none (an entry list under the page header
|
||||
no longer jumps `h1` → `h3`); override with `createBlockRegistry({ itemHeadings: { entryList: 'h3' } })`. The first
|
||||
image of the block that leads the page loads eagerly with high priority — `createPageRoute` now passes `firstImage`
|
||||
("no block before this one shows an image", `blockPosition`) next to `isFirst`; `priorityImage: false` turns it off.
|
||||
- **Sitemap, llms.txt, the site index (MCP `list_pages`), search (`searchContent`, the search route, MCP
|
||||
`search_content`):** the page assigned as the 404 page is no longer listed —
|
||||
it answers 404 at its own address (`unlistedPageIds(settings)`). A 404 page that is also the homepage stays.
|
||||
- **`buildImagesConfig` in production without R2:** with `R2_PUBLIC_URL` empty (the default: media served by the
|
||||
app) the site's own `/api/media/file/**` on `NEXT_PUBLIC_SERVER_URL` is allowed, so next/image no longer answers
|
||||
400. With R2 nothing changes; a production build on localhost still never opens private IPs.
|
||||
- **`fillGlobal`:** a choice field (select, radio, checkbox, number, date) still at its `defaultValue` counts as
|
||||
empty, so e.g. Theme → `defaultTheme: 'system'` can be seeded over the stored default `light`. Text is never
|
||||
overwritten, even when it equals a default. A field already holding
|
||||
exactly the seeded value is not rewritten (`skip (exists)`), so a seed of defaults stays idempotent.
|
||||
- **Docs:** `LanguageSwitcher` with `renderLabel` needs a `'use client'` wrapper (i18n.md, ipal-site).
|
||||
|
||||
### Changed
|
||||
- **ipal-seo-check:** duplicate titles are counted per language (the same word in two languages is not a duplicate).
|
||||
- **ipal-audit:** array `labels` / `rowLabel` after the `fields` key are found (were reported missing); a form seeded
|
||||
from any seed file (`src/seed/forms.ts`, `upsertBy('forms', …)`) counts as a form seed; the script runs grep in UTF-8
|
||||
(in the C locale an en dash matched the Polish-letter check).
|
||||
- The plugin's own dependencies are pinned to exact versions (`lucide-react` 0.400.0, `nodemailer` 10.3.1,
|
||||
`server-only` 0.0.1, `slugify` 1.6.9), so two sites created from the same release get identical trees. Projects:
|
||||
nothing to do (pnpm installs the pinned versions; `nodemailer` moves from 10.2.1 to 10.3.1).
|
||||
- The reference site carries `@starter:if` markers (comment lines) and the starter's alternatives as `//: ` lines;
|
||||
it runs exactly as before.
|
||||
- **Cookie banner / button colours** read the single token names (`--ipal-surface`, `--ipal-text` …) instead of
|
||||
`dark:` + `--ipal-*-dark`. With `tokens.css` they switch with the theme. Without it, the built-in fallback follows the
|
||||
page's `color-scheme` (`light-dark()`): a site without a dark theme no longer gets a dark banner on a dark-mode
|
||||
device. A `-dark` variable a site still sets is used as the dark fallback. The secondary button's dark fallback text
|
||||
is `#d4d4d4` (was `#e5e5e5`).
|
||||
- Lightbox fade: `--ipal-lightbox-duration` defaults to `var(--ipal-duration, 200ms)`; new `--ipal-lightbox-easing`.
|
||||
- **Admin labels:** the link "Open in new tab" checkbox is now **New tab** (with a description) and the table-of-contents
|
||||
switch **Show contents** — shorter labels per admin-ux; the stored fields are unchanged.
|
||||
- **A full seed of a live database is refused:** a run without `only` / `SEED_ONLY` against `NODE_ENV=production` or
|
||||
a non-local database now throws (with the steps to follow). Dry runs (`SEED_DRY_RUN=1`) are never refused. Allow it
|
||||
only with the owner's explicit OK: `IPAL_SEED_ALLOW_FULL=1` or `guard: { allowFull: true }`; `guard: false` turns
|
||||
every guard off.
|
||||
|
||||
### What projects must update
|
||||
1. **Production seed scripts / Coolify jobs:** a seed run against production without a record list now stops. List
|
||||
the records: `SEED_ONLY="pages:kontakt,global:header" pnpm seed` (check with `SEED_DRY_RUN=1` first, back up the
|
||||
database). A deliberate full re-seed: `IPAL_SEED_ALLOW_FULL=1`, with the owner's OK. Local seeding is unchanged.
|
||||
2. Optional: name the databases `<domain without dots>_prod` / `_dev` and add `ipalEnvRules({ databaseName: true })`
|
||||
to see a warning when `DATABASE_URI` points elsewhere. Existing databases need not be renamed.
|
||||
3. Seed scripts copied from older templates: take the new `SEED_ONLY` handling from `ipal-site` / `ipal-form`.
|
||||
4. Optional: adopt the design-token standard (design-tokens.md → "Migrating an existing site"; **ipal-upgrade**). A
|
||||
site that styles the cookie banner only through `--ipal-*-dark` for its dark theme and does not adopt `tokens.css`:
|
||||
check the banner in the dark theme (the dark fallback now needs `color-scheme: dark`, which `<ThemeScript>` sets).
|
||||
5. Block library — optional, nothing changes until you turn blocks on. New sites: the starter turns on eight blocks.
|
||||
Existing sites move block by block when they get work (an own block with the same slug and fields can be replaced by
|
||||
the library block with `slug`, else a migration with **ipal-migrate-fields**). After turning blocks on:
|
||||
`pnpm generate:types`, `pnpm payload generate:importmap`, Postgres/SQLite `pnpm payload migrate:create`.
|
||||
6. **CookieButton:** it now lifts above the site footer when the footer is in view. A site with its own fixed footer
|
||||
bar or a button placed by `className`: check it; `avoid={false}` keeps the old fixed position.
|
||||
7. **Agent skills:** `pnpm ipal:skills` — new skill **ipal-doctor**, and the updated `ipal-reference`, `ipal-setup`,
|
||||
`ipal-site`, `ipal-audit` (the audit now skips the starter's `//:` alternative lines).
|
||||
8. **Recommended:** run `pnpm exec ipal-doctor` in the site (and `--url https://<site>` against production) and fix or
|
||||
silence each finding with a reason in `ipal-doctor.json`. The `GET /api/ipal/doctor` endpoint stays a 404 until
|
||||
`IPAL_DOCTOR_TOKEN` (≥ 32 characters) is set; `ipalKit({ doctor: false })` removes it.
|
||||
9. **Exact dependency pins:** the plugin's own `lucide-react`, `nodemailer` (10.3.1), `server-only` and `slugify` are
|
||||
pinned — nothing to do; `pnpm install` picks them up. Node.js stays `>=20.9` for the plugin (new sites from
|
||||
`ipal-kit create` use Node 22).
|
||||
10. **New sites:** `pnpm --config.auto-install-peers=false dlx @intecion/ipal-kit@1.15.0 create <domain>` (project-starter.md).
|
||||
Not yet: single-language sites and a default language other than `pl` — the command stops and points to the manual
|
||||
**ipal-setup** path.
|
||||
|
||||
## 1.14.6
|
||||
|
||||
The release of everything listed under 1.14.5. **1.14.5 was tagged but never published** (its pre-publish test run
|
||||
failed on the bug below): projects upgrade from 1.14.4 straight to 1.14.6 and follow the **1.14.5 "What projects
|
||||
must update" steps**.
|
||||
|
||||
### Fixed
|
||||
- **The admin link-preview hook no longer throws without a Payload instance.** The Site settings `afterChange` hook
|
||||
added in 1.14.5 (`adminMeta`) called `syncAdminMeta(req.payload, …)`; with no `payload` on the request (tests,
|
||||
scripts calling hooks by hand) it threw, and its own error handler threw again. `syncAdminMeta` now returns when
|
||||
there is no Payload instance and logs only through `payload?.logger`, and the hook skips it without `req.payload`.
|
||||
The `fillEmptyLocales` hooks got the same guard. In a running site `req.payload` is always set.
|
||||
|
||||
### What projects must update
|
||||
- From 1.14.4: the 1.14.5 steps below (storage-type and title-separator migrations, theme key, cookie list, admin
|
||||
link preview, dependency overrides, agent skills). Nothing more for 1.14.6.
|
||||
|
||||
## 1.14.5
|
||||
|
||||
> Tagged but never published — use 1.14.6, which contains everything below.
|
||||
|
||||
The theme choice moves to the standard `theme` key, the cookie scanner declares the plugin's own browser-storage
|
||||
key, and the cookie list tells cookies from browser storage. A pasted `/admin` link now shows the site's own name,
|
||||
description and preview image instead of Payload's, and search engines are told not to index the panel.
|
||||
`/api/graphql` works again: it answered 500 on every site since 1.0.1. The `graphql-scalars` advisory is fixed in the
|
||||
plugin and recommended to projects, and the agent guide asks the architecture questions first and can add pinned
|
||||
third-party skills.
|
||||
|
||||
### Fixed
|
||||
- **`/api/graphql` returned 500 for every project** (`Names must start with [_a-zA-Z] but "|" does not.`). The values
|
||||
of Site settings → **Title separator** became GraphQL enum names, and `|`, `–`, `·` are not valid names (`-` and
|
||||
`/` both became `_`). Present since 1.0.1. The admin, REST and Local API were not affected, because they don't use
|
||||
GraphQL. Stored values are now names: `pipe`, `endash`, `hyphen`, `middot`, `slash`. The labels are the same, and
|
||||
`TITLE_SEPARATORS` / `titleSeparatorChar` map a name to its character. An old stored character still works: titles
|
||||
use it, and the field reads and saves it as its name. A test now builds the full plugin's GraphQL schema and fails
|
||||
on any invalid or duplicate enum name.
|
||||
|
||||
### Changed
|
||||
- **Theme key** `ipal-theme` → **`theme`** (`THEME_STORAGE_KEY`), the key and `light` / `dark` values next-themes uses.
|
||||
Visitors keep their choice: `<ThemeScript>` moves an old `ipal-theme` value to the new key before the first paint
|
||||
(no flash) and removes the old key; `useTheme` / `<ThemeSwitcher>` do the same on pages without the script
|
||||
(`migrateThemeStorage`, `LEGACY_THEME_STORAGE_KEY`). A project that also runs next-themes now shares the key —
|
||||
set `ipalKit({ theme: { storageKey } })` to keep them apart.
|
||||
- **White-label credit text** "Technology supported by Intecion.com" → **"Technology support: Intecion.com"** (pl:
|
||||
"Wsparcie technologiczne: Intecion.com"), with the name from the `agency` option.
|
||||
|
||||
### New
|
||||
- **`theme.storageKey`** option (`ThemeOptions`): `getSiteShell().theme.storageKey` → `<ThemeScript>` →
|
||||
`<html data-theme-storage>` (`THEME_STORAGE_ATTRIBUTE`) → `useTheme` / `<ThemeSwitcher>`; both also take `storageKey`.
|
||||
- **Cookie scanner declares browser storage**: the theme choice (*Theme choice*, on when Site settings → Theme →
|
||||
*Allow theme toggle* is on) as **necessary**, local storage, "until changed or site data is cleared" — so
|
||||
**Scan cookies** finds it without a crawl.
|
||||
- **Type in the cookie list**: *Cookies → Cookie list* rows have **Type** (`storage`: cookie · local storage ·
|
||||
session storage, default cookie, shared by every language), filled by scan, review and approval. The detailed
|
||||
settings window shows it for storage entries (heading: *Settings window → Cookie list headings → Type*);
|
||||
`<CookieTable>` adds a **Type** column when the list has a storage entry (`storageColumn`, `storageTypes`,
|
||||
`COOKIE_STORAGE_LABELS`). `CookieTableRow.storage`, `texts.details.storage` / `.storageTypes`, type `ConsentStorage`.
|
||||
The approval page marks storage entries.
|
||||
- **Admin link previews** (`adminMeta`, default on): the panel's `<title>` suffix, description, `og:site_name`,
|
||||
preview image and favicon come from Site settings (site name, logo, site icon), and `/admin` gets
|
||||
`robots: noindex, nofollow`. The preview image is `GET /api/ipal/admin-og` (1200×630 PNG rendered with next/og:
|
||||
the logo or site name, "Administration panel", a technology-support line) and the icon `GET /api/ipal/admin-icon`.
|
||||
Both are public, like the link previews that fetch them, and show only what Site settings already serves
|
||||
publicly (name, logo, icon). Per piece: `adminMeta: { description, image, icons, robots, titleSuffix, language }`
|
||||
(`false` for a piece = Payload's own); `adminMeta: false` turns it all off; keys the project sets in its own
|
||||
`admin.meta` always win. Building blocks: `buildAdminMeta`, `adminMetaForSite`, `syncAdminMeta`,
|
||||
`buildAdminImageEndpoints`, `ADMIN_META_TEXTS`, types `AdminMetaOptions`, `ResolvedAdminMeta` (white-label.md).
|
||||
- **`agency`** option (default `{ name: 'Intecion.com', url: 'https://intecion.com' }`, `AgencyOption`,
|
||||
`DEFAULT_AGENCY`): the technology-support name in the white-label credit, the admin description and the preview
|
||||
image. Another agency: `agency: { name, url }`; none anywhere: `agency: false`. The credit itself still turns off
|
||||
with `whiteLabel: { credit: false }`.
|
||||
- **Agent guide — ask before you build:** AGENT.md and the `ipal-*` skills start with one list of architecture
|
||||
questions (languages, content model, forms, integrations, hosting…) that the agent asks once and waits for; an
|
||||
unanswered question is never guessed. **ipal-kit first:** use the plugin's function when one exists; a gap is
|
||||
reported (`ipal-plugin-gap`) and the agent waits instead of writing its own version. Plus code rules for the
|
||||
project (`ipal-block`, `ipal-collection`, `ipal-form`, `ipal-site`, `ipal-setup`, `ipal-debug`).
|
||||
- **External skills (opt-in):** `pnpm exec ipal-skills --external` (or `--external ext-react-best-practices,ext-payload`)
|
||||
also copies five vendored third-party skills — `ext-react-best-practices`, `ext-composition-patterns`
|
||||
(vercel-labs/agent-skills, MIT), `ext-accessibility` (addyosmani/web-quality-skills, MIT), `ext-frontend-design`
|
||||
(anthropics/skills, Apache-2.0), `ext-payload` (payloadcms/payload, MIT). Text only, pinned to a commit, with each
|
||||
licence and a sha256 manifest (`docs/agent/external/manifest.json`); nothing is fetched at install time. Without
|
||||
`--external` nothing changes.
|
||||
|
||||
### Security
|
||||
- **`graphql-scalars` advisory** (high, ReDoS in the `PhoneNumber` scalar, GHSA-x8rm-f576-gq67): `@payloadcms/graphql`
|
||||
pins 1.22.2 up to the latest Payload (3.92.1). The plugin's repo overrides it to `^2.0.1`; Payload's GraphQL
|
||||
(`DateTime`, `EmailAddress`, JSON) works unchanged with it. Projects get the recommendation in AGENT.md §4 item 12.
|
||||
`pnpm audit --prod` on the plugin: 0 high, only the unfixed `deepmerge` low. graphql-scalars 2.x is a major
|
||||
(graphql-js 16+); Node.js 22 is recommended for projects that add the override (the package itself declares
|
||||
`node >=10`, and the plugin's `engines` stay `>=20.9`).
|
||||
|
||||
### Known issue
|
||||
- `deepmerge` 4.2.0–4.3.1 (low, GHSA-gcqx-w48m-w2h4) through `payload`: no patched version yet; nothing to do.
|
||||
|
||||
### What projects must update
|
||||
1. **Migration (Postgres / SQLite):** `pnpm payload migrate:create cookie-storage-type` — it only adds
|
||||
`cookie_settings_cookies.storage` (enum, `DEFAULT 'cookie'`) and `cookie_settings_locales.detail_labels_storage`.
|
||||
Existing rows become *Cookie*: set the type of storage rows by hand. MongoDB: nothing to do.
|
||||
2. A project that reads `localStorage.getItem('ipal-theme')` itself: use `THEME_STORAGE_KEY` (or `documentThemeStorageKey()`).
|
||||
3. Cookie list: after the next **Scan cookies**, approve the new *theme* entry; remove an old *ipal-theme* row from
|
||||
*Cookies → Cookie list* once the site runs this version.
|
||||
4. **Admin link previews:** nothing required — the preview, noindex and favicon come from Site settings by default.
|
||||
Remove a hand-written `admin.meta` that only set the panel title, description, `openGraph` or `robots: noindex`
|
||||
(keep any key you really want: your `admin.meta` keys win). With `whiteLabel`, the credit reads "Technology support:
|
||||
Intecion.com"; `agency: false` or `whiteLabel: { credit: false }` to remove it. No new admin components (the import
|
||||
map is unchanged). **Check:** `curl -s $URL/admin/login | grep -E 'og:|robots'`, open `$URL/api/ipal/admin-og`, and
|
||||
paste an `/admin` link in Slack or Messenger.
|
||||
5. **Security (recommended):** on `payload` 3.90.x–3.92.x add `"graphql-scalars@<2.0.1": "^2.0.1"` to `pnpm.overrides`
|
||||
next to the `dompurify` and `undici` ones (AGENT.md §4 item 12), `pnpm install`; Node.js 22 recommended with this
|
||||
override (check the Coolify build image). **Check:** `pnpm audit --prod` → no high or critical; with GraphQL in use,
|
||||
a query on a `DateTime` / `EmailAddress` field still answers 200.
|
||||
6. **Title separator (Postgres):** `pnpm payload migrate:create title-separator`. The generated SQL turns the column
|
||||
into text, recreates the enum with the new names and casts back, and that cast **fails on a stored `|`**. Add the
|
||||
data update right after the first `SET DATA TYPE text;` in `up` (and the `'down'` variant in `down`):
|
||||
```ts
|
||||
import { titleSeparatorSql } from '@intecion/ipal-kit'
|
||||
// up: ALTER TABLE "site_settings" ALTER COLUMN "title_separator" SET DATA TYPE text;
|
||||
// ${sql.raw(titleSeparatorSql())}
|
||||
// down: ALTER TABLE "site_settings" ALTER COLUMN "title_separator" SET DATA TYPE text;
|
||||
// ${sql.raw(titleSeparatorSql({ direction: 'down' }))}
|
||||
```
|
||||
**SQLite:** the column is plain text, so nothing fails. Optionally run `titleSeparatorSql()` in a migration to
|
||||
store the names. **MongoDB:** nothing to do, because the plugin rewrites the stored character at start
|
||||
(`[ipal] Site Settings: title separator … stored as …`). If you overrode the field's options (`globalOverrides`),
|
||||
use GraphQL-safe values (`/^[_A-Za-z][_A-Za-z0-9]*$/`). **Check:**
|
||||
`curl -s -X POST $URL/api/graphql -H 'content-type: application/json' -d '{"query":"{ SiteSetting { titleSeparator } }"}'`
|
||||
returns 200, and the browser tab shows the same separator as before.
|
||||
Project code that reads `settings.titleSeparator` itself now gets a name (`pipe`, …): pass it through
|
||||
`titleSeparatorChar()` before putting it in a title.
|
||||
7. **Agent skills:** `pnpm ipal:skills` (or `pnpm exec ipal-skills`) to get the new agent rules. Optional, only if the
|
||||
owner wants them (record it in AGENTS.md → "Project decisions"): `pnpm exec ipal-skills --external`.
|
||||
|
||||
## 1.14.4
|
||||
|
||||
Cookie texts in every language without retyping them, and one **Cookies** entry in the admin instead of three.
|
||||
Both are on by default and can be turned off; no schema change.
|
||||
|
||||
### New
|
||||
- **Empty languages are filled automatically** (`fillEmptyLocales`, default on): text written in one language goes
|
||||
to every language where the same field is still empty — the cookie list (Cookies → Cookie list: `purpose`,
|
||||
`duration`) and the cookie review (`purpose`, `retention`). A language that has its own text is never overwritten,
|
||||
so editors can still change each language on its own. `fillEmptyLocales: false` turns it off; an object sets the
|
||||
fields per slug (`{ 'cookie-settings': [...], 'cookie-review': [...] }`, `[]` = off for that slug). Building blocks:
|
||||
`fillEmptyLocales`, `withFillLocales`, `buildFillEmptyLocalesGlobalHook`, `buildFillEmptyLocalesCollectionHook`,
|
||||
type `FillEmptyLocalesTarget` (docs/hooks.md).
|
||||
- **One Cookies entry in the admin** (`cookieScanner.adminLayout`, default `'combined'`): with the cookie scanner,
|
||||
the Cookies global gets **Review and approve** and **Site check** tabs (`CookieReviewTab`, `CookieSiteCheckTab`,
|
||||
`/admin`; `addCookieScannerTabs`). The Cookie review collection and the Cookie check global leave the navigation;
|
||||
their data, API and `/admin/cookie-approval` stay. `adminLayout: 'separate'` keeps the separate entries.
|
||||
`collectionOverrides` and `crawl.globalOverride` still win (e.g. `admin.group` to show an entry again).
|
||||
|
||||
### Changed
|
||||
- The **Cookie banner** global is labelled **Cookies** (pl: Cookies) in every project; the slug `cookie-settings` and
|
||||
the data are unchanged. Docs and skills use the new name.
|
||||
|
||||
### Known issue
|
||||
- `pnpm audit --prod` still reports one **low** advisory: `deepmerge` 4.2.0–4.3.1 (GHSA-gcqx-w48m-w2h4), reached
|
||||
through `payload`. No patched version exists yet; nothing to do in projects.
|
||||
|
||||
### What projects must update
|
||||
1. `pnpm payload generate:importmap` — with `cookieScanner` it adds `@intecion/ipal-kit/admin#CookieReviewTab` and
|
||||
(with `crawl`) `@intecion/ipal-kit/admin#CookieSiteCheckTab`; commit `importMap.js`. No migration (no schema change).
|
||||
2. **Behaviour to know (both overridable):**
|
||||
- Empty languages of the cookie texts are now filled from the language an editor writes in. To keep empty
|
||||
languages empty: `ipalKit({ fillEmptyLocales: false })`.
|
||||
- With `cookieScanner`, the cookie screens are one **Cookies** entry with tabs; Cookie review and Cookie check
|
||||
are no longer in the navigation. To keep the old entries: `cookieScanner: { adminLayout: 'separate' }`.
|
||||
3. Tell editors: **Cookie banner** is now **Cookies**; the review list and the site check are its tabs. Update
|
||||
screenshots and instructions. **Check:** the admin navigation shows one **Cookies** entry; its **Review and
|
||||
approve** tab lists the review entries; type a cookie purpose in one language, save → the other languages show it.
|
||||
|
||||
## 1.14.3
|
||||
|
||||
One approval for everything the cookie scanner finds: editors tick the cookies and add them all to the cookie list
|
||||
at once, instead of opening every review entry. Only for projects with `cookieScanner`.
|
||||
|
||||
### New
|
||||
- **Approve cookies** page (`/admin/cookie-approval`, `CookieApprovalView`; linked from the scan box on Privacy →
|
||||
Cookie review and from the dashboard): the cookies a scan or crawl found,
|
||||
grouped by category, with one **Approve and add** button for every ticked cookie. They go into Cookie banner →
|
||||
Cookies in every locale. Nothing reaches the cookie list until an editor approves it. The approve and list endpoints
|
||||
are for editors and up by default (`cookieScanner.access`).
|
||||
- **Markers** on each review entry (new `change` and `needsDescription` fields): **New**, **Changed** (a scan changed
|
||||
its suggested values), **Needs description** (no purpose yet; cleared when an editor writes one) and **No longer
|
||||
found** (a scan or crawl no longer sees it). A cookie that is no longer found is flagged for review only; neither the
|
||||
review entry nor the list row is deleted.
|
||||
- **Never overwrites, never duplicates:** an existing list row (same name, or a pattern such as `_ga_*` that covers
|
||||
it) only gets its empty texts filled; editor text is kept, and no second row is added.
|
||||
- **Unknown cookies** that no integration or database knows go to `cookieScanner.approval.unknownCategory` (default
|
||||
`marketing`, so they need consent until an editor describes them).
|
||||
- **Reminders:** a dashboard notice while cookies wait (`CookieCrawlAlert`; `approval.dashboard: false` hides it), and
|
||||
the crawl e-mail says how many cookies wait, with a link to the approval page.
|
||||
- **`cookieScanner.approval: false`** keeps the old review, entry by entry.
|
||||
- New exports: `approveCookies`, `loadCookieApproval`, `countPendingCookies`, `flagGoneEntries`, `nextChange`,
|
||||
`sameCookie`, `buildCookieApprovalEndpoints`, `COOKIE_APPROVAL_PATH`, `COOKIE_APPROVAL_VIEW_PATH`,
|
||||
`DEFAULT_UNKNOWN_CATEGORY`, `PENDING_WHERE`; `CookieApprovalView`, `CookieApprovalForm` (`/admin`); types
|
||||
`CookieApprovalOptions`, `CookieApprovalItem`, `CookieApprovalList`, `CookieApprovalResult`, `CookieChange`.
|
||||
|
||||
### Changed
|
||||
- **Hand-typed cookie list rows:** a scan looks a row up (database, integrations) only while it has no review entry.
|
||||
Once it has one, the review entry and the approval page are the place to change it.
|
||||
|
||||
### Known issue
|
||||
- `pnpm audit --prod` still reports one **low** advisory: `deepmerge` 4.2.0–4.3.1 (GHSA-gcqx-w48m-w2h4), reached
|
||||
through `payload`. No patched version exists yet; nothing to do in projects.
|
||||
|
||||
### What projects must update
|
||||
- **Projects with `cookieScanner`:**
|
||||
1. `pnpm payload generate:importmap` — adds `@intecion/ipal-kit/admin#CookieApprovalView` and
|
||||
`@intecion/ipal-kit/admin#CookieCrawlAlert` (the dashboard reminder now uses it even without `crawl`); commit
|
||||
`importMap.js`.
|
||||
2. Postgres/SQLite: `pnpm payload migrate:create` → `migrate` — the `cookie-review` collection gets `change` (an
|
||||
enum column with an index) and `needs_description` (boolean). Only new columns; nothing is dropped or renamed.
|
||||
MongoDB: nothing.
|
||||
3. Tell editors: after a scan, open **Approve cookies** (from the scan box on Privacy → Cookie review, or the
|
||||
dashboard), tick and **Approve and add**. Fill in the cookies
|
||||
marked **Needs description**. **Check:** run a scan → the new cookies appear on `/admin/cookie-approval`; approve
|
||||
one → it is in Cookie banner → Cookies in every language.
|
||||
4. Keep the old review instead: `cookieScanner: { approval: false }`.
|
||||
- Projects without `cookieScanner`: nothing.
|
||||
|
||||
## 1.14.2
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -23,11 +23,13 @@ API details — one file per module:
|
||||
| Accessibility widget (optional) | [accessibility.md](./accessibility.md) |
|
||||
| GA4, GTM, Meta Pixel, Clarity, LinkedIn, TikTok, `defer` | [analytics.md](./analytics.md) |
|
||||
| Blocks, RenderBlocks, enhanceProps | [blocks.md](./blocks.md) |
|
||||
| Block library: ready sections, page templates | [block-library.md](./block-library.md) |
|
||||
| Cookie consent, banner, settings window (in the bar / modal / large with cookie details) | [consent.md](./consent.md) |
|
||||
| Cookie scanner: review list of drafts, "Scan cookies", Open Cookie Database lookup (optional) | [cookie-scanner.md](./cookie-scanner.md) |
|
||||
| Under construction — locks subpages behind a popup (developer tool) | [construction.md](./construction.md) |
|
||||
| Routing, archives, redirects, Markdown, search | [content.md](./content.md) |
|
||||
| Site frontend: `createContentHelpers` (`@/lib/content`), `createPageRoute`, `SiteProviders` | [frontend.md](./frontend.md) |
|
||||
| New site in one command (`ipal-kit create`, `@intecion/ipal-kit/starter`) | [project-starter.md](./project-starter.md) |
|
||||
| Deployment, production variables, health check | [deployment.md](./deployment.md) |
|
||||
| Seeds: create-only, dry run, backup, production update guard | [seeding.md](./seeding.md) |
|
||||
| Email SMTP / Graph | [email.md](./email.md) |
|
||||
@@ -50,8 +52,10 @@ API details — one file per module:
|
||||
| Stats in the admin panel (no cookies; visitor history with consent) | [stats.md](./stats.md) |
|
||||
| Auto-slug | [slug.md](./slug.md) |
|
||||
| Light / dark theme, switcher | [theme.md](./theme.md) |
|
||||
| Design tokens (`--ipal-*`, `tokens.css`, `tailwind.css`, `ipal-tokens`, DESIGN.md) | [design-tokens.md](./design-tokens.md) |
|
||||
| R2, `buildImagesConfig`, `MediaPreconnect`, `YouTubeEmbed` | [storage.md](./storage.md) |
|
||||
| Turnstile | [turnstile.md](./turnstile.md) |
|
||||
| ipal-doctor (the site against the team standard, `ipal-doctor.json`) | [doctor.md](./doctor.md) |
|
||||
| Admin panel white-label | [white-label.md](./white-label.md) |
|
||||
|
||||
Maintenance rule: a module's API changes → update its file in the same commit. New working rules →
|
||||
|
||||
@@ -75,8 +75,14 @@ the plugin only needs `A11yTexts` for the current locale.
|
||||
|
||||
## 2. CSS that reacts to the attributes (MANDATORY — project)
|
||||
|
||||
The widget sets attributes on `<html>`. Without this CSS nothing happens. Copy it
|
||||
into the project's global CSS (adapt it to the design):
|
||||
The widget sets attributes on `<html>`. Without CSS for them nothing happens.
|
||||
|
||||
**Ready file (1.15.0):** `@import "@intecion/ipal-kit/a11y.css";` in `styles.css` — the rules below, working through
|
||||
the design tokens ([design-tokens.md](./design-tokens.md)): the readable font swaps `--ipal-font-body/-heading` (set
|
||||
`--ipal-font-readable` to change it), "no animations" zeroes the `--ipal-duration-*` tokens, contrast + grayscale
|
||||
combine, the big cursor is built in. Check: tick each option in the widget and see the page change.
|
||||
|
||||
Or copy this into the project's global CSS (adapt it to the design):
|
||||
|
||||
```css
|
||||
/* Text size */
|
||||
|
||||
+240
-45
@@ -30,28 +30,115 @@ or data shape where an option or an exported building block is enough.
|
||||
|
||||
**In practice:** before you write something from scratch or start fighting the plugin — find
|
||||
the option or the exported builder (module docs §12, types in `dist/**/*.d.ts`). It is missing →
|
||||
**plugin gap** (report + a marked workaround in the project code), never patching
|
||||
`node_modules` or forking the package.
|
||||
**plugin gap**: report it to the owner and wait for their decision (see "ipal-kit first" below), never
|
||||
patch `node_modules` or fork the package.
|
||||
|
||||
**Docs language:** all ipal-kit docs, this guide and the skills are written in English.
|
||||
Write new rules, AGENTS.md entries and plugin-gap reports in English.
|
||||
|
||||
> **VERY IMPORTANT — seeding after launch.** Once a site is live, **never run a full seed again**: the owner's
|
||||
> edits on the live site must survive. Every later change targets **named records only** — specific pages,
|
||||
> globals, forms or fields — listed in the seed (`only: [...]` / `SEED_ONLY="pages:kontakt,global:header"`).
|
||||
> Never re-seed everything, not even in create-only mode, without the owner's explicit OK. `createSeeder`
|
||||
> refuses a run with no record list against a production or non-local database unless `IPAL_SEED_ALLOW_FULL=1`
|
||||
> (set it only after that OK).
|
||||
|
||||
**Database names** (MongoDB and Postgres): the site's domain **with the dots removed**, plus `_prod` or `_dev` —
|
||||
`intecion.com` → `intecioncom_prod` / `intecioncom_dev`, `architektimprez.pl` → `architektimprezpl_prod` /
|
||||
`architektimprezpl_dev`. The name is the path of `DATABASE_URI`: `mongodb://…@mongo:27017/intecioncom_prod?authSource=admin`,
|
||||
`postgres://…@db:5432/intecioncom_prod`. You derive the names from the domain and confirm them with the owner (ipal-setup
|
||||
stage 0). `ipalEnvRules({ databaseName: true })` warns when they do not match (deployment.md §4.2a).
|
||||
|
||||
**Seeding on production** (details: `node_modules/@intecion/ipal-kit/docs/seeding.md`). Write seeds with
|
||||
`createSeeder` from `@intecion/ipal-kit/seed` (the templates do) — it enforces every rule below:
|
||||
- Call `guardSeedExit()` first in every seed script (before `getPayload`): a run that ends early exits 1 with the reason
|
||||
instead of a silent 0 that looks like success in Coolify's Terminal.
|
||||
- Seeds are create-only and idempotent: match by the default-locale slug / form title / the global, skip what exists.
|
||||
- Never delete; never seed users, passwords or secrets; globals: fill only empty fields; no media uploads.
|
||||
- Every locale written separately with `fallbackLocale: false`; `context: { disableRevalidate: true, ipalSkipIndexNow: true }`.
|
||||
- On production: dry run first (`SEED_DRY_RUN=1`), back up the database (Coolify **Backup now**), then the real run.
|
||||
- `SEED_UPDATE=1` on production / a non-local database only with `IPAL_SEED_ALLOW_PROD_UPDATE=1`, after a backup;
|
||||
records an editor changed are always skipped and reported (`skip (edited)`) — never use `SEED_FORCE=1` there.
|
||||
- After launch: named records only (`only` / `SEED_ONLY`); a full run of a live database is refused without `IPAL_SEED_ALLOW_FULL=1`.
|
||||
- Schema and one-off data fixes → Payload migrations; field renames with content → **ipal-migrate-fields**; content → seeds.
|
||||
|
||||
## Ask before you build — architecture questions
|
||||
|
||||
Before you set up a site (or a new part of one), **ask the owner these questions and wait for the answers**.
|
||||
They decide the architecture; a wrong guess means rework. Ask them as **one list**, once, at the start —
|
||||
the ready-to-send list is in **ipal-setup** stage 0 (ipal-site phase 0 uses the same list).
|
||||
|
||||
| Topic | What you need to know |
|
||||
|---|---|
|
||||
| Languages | which locales, the default locale, URL structure (`/pl/…` for every language, or the default without a prefix) |
|
||||
| Styling | a design system / `DESIGN.md` or plain Tailwind tokens, brand colours, fonts, light/dark theme |
|
||||
| Content | the pages, the collections (blog, case studies, products…), archive pages |
|
||||
| Forms | which forms, who receives them, e-mail provider (SMTP from the panel or Microsoft Graph) |
|
||||
| Analytics and consent | GA4 / GTM / pixels, Consent Mode basic or advanced, cookie banner mode, cookie scan |
|
||||
| SEO / GEO | market and local business data, AI crawler policy (llms.txt, Markdown, MCP, AI bots) |
|
||||
| Data and media | database (Postgres or MongoDB) and its names (`<domain without dots>_prod` / `_dev` — derive, then confirm), media storage (R2 or local disk) |
|
||||
| Admin | 2FA, white-label (client brand in the panel), agency credit |
|
||||
| Hosting | Coolify, the production domain(s), who adds the DNS records (deployment.md §6) |
|
||||
|
||||
- **A new site starts with `ipal-kit create`** (docs/project-starter.md): `pnpm --config.auto-install-peers=false dlx
|
||||
@intecion/ipal-kit@<version> create <domain>` asks exactly these questions (or reads them from `--answers file.json`),
|
||||
generates the site from the reference site, writes the answers into `AGENTS.md` and makes the first commit. Ask the owner
|
||||
first, then pass the answers — the command never fills a gap. The manual path (`ipal-setup` stages 1–11) is for an
|
||||
existing project or what the command does not cover yet: **single-language sites, a default language other than `pl`**, sites
|
||||
without `en`, URLs without a prefix, Postgres — the command stops with a message pointing here.
|
||||
- Write every answer into the project's `AGENTS.md` → **"Project decisions"** (one line per topic).
|
||||
- **Do not guess a missing answer.** No answer to an architecture question → do not build that part; ask again.
|
||||
(Only *content* gaps — company data, texts, IDs — may wait: use `[TO FILL: …]` in the panel, §0a.)
|
||||
- An answer that conflicts with these rules → say so straight away and propose a compliant option.
|
||||
|
||||
## ipal-kit first — hard rule
|
||||
|
||||
- **Anything the plugin covers, you build with the plugin's feature.** Always. Look it up first: the
|
||||
**ipal-reference** skill, the module docs (§12), the types in `dist/**/*.d.ts`.
|
||||
- The only exceptions: the plugin's feature **does not work**, or it **is not enough** for this project.
|
||||
- Even then: **report the gap to the owner first** with the **ipal-plugin-gap** skill and **do nothing on
|
||||
your own** for that part until the owner decides (wait for a plugin fix / an approved option / an approved,
|
||||
marked workaround). Work on unrelated parts may go on.
|
||||
- **No hand-built replacements and no silent workarounds.** A workaround exists only after the owner approved
|
||||
it, is marked `// WORKAROUND ipal-kit <version>: docs/plugin-requests/<file>` and is recorded in
|
||||
"Project decisions".
|
||||
|
||||
## Reference site — copy the pattern, not from memory
|
||||
|
||||
Every convention in this file is implemented in the **reference site**: one complete client site on ipal-kit
|
||||
("Example Studio", made up), kept current with each release and built, seeded and smoke-tested in the plugin's CI.
|
||||
Before you write a file the plugin expects you to wire (payload.config, layout, catch-all page, `lib/content.ts`,
|
||||
proxy, SEO/GEO routes, forms, seeds, `AGENTS.md`, `DESIGN.md`, deploy notes), open
|
||||
`node_modules/@intecion/ipal-kit/docs/agent/reference-site/INDEX.md`, find the matching file and copy its pattern —
|
||||
short wiring files are in the index in full, longer ones are linked at the tag of your plugin version. Change only the
|
||||
project's content (names, texts, blocks the site map needs), never the pattern. The index and this file disagree →
|
||||
report it with **ipal-plugin-gap**: it is a plugin bug.
|
||||
|
||||
## Code rules
|
||||
|
||||
Short version of §8 — every skill follows it.
|
||||
- **Single responsibility:** one job per file, per component, per function.
|
||||
- **Small files, clear names, no dead code** (no commented-out code, unused exports or props).
|
||||
- **No duplicated logic** — extract it once; reuse the plugin's exports instead of rewriting them.
|
||||
- **Typed, no `any`** (no `@ts-ignore`; unknown shape → `unknown` + a type guard).
|
||||
- **Texts in i18n, never literals** — every visible text comes from the panel / localized fields (§2).
|
||||
- **Tests or checks for new behaviour** — a unit test, an `ipal-audit` / `ipal-seo-check` result, or a
|
||||
documented manual check (§8a).
|
||||
|
||||
```tsx
|
||||
// BAD — one component fetches, formats and renders; hardcoded text; any
|
||||
export function Offer({ data }: { data: any }) { const p = fetch(…); return <h2>Nasza oferta</h2> }
|
||||
// GOOD — data comes in typed props (enhanceProps / lib/content), text from the panel, one job
|
||||
export function Offer({ header, items }: OfferBlockProps) { return <Section header={header}><OfferList items={items} /></Section> }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 0. COMPASS (if you remember only this)
|
||||
|
||||
0. **Ask first.** Architecture questions before you build ("Ask before you build" above) — never guess.
|
||||
1. **ipal-kit is mandatory.** A feature the plugin has goes through the plugin.
|
||||
Something is missing → report (§1.3, plugin gap) + a marked workaround, not a silent patch.
|
||||
Missing or broken → report it (plugin gap, §1.3) and wait for the owner's decision — no silent patch.
|
||||
2. **Nothing hardcoded.** Text, image, link, file, company data → admin panel. Domains,
|
||||
keys → `.env`. Also in an `||` fallback and in `catch`.
|
||||
3. **Next 16 = `proxy.ts`.** NEVER `middleware.ts`.
|
||||
@@ -66,6 +153,8 @@ Write new rules, AGENTS.md entries and plugin-gap reports in English.
|
||||
`docs/dev/admin-ux.md`); no empty "just in case" fields.
|
||||
7. **Renderers from the plugin:** `RenderBlocks` (not a `switch`), `RenderRichText` (not
|
||||
your own Lexical parser), `useForm` (not hand-made form plumbing).
|
||||
**Sections from the block library first:** `libraryBlocks` + `createBlockRegistry` (15 ready blocks,
|
||||
docs/block-library.md); an own block only when no library block, variant or option fits.
|
||||
8. **No `any` and no `@ts-ignore`.** Types from `@/payload-types`, `unknown` + guard.
|
||||
9. **One source of truth** — `i18n.config.ts`, `lib/content.ts`, never copies.
|
||||
10. **"Done" only after** a local `pnpm build` + the checks from §11.
|
||||
@@ -77,7 +166,8 @@ Write new rules, AGENTS.md entries and plugin-gap reports in English.
|
||||
| What | How |
|
||||
|---|---|
|
||||
| a page | in the panel: Pages + blocks, no code (§5.1) |
|
||||
| a section (block) | `src/blocks/<Name>/config.ts` + `Component.tsx`, an entry in `blocks/registry.ts`, the block in the Pages `layout` field → `pnpm generate:types` (+ `pnpm payload generate:importmap` with `rowLabel`) — **ipal-block** |
|
||||
| a section (block) | a library block first: `blockOptions` → `libraryBlocks` in `src/blocks/configs.ts`, `createBlockRegistry(content, { Image, Link, sendForm })` in `blocks/registry.ts` (docs/block-library.md). None fits → `src/blocks/<Name>/config.ts` + `Component.tsx`, `extra` in the registry, `pageBlocks` → `pnpm generate:types` (+ `pnpm payload generate:importmap` with `rowLabel`) — **ipal-block** |
|
||||
| a standard page (home, about, services, contact, legal, 404…) | `pageTemplates` from `@intecion/ipal-kit/templates` in the content seed (after launch only with `SEED_ONLY`) — **ipal-site** phase 6 |
|
||||
| a form | the Forms panel (builder) from the seed `scripts/seed-form-*.ts`, a block with `<RenderForm>`, sending via `sendForm` — **ipal-form** |
|
||||
| a language | `i18n.config.ts` (the only place) + a Postgres migration + content in the new language — **ipal-locale-add** |
|
||||
| a collection with URLs | `content: { collections: [...] }` in `ipalKit` and `createContentHelpers` (§5.4) — **ipal-collection** |
|
||||
@@ -108,13 +198,14 @@ site), **P** = a test in the panel. Full code: PROGRAMISTA.md §2.
|
||||
| 9 | **Media / R2 / speed** | `Media` with `focalPoint`, `normalizeFilenameHook`, `buildOptimizeUploadHook`, `buildMediaPlaceholderHook` + field; **always** `buildR2Storage(['media'], { s3Storage })` + `@payloadcms/storage-s3`; `R2_*` in `.env.example`; `<MediaPreconnect/>`; `images: buildImagesConfig()` and `buildUploadSecurityHeaders()` in `next.config.ts`; the project's `<Media>` via `mediaImageProps`/`videoProps` (§6.11b) | `buildR2Storage`, `mediaImageProps`, `videoProps`, `buildImagesConfig` | A, S |
|
||||
| 10 | **Forms** | every form from a **seed** (`scripts/seed-form-*.ts`: fields, confirmation, mail to the company **and** confirmation to the customer, every language); a block with `<RenderForm>` + `formClasses.ts` (look, once); `actions.ts` = `createSubmitAction({ getCachedPayload, headers })`; `forms: {…}` in `ipalKit`; `email: mailAdapter()` | `RenderForm` (`/rsc`), `createSubmitAction`, `mailAdapter` | A, P |
|
||||
| 11 | **Turnstile** | `<SiteProviders>` in `[locale]/layout.tsx` (wires `TurnstileProvider` with the key from the panel); `RenderForm` renders the widget; keys in Site integrations | `SiteProviders`, `getTurnstileConfig`, `TurnstileProvider` | A, P |
|
||||
| 12 | Consent + analytics | Consent Mode: `'advanced'` (default — the Google tag loads at once with every signal `denied`) or `'basic'` (`<SiteProviders analytics={{ consentMode: 'basic' }}>` — no request to Google before consent; a client who wants zero requests), the choice goes to "Project decisions"; `ipalKit({ consentLog: true })` (without it the `/api/ipal/consent` endpoint does not exist) + `<SiteProviders logEndpoint="/api/ipal/consent" banner={<CookieBanner equalChoice settings="detailed" />}>` (ConsentProvider, banner, CookieButton, Analytics in the right order); settings window mode (`settings`: `inline` / `modal` / `detailed`) per the design, brief is silent → `detailed`, the decision goes to "Project decisions"; tool IDs in the panel; the cookie list from a scan (`cookieScanner: true` → *Cookie review* → **Scan cookies** → the editor accepts; or cookie-scan → import) — feeds `<CookieTable>` on the policy page **and** the lists in the `detailed` window; Cookie banner → Settings window → Cookie list headings in every language | consent.md, analytics.md | A, `ipal-consent-check` |
|
||||
| 12 | Consent + analytics | Consent Mode: `'advanced'` (default — the Google tag loads at once with every signal `denied`) or `'basic'` (`<SiteProviders analytics={{ consentMode: 'basic' }}>` — no request to Google before consent; a client who wants zero requests), the choice goes to "Project decisions"; `ipalKit({ consentLog: true })` (without it the `/api/ipal/consent` endpoint does not exist) + `<SiteProviders logEndpoint="/api/ipal/consent" banner={<CookieBanner equalChoice settings="detailed" />}>` (ConsentProvider, banner, CookieButton, Analytics in the right order); settings window mode (`settings`: `inline` / `modal` / `detailed`) per the design, brief is silent → `detailed`, the decision goes to "Project decisions"; tool IDs in the panel; the cookie list from a scan (`cookieScanner: true` → *Cookie review* → **Scan cookies** → *Approve cookies* → **Approve and add**; or cookie-scan → import) — feeds `<CookieTable>` on the policy page **and** the lists in the `detailed` window; Cookies → Settings window → Cookie list headings in every language | consent.md, analytics.md | A, `ipal-consent-check` |
|
||||
| 13 | Security | `buildSecurityHeaders` in `next.config.ts`; `withPayload(withSecurityConfig(nextConfig))` (no `X-Powered-By`); CSP: `buildSecurityHeaders({ csp: { mode: 'report-only', reportUri: '/api/csp-report', … } })` + `buildAdminCspHeaders` on `/admin/:path*` + `src/app/api/csp-report/route.ts` (`createCspReportRoute`) → read the reports → `mode: 'enforce'`; `twoFactor: { issuer, plugin: payloadTotp }` + `generate:importmap` (`TotpRedirectProvider`; check: a new admin lands on `/admin/setup-totp?back=%2Fadmin` with the QR, no reloading); `IPAL_IP_HEADER` in production | security.md, forms.md | A |
|
||||
| 14 | Operations | `src/app/api/health/route.ts` (`healthRoute`); `src/instrumentation.ts` with `assertEnv(ipalEnvRules({ storage: true, ipHeader: true }))`; staging with `IPAL_NOINDEX=1`; smoke tests (§8a) | `healthRoute`, `assertEnv`, `ipalEnvRules` | A |
|
||||
| 15 | System pages | Site settings → System pages: homepage, 404, privacy policy, cookies; legal links in the footer by role (`getSystemLinks(locale)`) | `getSystemLinks`, `getSystemPagePath`, `getNotFoundPage` | P |
|
||||
| 16 | **Nothing hardcoded** | every text, link, image, file, company data from the panel; domains and keys from `.env` (§2) | — | A, P |
|
||||
| 17 | **Content** | one h1, the answer at the start of each section, facts, internal links, FAQ from real questions, `aiSummary`, sameAs, consistent company data (§0c) | — | S, P |
|
||||
| 18 | **Scaling** | `fluid.css` / `fluid-wide.css`, hero on `--ipal-hero-min-h`, the screen list in §6.11a (including 1366×768) | — | A, browser |
|
||||
| 19 | **Design tokens** | `DESIGN.md` + `src/design/tokens.ts` → `pnpm exec ipal-tokens` → `src/design/tokens.css`; `styles.css` imports `fluid-wide.css`, `tokens.css`, `tailwind.css`, the brand file (§6.11); fonts in `--font-family-body` / `--font-family-heading` | `defineTokens`, `ipal-tokens` | A (`ipal-tokens --check`), browser (both themes) |
|
||||
|
||||
**Turnstile works by itself:** both keys in the panel (or env) → the widget shows, and
|
||||
`submitForm` **requires** a token; no keys → no widget, the form works.
|
||||
@@ -129,6 +220,7 @@ Do not make the provider or the widget conditional in code — always wire them.
|
||||
| Instead of the plugin | Why not | Use |
|
||||
|---|---|---|
|
||||
| your own form with fields in JSX, `react-hook-form`, `formik`, your own form renderer | the client cannot change the fields; no Turnstile, rate limit, GDPR consent; a copy of the engine passes addresses from the Emails tab into HTML | the builder in the panel + `<RenderForm>` (look: `formClasses`, unusual cases: `useBuilderForm`) |
|
||||
| a file input wired by hand, your own upload route, form files saved to Media / R2 / disk | candidate and customer documents end up public or kept forever; no type, size or macro checks; the gates are skipped | `forms: { attachments: true }` + the **File** field — the file is e-mailed to the company and never stored (forms.md "Files") |
|
||||
| your own `api/contact` / `api/send` / `api/form` route, `nodemailer` / `resend` / `@sendgrid` in the project | bypasses the `submitForm` validation and gates, a second mail transport | the `sendForm` server action → `submitForm`, mails from Forms → Emails via `mailAdapter()` |
|
||||
| reCAPTCHA, hCaptcha, your own captcha | a second mechanism, no status in the panel | Turnstile from the plugin |
|
||||
| a hand-written `<script type="application/ld+json">` | no escaping, drifts from the panel | `JsonLdGraph` |
|
||||
@@ -222,6 +314,7 @@ yourself and check your own work yourself. For a full build use the
|
||||
- plugin defaults (media limits, ISR, robots) — unless the brief says otherwise.
|
||||
|
||||
### You ask only about this (collect the questions in **one list**, not one at a time)
|
||||
- **the architecture questions** ("Ask before you build" at the top) — before you build; you wait for these answers;
|
||||
- **data that is missing** from the brief and the panel: languages, market, domain, company data,
|
||||
analytics IDs and integration keys, notification email addresses;
|
||||
- **irreversible decisions**: deleting content, migrating a database with content, changing slugs
|
||||
@@ -257,8 +350,8 @@ Diagnose (**ipal-debug**: symptom → cause → fix), fix it at the source,
|
||||
check again. Do not report problems you can solve.
|
||||
|
||||
### Report only when
|
||||
- **ipal-kit has a bug or is missing a feature** → **plugin gap** (report +
|
||||
a minimal, marked workaround — the work goes on, you do not wait),
|
||||
- **ipal-kit has a bug or is missing a feature** → **plugin gap** (report to the owner and
|
||||
wait for their decision on that part — no workaround on your own; unrelated work goes on),
|
||||
- you see an **ipal-kit improvement** useful in many projects → **plugin gap**
|
||||
(type: improvement),
|
||||
- **the task is finished** → the final report (format in **ipal-site**).
|
||||
@@ -289,8 +382,9 @@ Rule: **identical in every project → plugin. Depends on the client → project
|
||||
### 1.3 When the plugin is missing something or something does not work
|
||||
**Do not patch silently** (a hook with a hardcoded value, your own helper, `as any`). It
|
||||
almost always means the plugin already has it (check the docs) or the plugin is missing it.
|
||||
The **ipal-plugin-gap** skill: report + a minimal, marked workaround
|
||||
(`// WORKAROUND ipal-kit <version>: …`), the work goes on. The report contains:
|
||||
The **ipal-plugin-gap** skill: report to the owner and **wait for their decision** on that part
|
||||
("ipal-kit first" at the top). A workaround only after approval, marked
|
||||
(`// WORKAROUND ipal-kit <version>: …`) and recorded in "Project decisions". The report contains:
|
||||
- a description of the problem / missing feature,
|
||||
- the proposed API (function / option signature),
|
||||
- why it is universal (useful in other projects).
|
||||
@@ -329,7 +423,7 @@ CDN preconnect: `<MediaPreconnect />` (from env). Media: `normalizeFilenameHook`
|
||||
```
|
||||
src/
|
||||
app/
|
||||
(frontend)/
|
||||
(frontend)/ # any route group name works ((site) …); ipal-doctor finds it by structure
|
||||
styles.css # Tailwind + @source on node_modules/@intecion/ipal-kit/dist
|
||||
[locale]/ # single-language: no [locale] (see i18n.md)
|
||||
layout.tsx # no <head>; <SiteProviders shell={await getSiteShell(locale)}> + Header/Footer
|
||||
@@ -411,25 +505,52 @@ No abbreviations (`HeroSection`, not `HeroSec`). Do not create `lib/pages.ts`,
|
||||
9. **RSC by default.** `'use client'` only for state/interaction, in a separate file;
|
||||
the section stays a server component and passes data to it. Secrets: `import 'server-only'`.
|
||||
10. **Blocks do not import `lib/*`** (cycle). Server-side data → `enhanceProps`.
|
||||
11. **Next.js 16.4.1 or later** (minimum safe version). 16.0.0–16.4.0 have unauthenticated RCE and DoS
|
||||
advisories (GHSA-2464-fhr4-w9xw, GHSA-673q-mjm6-r5xr, GHSA-p3m5-59mp-jv5r); Payload supports no patched
|
||||
15.x line. Pin `next` and `eslint-config-next` to the same 16.4.x (≥ 16.4.1) and make sure `sharp` resolves to
|
||||
0.35.5 or later (`pnpm why sharp`). The plugin's peer range stays open (`next >=15`) — the minimum is yours to keep.
|
||||
**Check:** `pnpm ls next sharp` → next ≥ 16.4.1, sharp ≥ 0.35.5; `pnpm dev` prints no security-upgrade warning.
|
||||
12. **No open production advisories.** Node.js 20 or later (the plugin's `nodemailer` 10 requires it). Run
|
||||
11. **Next.js 16.4.5 or later** (minimum safe version; the plugin, the reference site and the starter use 16.4.6).
|
||||
16.0.0–16.4.0 have unauthenticated RCE and DoS advisories (GHSA-2464-fhr4-w9xw, GHSA-673q-mjm6-r5xr,
|
||||
GHSA-p3m5-59mp-jv5r); 16.3.0–16.4.4 have GHSA-mfr8-8qww-v76h (information disclosure across root params when a
|
||||
`'use cache'` function is called through `unstable_cache()`, moderate; fixed in 16.4.5). Payload supports no
|
||||
patched 15.x line. Pin `next` and `eslint-config-next` to the same 16.4.x (≥ 16.4.5):
|
||||
`pnpm add next@16.4.6 eslint-config-next@16.4.6`, and make sure `sharp` resolves to 0.35.5 or later
|
||||
(`pnpm why sharp`). The plugin's peer range stays open (`next >=15`) — the minimum is yours to keep.
|
||||
**Check:** `pnpm ls next sharp` → next ≥ 16.4.5, sharp ≥ 0.35.5; `pnpm exec ipal-doctor` → no `next-min`
|
||||
finding; `pnpm dev` prints no security-upgrade warning.
|
||||
12. **No open production advisories.** Node.js 20 or later for the plugin itself (its `nodemailer` 10 requires it);
|
||||
**Payload 3.94 needs Node.js 22.23.5 or later** on the 22 line (`engines`: `">=22.23.5 <23"`, `.nvmrc` `22`), locally,
|
||||
in CI and in Coolify (Nixpacks takes the major from `engines` / `.nvmrc` and the patch from its own release: check
|
||||
`node -v` in the app's Terminal; below 22.23.5, update Coolify before moving to Payload 3.94). Run
|
||||
`pnpm audit --prod`. The plugin's own dependencies are clean; what remains comes from Payload's tree, which only
|
||||
the project's lockfile can fix. With `payload` 3.90.x two packages are pinned exactly and need `pnpm.overrides`
|
||||
next to the `@payloadcms/*` ones:
|
||||
the project's lockfile can fix. With `payload` **3.94.x** two packages are still pinned below a fix and need
|
||||
`pnpm.overrides` next to the `@payloadcms/*` ones:
|
||||
```json
|
||||
"dompurify@<3.4.17": "^3.4.17",
|
||||
"happy-dom@<21.0.4": "^21.0.4"
|
||||
```
|
||||
`happy-dom` comes from `@payloadcms/richtext-lexical` → `@lexical/headless` 0.50 (`^20.9.0`, still so in 3.94.1);
|
||||
every 20.x has GHSA-c8p4-j97h-3vg8 (high, SSRF when parsing untrusted HTML, fixed in 21.0.0) and
|
||||
GHSA-834v-8h66-3h79 (high, host code execution, fixed in 21.0.4). 21 is a major, but only
|
||||
`@lexical/headless/dom` (`withDOM`) loads it — Payload never imports that entry, and Lexical 0.53 itself moved to
|
||||
`^21.0.4`. `dompurify` comes from the admin code editor (`@payloadcms/ui` → `monaco-editor`; low advisories).
|
||||
**On an older Payload** add these too, until you upgrade (upgrading to 3.94.1 is the better fix):
|
||||
```json
|
||||
"mongoose@>=8 <8.24.7": "~8.24.10",
|
||||
"undici@>=7 <7.30.1": "^7.30.1"
|
||||
```
|
||||
`undici` comes from `payload` (3.92.1 and later already ship 7.30.1), `dompurify` from the admin code editor
|
||||
(`@payloadcms/ui` → `monaco-editor`, which pins 3.2.7). Everything else in the report (`fast-uri`, `js-yaml`,
|
||||
`browserslist`, `source-map-js`, `fast-copy`, `baseline-browser-mapping`) is a range: `pnpm update` or a fresh
|
||||
lockfile picks up the fix; add an override like the ones above only if it does not. These are recommendations —
|
||||
the plugin forces none of them. Never add a project dependency on `nodemailer` or `@types/nodemailer`.
|
||||
**Check:** `pnpm audit --prod` → no high or critical; `pnpm why undici dompurify` → only the fixed versions.
|
||||
`mongoose` (MongoDB sites on Payload 3.90–3.93): `@payloadcms/db-mongodb` pins 8.24.1, which has five advisories —
|
||||
GHSA-pcrw-h46h-c93h (critical, `sanitizeFilter` not applied on `countDocuments`, fixed in 8.24.3),
|
||||
GHSA-gg4r-jv3p-qx3c and GHSA-8332-j7wj-wjw4 (high), GHSA-wr5m-5jph-8m96 and GHSA-6972-9mcm-vhwj (moderate), all
|
||||
fixed in 8.24.7; Payload 3.94.0 and later ship 8.24.7. `undici` (Payload 3.90–3.91): 3.92.0 and later ship 7.30.1.
|
||||
Both selectors match only the vulnerable versions, so they do nothing once Payload ships the fix — remove them then.
|
||||
**`graphql-scalars` needs no override any more:** GHSA-x8rm-f576-gq67 now covers 1.24.1–2.0.0 only, and
|
||||
`@payloadcms/graphql` pins 1.22.2. A `"graphql-scalars@<2.0.1": "^2.0.1"` line added earlier may be removed (it
|
||||
also works if kept: Payload's GraphQL runs unchanged on 2.x). The `deepmerge` low is gone from Payload 3.94.1.
|
||||
Everything else in the report (`fast-uri`, `js-yaml`, `browserslist`, `source-map-js`, `fast-copy`,
|
||||
`baseline-browser-mapping`) is a range: `pnpm update` or a fresh lockfile picks up the fix; add an override like
|
||||
the ones above only if it does not. These are recommendations — the plugin forces none of them. Never add a
|
||||
project dependency on `nodemailer` or `@types/nodemailer`.
|
||||
**Check:** `pnpm audit --prod` → no high or critical; `pnpm why dompurify happy-dom mongoose undici` → only the
|
||||
fixed versions (dompurify 3.4.17 or later, happy-dom 21.0.4 or later, mongoose 8.24.7 or later, undici 7.30.1 or
|
||||
later); `pnpm exec ipal-doctor` → no `transitive-min` finding; after a Payload or mongoose change run
|
||||
`pnpm build`, open the panel and save a document.
|
||||
|
||||
---
|
||||
|
||||
@@ -488,6 +609,13 @@ never by slug. pages.md.
|
||||
|
||||
## 6. BUILDING SECTIONS (`.tsx` blocks)
|
||||
|
||||
**Block library first.** The plugin ships 15 sections built to every rule below — `hero`, `textMedia`,
|
||||
`featureGrid`, `cta`, `richText`, `faq`, `contact`, `gallery`, `testimonials`, `stats`, `steps`, `logos`, `team`,
|
||||
`pricing`, `entryList` — with variants, `{ en, pl }` panels, accessibility and token-only styling, plus ten page
|
||||
templates ([block-library.md](../block-library.md)). Turn them on with `libraryBlocks(blockOptions)`, render them with
|
||||
`createBlockRegistry`, change them with their options (`fields`, `variants`, `classNames`, `ui`, `components`), own one
|
||||
with `ipal-blocks eject`. The rules below are how those blocks are built and how you build your own when none fits.
|
||||
|
||||
Three problems that must never repeat: **a zoo of CTA fields** (`ctaLabel`,
|
||||
`cta2Text`, `buttonUrl`…), **files as text** (`pdfUrl: '/files/x.pdf'`),
|
||||
**the monolith section** (200–400 lines with cards, SVG icons and button styles).
|
||||
@@ -547,7 +675,10 @@ Field labels as `{ en, pl }` objects (the panel runs in English and Polish; §6.
|
||||
|
||||
### 6.3 Layer 2 — UI primitives
|
||||
|
||||
Code 1:1: [section-code.md](./skills/ipal-block/resources/section-code.md). Each one has one job:
|
||||
With the block library they come from the plugin: `Section`, `SectionHeader`, `Media`, `CMSLink`, `buttonClass`,
|
||||
`Container`, `Card` from `@intecion/ipal-kit/blocks/rsc` (no project copies; `src/components/ui/` holds only a
|
||||
project version you pass in with `createBlockRegistry(content, { ui: { Media } })`). A project without the library:
|
||||
code 1:1 from [section-code.md](./skills/ipal-block/resources/section-code.md). Each one has one job:
|
||||
|
||||
| Primitive | Does | Instead of |
|
||||
|---|---|---|
|
||||
@@ -638,7 +769,8 @@ empty fields, without guessing, without numbered slots. You design the schema fo
|
||||
(`ctaUrl` → "Cta Url"). Label 1–3 words, ≤ 30 characters.
|
||||
- Texts are `{ en: '…', pl: '…' }` (one key per admin language of the project):
|
||||
`label`, `admin.description`, option `label`, tab `label`, `labels.singular/plural`,
|
||||
`admin.group`. Type: `AdminText` from `@intecion/ipal-kit`.
|
||||
`admin.group`. Type: `AdminText` from `@intecion/ipal-kit`; shorthand `adminText('Title', 'Tytuł')` from
|
||||
`@intecion/ipal-kit/blocks`. In a schema file `ipal-audit` accepts both; the same words in a component are an error.
|
||||
- `admin.description` only when the label is not enough — one sentence ≤ 120 characters:
|
||||
what it does / where it shows, with a format example (`'Section id for #links, e.g. "pricing".'`),
|
||||
never how the code works (no component, function, env-var or package names).
|
||||
@@ -789,25 +921,38 @@ upload + `<Media>`; **a fixed set of UI icons** → a `select` field with names
|
||||
a `lucide-react` map in `src/components/icons/` (names in a separate file, so the block
|
||||
config does not import React). Code: [section-code.md](./skills/ipal-block/resources/section-code.md). **Never** SVG pasted into a section's JSX.
|
||||
|
||||
### 6.11 Styles
|
||||
### 6.11 Styles — the design-token standard ([design-tokens.md](../design-tokens.md))
|
||||
|
||||
- Tailwind in components; colors and fonts as **tokens** in `styles.css` (`@theme`)
|
||||
from the `DESIGN.md` source. In components only tokens (`bg-primary`), **never**
|
||||
`bg-[#ff6600]` or hex.
|
||||
- Map the plugin's tokens to the project: `--ipal-primary: var(--color-primary)`.
|
||||
- Fluid typography and spacing: `@import "@intecion/ipal-kit/fluid.css"` + mapping in
|
||||
`@theme` (`text-h1`, `py-section`, `px-gutter` — PROGRAMISTA §2.5). Do not write `clamp()`
|
||||
in components; other values from `DESIGN.md` → override the `--ipal-*` variables in `:root`.
|
||||
Every site uses the same `--ipal-*` token names and Tailwind utilities; only the values differ per brand.
|
||||
- **The brand lives in two files:** `DESIGN.md` (human, template `ipal-setup/resources/DESIGN.md`) and
|
||||
`src/design/tokens.ts` (`defineTokens` from `@intecion/ipal-kit/tokens`, template `ipal-setup/resources/tokens.ts`).
|
||||
`pnpm exec ipal-tokens` writes `src/design/tokens.css` (commit it) and fails on a WCAG AA contrast error.
|
||||
Never edit the generated file; never put brand values in `styles.css` or in a component.
|
||||
- **`styles.css` is the same on every site:** `@import "tailwindcss"`, `@intecion/ipal-kit/fluid-wide.css` (or
|
||||
`fluid.css`), `@intecion/ipal-kit/tokens.css`, `@intecion/ipal-kit/tailwind.css`, `../../design/tokens.css` (last), `@source` of the plugin's dist.
|
||||
- **Components use only the utilities from the preset:** `bg-bg`, `bg-surface`, `bg-surface-muted`, `bg-inverse`,
|
||||
`text-fg`, `text-fg-strong`, `text-fg-muted`, `text-on-primary`, `border-border`, `bg-primary hover:bg-primary-hover`,
|
||||
`text-link`, `outline-focus`, `text-h1`…`text-display`, `py-section`, `px-gutter`, `gap-gap`, `rounded-control`,
|
||||
`rounded-card`, `shadow-sm`, `max-w-container`, `duration-fast ease-out`. **Never** hex, `bg-[#…]`, `var(--color-…)`,
|
||||
or `dark:` for colours (the roles switch with `data-theme` themselves). `dark:` only for non-colour differences.
|
||||
- **Inverted section:** `<Section>` with `settings.background = inverted` → `bg-inverse` + `data-surface="inverse"`;
|
||||
content inside keeps `text-fg` / `text-link` / `bg-primary` (the scope re-maps them; a dark brand primary needs
|
||||
`primary-inverse` / `primary-inverse-text` in `tokens.ts` — the contrast report says when; default: the brand primary). `data-theme="dark"` on any element = a dark panel.
|
||||
- Fonts via `next/font` with `variable: '--font-family-body'` / `'--font-family-heading'` on `<html>` (not
|
||||
`--font-body`: a `var()` cycle with the `font-body` utility). Max 2 families.
|
||||
- Values a CSS variable can't reach (`next/og`, e-mail, `theme-color`): `resolveColors(tokens)` from `@/design/tokens`.
|
||||
In inline styles / charts: `IPAL_TOKENS.primary` or `ipalVar('primary')`; breakpoints in JS: `IPAL_BREAKPOINTS`.
|
||||
- A missing role every site would need → **ipal-plugin-gap**; a project-only decorative colour → `styles.css` below the
|
||||
imports + `DESIGN.md` → Deviations.
|
||||
- JSON-LD only via `<JsonLdGraph>` from `/rsc` — never your own `<script dangerouslySetInnerHTML>`.
|
||||
- Fonts via `next/font`, wired to `@theme` through a CSS variable.
|
||||
- No CSS Modules and no `style={{…}}` — exception: a dynamic value from data.
|
||||
- Variants → `Record<Variant, string>`, not ternary chains.
|
||||
Example `styles.css`: [section-code.md](./skills/ipal-block/resources/section-code.md).
|
||||
|
||||
### 6.11a Scaling (fluid / responsive) — from 360 px to 1920 px
|
||||
- **Scale from the plugin:** `fluid.css` (grows up to 1280 px) or `fluid-wide.css` (grows up to 1920 px —
|
||||
choose it when the site should look different on a 13″ laptop and a 27″ monitor). No `clamp()` in
|
||||
components; numbers from `DESIGN.md` → override `--ipal-*` in `:root`.
|
||||
- **Scale from the plugin:** `fluid-wide.css` (grows up to 1920 px — the default for new sites) or `fluid.css`
|
||||
(stops at 1280 px). No `clamp()` in components or `styles.css`; different numbers from `DESIGN.md` → min/max
|
||||
pairs in `src/design/tokens.ts` (`fs: { h1: ['2.25rem', '4rem'] }`, `space: { section: [3, 8] }`) → `ipal-tokens`.
|
||||
- **Screen height:** instead of `h-screen` / `100vh` → `min-h-[var(--ipal-hero-min-h)]` (svh, with
|
||||
a limit). Hero heading `--ipal-fs-display-fit`, hero spacing `--ipal-space-section-fit` — on
|
||||
1366×768 the hero CTA must be visible without scrolling.
|
||||
@@ -912,9 +1057,10 @@ project → **plugin gap**, not a copy.
|
||||
| Unusual form markup | `BuilderForm renderField` / `useBuilderForm` (`/client`) | forms.md |
|
||||
| A field filled in by the page (product variant, category) | `RenderForm values` / `prepareBuilderForm` + `BuilderForm values` | forms.md |
|
||||
| Sending | `createSubmitAction({ getCachedPayload, headers })` (`/server`) | forms.md |
|
||||
| A file on a form (CV, specification) | `forms: { attachments: true }` + a **File** field in the panel; the file is e-mailed to the company and **never stored** (no Media, no bucket, no download). Options `FormAttachmentsOption` (`maxSizeMB`, `maxTotalMB`, `maxFiles`, `fileTypes`: `FormFileType` / `FormFileDetect`, `allowRisky`, `scan`: `FormFileScanInput` → `FormFileScanResult`, `strictPdf`, `notice`, `maxConcurrent`, `path`, `submit`: `FormSubmitEndpointOptions`); block `buildFileBlock` / `fileBlock`; types `FORM_FILE_TYPES`, refused `RISKY_FILE_EXTENSIONS`; own markup `getFileProps` / `getFiles` / `removeFile`, `fileFieldRules`, `fileFieldError`, `formatFileSize`, `BuilderFileLimits`, `BuilderFile`; own transfer `submitForm({ files })` + `splitFormFiles`; transport ceiling `mailAttachmentLimit` | forms.md "Files", email.md "Attachments" |
|
||||
| Message texts and step button texts | Form messages → `getFormTexts(locale)` | notifications.md |
|
||||
| A form in the database | seed `ipal-form/resources/seed-form.template.ts` | forms.md, seeding.md |
|
||||
| Antispam / limit / IP | honeypot in `BuilderForm`, Turnstile from `SiteProviders` (`createSubmitAction({ turnstileHostnames })` pins the domain), `clientIp`, `setRateLimitStore`, `setUnknownIpFactor` | forms.md, turnstile.md |
|
||||
| Antispam / limit / IP | honeypot in `BuilderForm` (`getHoneypotProps` on `useBuilderForm`), Turnstile from `SiteProviders` (`createSubmitAction({ turnstileHostnames })` pins the domain), `clientIp`, `setRateLimitStore`, `setUnknownIpFactor` | forms.md, turnstile.md |
|
||||
| GTM event after sending | `buildFormAnalyticsFields` (panel) — `RenderForm` sends it itself | forms.md |
|
||||
| A form outside the builder (e.g. filters) | `useForm` + `buildValidator`, `required`, `email`… | forms.md |
|
||||
|
||||
@@ -939,7 +1085,9 @@ project → **plugin gap**, not a copy.
|
||||
| YouTube without cookies before a click | `<YouTubeEmbed>` (`/client`) | storage.md |
|
||||
| `next.config` | `buildImagesConfig`, `buildSecurityHeaders` (`csp`), `buildCsp`, `buildCspHeaders`, `buildAdminCsp` / `buildAdminCspHeaders`, `buildUploadSecurityHeaders`, `withSecurityConfig` (hides `X-Powered-By`) | storage.md, security.md |
|
||||
| CSP reports, nonces | `createCspReportRoute` (`parseCspReports`, type `CspViolation`), `createProxy({ csp })` + `<SiteProviders nonce>` (dynamic pages only), `createCspNonce`, `CSP_NONCE_HEADER`, `buildReportingEndpoints`, `cspHeaderKey`, `DEFAULT_CSP_REPORT_GROUP`; types `BuildAdminCspArgs`, `CspDirective`, `CspSources`, `CreateCspReportRouteArgs`, `WithSecurityConfigOptions` | security.md |
|
||||
| Fluid typography and spacing | `fluid.css` / `fluid-wide.css` (`--ipal-*` variables) | PROGRAMISTA §2.5 |
|
||||
| Fluid typography and spacing | `fluid.css` / `fluid-wide.css` (`--ipal-*` variables); your own sizes: `fluidClamp`, `FLUID_SCALE`, `FLUID_RANGES` | design-tokens.md |
|
||||
| Brand colours, fonts, radii, motion, dark mode | `tokens.css` + `tailwind.css`, `src/design/tokens.ts` (`defineTokens`, types `TokensInput`, `ColorInput`, `ColorRole`), `pnpm exec ipal-tokens` (`--check`, `--report`, `--warn-only`); building blocks `tokensToCss`, `defaultTokensCss`, `contrastReport` (`ContrastRow`), `contrastRatio`, `parseColor`, `resolveColors`, `IPAL_TOKENS`, `ipalVar`, `IpalTokenName`, `IPAL_BREAKPOINTS`, `COLOR_DEFAULTS`, `STATIC_DEFAULTS`, `FLUID_TOKENS`, `INVERSE_SCOPE`, `LEGACY_DARK_ROLES`, `LIGHT_SELECTOR`, `DARK_SELECTOR`, `INVERSE_SELECTOR`, `RemValue`, `FluidRange` | design-tokens.md |
|
||||
| Accessibility widget CSS | `@intecion/ipal-kit/a11y.css` (works through the tokens) | accessibility.md |
|
||||
|
||||
**Consent, analytics, operations**
|
||||
| Need | Use | Doc |
|
||||
@@ -948,12 +1096,13 @@ project → **plugin gap**, not a copy.
|
||||
| Settings window: in the bar / small / large with cookie details | `<CookieBanner settings="inline" \| "modal" \| "detailed">` — do not build your own window or cookie list | consent.md → "Large window with details" |
|
||||
| A consent-dependent script | `ConsentScript` | consent.md |
|
||||
| Cookie table on the policy page | `<CookieTable>` (`/rsc`), `getCookieTable` | consent.md |
|
||||
| Cookie list filled from the panel (drafts the editor accepts) | `ipalKit({ cookieScanner: true })` + `pnpm generate:importmap` + migration; project cookies: `cookieScanner.declarations` / `integrations` — do not type the list by hand or build your own scanner | cookie-scanner.md |
|
||||
| Cookie list filled from the panel (scan, then one approval adds every cookie to the list, the policy table and the detailed window) | `ipalKit({ cookieScanner: true })` + `pnpm generate:importmap` + migration; the editor approves on `/admin/cookie-approval`; project cookies: `cookieScanner.declarations` / `integrations`; per-entry review: `approval: false` — do not type the list by hand or build your own scanner or approval page | cookie-scanner.md |
|
||||
| Pre-consent check in a browser (button in the panel, violations, dashboard + e-mail warning) | `cookieScanner: { crawl: true }` + env `IPAL_COOKIE_SCAN_URL` / `IPAL_COOKIE_SCAN_TOKEN` (`ipalEnvRules({ cookieCrawl: true })`) + the site's `host=token` in the shared service's `IPAL_CRAWLER_SITES`; never Playwright/Chromium in the site | cookie-scanner.md → Browser crawl |
|
||||
| GA4, GTM, Pixel, Clarity, LinkedIn, TikTok | IDs in the panel — `SiteProviders` loads `Analytics` (`analytics={{ defer: true }}`; `consentMode: 'basic'` = no Google request before consent) | analytics.md |
|
||||
| Mail | `email: mailAdapter()`, `sendEmail` | email.md |
|
||||
| Env validation, health | `assertEnv(ipalEnvRules({…}))` (`/env`), `healthRoute` | env.md |
|
||||
| 2FA, white-label, headers | `twoFactor: { issuer, plugin: payloadTotp }`, `whiteLabel`, `buildSecurityHeaders` | security.md, white-label.md |
|
||||
| Panel link preview + noindex (site name, description, preview image, technology support credit) | on by default (`adminMeta`, `agency`) — do not hand-write `admin.meta` for it; override single keys in `admin.meta` or `adminMeta: { … }` | white-label.md |
|
||||
| Rate limit (forms, MCP, search) | built in; IP from `IPAL_IP_HEADER`; several instances → `setRateLimitStore` | forms.md |
|
||||
|
||||
**Compliance (PL/EU) — the mechanism from the plugin, the content from the client:** policy pages
|
||||
@@ -980,8 +1129,14 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both
|
||||
|---|---|---|
|
||||
| Plugin globals: write editor+ (Site integrations: admin) | — | `ipalKit({ globalOverrides: { <slug>: { access, admin, hooks } } })`; a function `(global) => global` takes over (`applyGlobalOverrides`) |
|
||||
| Global saves revalidate the layout (with `ipalKit({ revalidatePath })`) | omit `revalidatePath`; once: `context: { disableRevalidate: true }` | `buildGlobalRevalidateHook` on your own globals |
|
||||
| Form files (`forms.attachments`): off; when on — 10 MB, PDF/DOC/DOCX ticked, programs/macros/archives refused, no antivirus, Graph sends files of 3 MB and more through a draft it deletes | omit `attachments`; `forms.fields.file: false`; `mailAdapter({ graph: { largeAttachments: false } })` | `maxSizeMB` / `maxTotalMB` / `maxFiles` / `fileTypes` / `allowRisky` / `scan` / `strictPdf` / `notice` / `submit`; `buildFileBlock`; `formSubmissionOverrides.fields` for the file fields of a submission |
|
||||
| Staff features without `access` (no roles field): every logged-in account passes (`userMeetsRole`) | add `access` (roles decide) | `globalOverrides`, `forms.formSubmissionOverrides`, `consentLog.collectionOverrides`, `stats.collectionOverrides` |
|
||||
| Cookie check (`crawl`): start editor+ or the token, results token-only for the running job, latest result only, dashboard warning on, e-mail off until recipients are set | omit `crawl`; `crawl.dashboard: false` | `crawl.serviceUrl` / `token` / `siteUrl` / `maxPages` / `acceptSelector` / `consentMode` / `trackerHosts` / `globalOverride`; *Cookie check → Warning e-mails to*; building blocks `ingestCrawlResult`, `findCrawlViolations`, `parseCrawlResult` |
|
||||
| Cookie admin: one *Cookies* entry — review list and site check as tabs, their own entries out of the navigation (pages and API kept) | `cookieScanner.adminLayout: 'separate'` | `addCookieScannerTabs`, `CookieReviewTab`, `CookieSiteCheckTab`; `collectionOverrides` / `crawl.globalOverride` win |
|
||||
| Theme choice in localStorage under `theme` (next-themes' key); old `ipal-theme` moved before paint; declared to the cookie scanner as necessary local storage | — | `ipalKit({ theme: { storageKey } })`; `<ThemeSwitcher storageKey>` / `useTheme({ storageKey })` |
|
||||
| Cookie list entries have a **Type** (cookie / local / session storage), filled by the scanner; `<CookieTable>` shows it when needed | `<CookieTable storageColumn={false}>` | `storageColumn`, `storageTypes`, Cookies → Settings window → Cookie list headings → Type |
|
||||
| Text written in one language fills the empty languages (cookie list, cookie review), never over a language's own text | `fillEmptyLocales: false` | `fillEmptyLocales: { 'cookie-settings': [...], 'cookie-review': [...] }`; `buildFillEmptyLocalesGlobalHook` / `…CollectionHook` for your own globals and collections |
|
||||
| Cookie approval: one summary + **Approve and add** (editor+), unknown cookies approved as `marketing` + "Needs description", dashboard reminder while cookies wait; nothing reaches the cookie banner before approval | `cookieScanner.approval: false` (per-entry review) | `approval.unknownCategory`, `approval.dashboard: false`; building blocks `approveCookies`, `loadCookieApproval`, `countPendingCookies`, `flagGoneEntries`, `sameCookie` |
|
||||
| Cookie review: scan + review editor+, delete admin; Open Cookie Database "Functional" → `functional` | omit `cookieScanner` | `cookieScanner.access`, `collectionOverrides`, `databaseCategories`, `integrations`, `declarations`, `labels`, `syncAccepted: false`; building blocks `runCookieScan`, `collectCookieFindings`, `applyCookieFindings` |
|
||||
| Consent records / stats visits: read and delete admin (stats view and chart follow `stats-visits` read access) | omit `consentLog` / `stats` | `consentLog.collectionOverrides`, `stats.collectionOverrides` (object merges `access`/`admin`/`hooks`, function takes over; `applyCollectionOverride`) |
|
||||
| Injected `users`: admin manages everyone, others only themselves | — | `access.authAccess` (your keys win); your own `users` collection wins whole |
|
||||
@@ -1036,6 +1191,8 @@ Rules:
|
||||
|
||||
## 8. CODE STANDARDS
|
||||
|
||||
The short version is "Code rules" at the top; the details:
|
||||
|
||||
**Types**
|
||||
- No `any` / `@ts-ignore`. Unknown shape → `unknown` + a type guard.
|
||||
- Types from `@/payload-types` (`pnpm generate:types`), not hand-made copies.
|
||||
@@ -1107,6 +1264,8 @@ eliminate most of it.
|
||||
`PRODUCT.md` + `DESIGN.md` in the project root (`/impeccable init`,
|
||||
`/impeccable document`). The agent does not "polish" styles ad hoc. Impeccable does not
|
||||
touch content — design tokens in code are the visual system, not hardcoded content.
|
||||
Whatever writes the look, it lands in `DESIGN.md` (template sections) and `src/design/tokens.ts`, on the
|
||||
fixed `--ipal-*` roles (§6.11) — never as new token names or values in components.
|
||||
- **Editor:** all content in the panel.
|
||||
|
||||
Record the key project decisions (stack, decisions, page modes) in the project's `AGENTS.md`
|
||||
@@ -1117,9 +1276,12 @@ Record the key project decisions (stack, decisions, page modes) in the project's
|
||||
## 11. BEFORE YOU SAY "DONE"
|
||||
|
||||
**Run, do not guess** — `ipal-audit` (the §0b set + the rules below) and `ipal-seo-check`
|
||||
(GEO and SEO on the built site) instead of manual greps:
|
||||
(GEO and SEO on the built site) instead of manual greps; then `ipal-doctor` for the whole site against the team
|
||||
standard (versions, Node 22, layout, database names, env, headers, 2FA, cookie scanner, AGENTS.md, skills, seeds,
|
||||
block library — [doctor.md](../doctor.md)):
|
||||
```bash
|
||||
bash .agents/skills/ipal-audit/scripts/audit.sh
|
||||
pnpm exec ipal-doctor # + --deep --url http://localhost:3000 on the built site
|
||||
node .agents/skills/ipal-seo-check/scripts/seo-check.mjs http://localhost:3000
|
||||
pnpm generate:types && pnpm tsc --noEmit
|
||||
pnpm build # --webpack in the script; locally, not only dev
|
||||
@@ -1160,6 +1322,7 @@ Anything that needs a developer → move it to the panel.
|
||||
| Accessibility widget (optional) | [accessibility.md](../accessibility.md) |
|
||||
| GA4, GTM, Meta Pixel, Clarity, LinkedIn, TikTok | [analytics.md](../analytics.md) |
|
||||
| Blocks, RenderBlocks, enhanceProps | [blocks.md](../blocks.md) |
|
||||
| Block library: 15 ready sections, page templates, eject | [block-library.md](../block-library.md) |
|
||||
| Cookie consent, banner | [consent.md](../consent.md) |
|
||||
| Cookie scanner (review list, Open Cookie Database) | [cookie-scanner.md](../cookie-scanner.md) |
|
||||
| Routing, archives, redirects, Markdown, search | [content.md](../content.md) |
|
||||
@@ -1175,6 +1338,7 @@ Anything that needs a developer → move it to the panel.
|
||||
| Under-construction mode | [construction.md](../construction.md) |
|
||||
| Visit statistics (optional) | [stats.md](../stats.md) |
|
||||
| Light / dark theme | [theme.md](../theme.md) |
|
||||
| Design tokens, `ipal-tokens`, DESIGN.md | [design-tokens.md](../design-tokens.md) |
|
||||
| Payload helpers (getSiteSettings…) | [payload-helpers.md](../payload-helpers.md) |
|
||||
| Rich text | [richtext.md](../richtext.md) |
|
||||
| Headers, CSP, 2FA, panel path | [security.md](../security.md) |
|
||||
@@ -1185,10 +1349,12 @@ Anything that needs a developer → move it to the panel.
|
||||
| R2, `buildImagesConfig`, YouTube | [storage.md](../storage.md) |
|
||||
| Front end: `createContentHelpers` (`@/lib/content`), `createPageRoute`, `SiteProviders` | [frontend.md](../frontend.md) |
|
||||
| Integrations (the `site-integrations` global, statuses, email test) | [integrations.md](../integrations.md) |
|
||||
| New site from the reference site: `ipal-kit create`, `@intecion/ipal-kit/starter` | [project-starter.md](../project-starter.md) |
|
||||
| Deployment, production env, health check | [deployment.md](../deployment.md) |
|
||||
| Seeds on production: create-only, dry run, backup, update guard | [seeding.md](../seeding.md) |
|
||||
| Meta Pixel / GA4 via GTM | [gtm-meta-pixel.md](../gtm-meta-pixel.md) |
|
||||
| Turnstile | [turnstile.md](../turnstile.md) |
|
||||
| ipal-doctor: the site against the team standard, `ipal-doctor.json`, `/api/ipal/doctor` | [doctor.md](../doctor.md) |
|
||||
| Panel white-label | [white-label.md](../white-label.md) |
|
||||
|
||||
---
|
||||
@@ -1210,14 +1376,21 @@ Before your first change, read all of:
|
||||
Module details: `node_modules/@intecion/ipal-kit/docs/<module>.md`.
|
||||
Skills: `.agents/skills/ipal-*` (refresh: `pnpm exec ipal-skills`). Always run `ipal-audit` before "done".
|
||||
The rules in AGENT.md take precedence over your general knowledge of Next/Payload.
|
||||
ipal-kit helps, never limits: first the plugin's option / exported builder; missing → plugin gap (ipal-plugin-gap), never a patch in `node_modules`.
|
||||
ipal-kit first: anything the plugin covers is built with the plugin. Missing or broken → plugin gap (ipal-plugin-gap): report to the owner and wait; never a hand-built replacement or a patch in `node_modules`.
|
||||
Code rules: AGENT.md "Code rules" (single responsibility, no duplicates, typed, texts from the panel, checks).
|
||||
Write everything in this file in English.
|
||||
|
||||
## Site map
|
||||
- <pages from the brief, the sections on each — written by ipal-site>
|
||||
|
||||
## Project decisions
|
||||
- Architecture answers (AGENT.md "Ask before you build"), one line each: languages + default + URLs ·
|
||||
styling · pages/collections · forms + e-mail · analytics/consent/cookie scan · SEO/GEO · database (+ names
|
||||
`<domain>_prod` / `<domain>_dev`, e.g. `intecioncom_prod`) + media ·
|
||||
2FA/white-label/credit · hosting + domains + DNS
|
||||
- <client-specific decisions, e.g. "blog without authors", "404 = homepage">
|
||||
- <approved workarounds: what, why, plugin-request file, owner's approval>
|
||||
- Launch date: <date> — from then on seeds touch named records only (AGENT.md "seeding after launch")
|
||||
- <exceptions to the rules — with the reason>
|
||||
- <only on a client decision> ipal-audit-skip: <keys from AGENT.md §0b> — <reason, source of the decision>
|
||||
```
|
||||
@@ -1252,9 +1425,10 @@ the task matches — manually: `/<name>`.
|
||||
| `ipal-audit` | before every "done" — the §0b set + the §11 checks + panel (§6.5a) + hardcoding in JSX + tsc + build |
|
||||
| `ipal-seo-check` | the running site through the eyes of Googlebot and AI agents (head, canonical, hreflang, sitemap, 404, JSON-LD, llms, Markdown, MCP) |
|
||||
| `ipal-consent-check` | browser: no tracking pixels or cookies before consent; the Google tag may load before consent only in Consent Mode `advanced` (all signals `denied`) — a client who wants zero requests gets `consentMode: 'basic'` |
|
||||
| `ipal-plugin-gap` | ipal-kit has a bug or is missing a feature — report + a marked workaround, the work goes on |
|
||||
| `ipal-doctor` | the whole site against the team standard in one command (`pnpm exec ipal-doctor`): versions, Node 22, layout, database names, env, headers, CSP, 2FA, cookie scanner, adminMeta, AGENTS.md, skills, seeds, block library, pnpm audit; `--url` / `--deep` for the running site and the database; `--strict` in the CI of a new site |
|
||||
| `ipal-plugin-gap` | ipal-kit has a bug or is missing a feature — report to the owner, wait for the decision; a marked workaround only after approval |
|
||||
|
||||
Run the scripts in the skills, do not read them (the output is enough): `ipal-audit/scripts/audit.sh`,
|
||||
Run the scripts in the skills, do not read them (the output is enough): `ipal-audit/scripts/audit.sh`, `pnpm exec ipal-doctor`,
|
||||
`ipal-seo-check/scripts/seo-check.mjs`, `ipal-consent-check/scripts/consent-check.mjs`,
|
||||
`ipal-locale-add/scripts/locale-coverage.ts`; templates to copy are in `resources/`.
|
||||
|
||||
@@ -1274,6 +1448,27 @@ It copies only the `ipal-*` folders: adds new ones, replaces existing ones entir
|
||||
retired ones. Name the project's own skills **without** the `ipal-` prefix — they stay untouched.
|
||||
`--dest` must be a subdirectory of the project. Commit the copied `ipal-*` to the project repo.
|
||||
|
||||
**External skills (opt-in)** — well-known third-party skills, vendored into the package at pinned commits
|
||||
(text only, licence + `SOURCE.md` in each folder). `ipal-skills` downloads nothing; it checks every file
|
||||
against `docs/agent/external/manifest.json` before copying:
|
||||
```bash
|
||||
pnpm exec ipal-skills --external # all ext-* next to the ipal-* skills
|
||||
pnpm exec ipal-skills --external ext-accessibility,ext-payload # only these
|
||||
```
|
||||
| Skill | Publisher · licence | What it is for | Our override |
|
||||
|---|---|---|---|
|
||||
| `ext-react-best-practices` | Vercel · MIT | React/Next performance rules (waterfalls, bundles, RSC, re-renders) | no `swr` / client-fetch libraries — Server Components + Payload / `@/lib/content` |
|
||||
| `ext-composition-patterns` | Vercel · MIT | compound components instead of boolean props, React 19 APIs | block schema and `RenderBlocks` follow §6 |
|
||||
| `ext-accessibility` | Addy Osmani · MIT | WCAG 2.2 audit and fixes | Lighthouse / axe only as pinned devDependencies; ipal-kit components fixed via props or a plugin gap |
|
||||
| `ext-frontend-design` | Anthropic · Apache-2.0 | distinctive visual direction, design quality floor | `DESIGN.md` tokens win; use it to write/extend `DESIGN.md` + `src/design/tokens.ts`, mapping its palette onto the `--ipal-*` roles (design-tokens.md) — never new token names, never hex/fonts/text in components |
|
||||
| `ext-payload` | Payload CMS · MIT | Payload 3 reference (v3.92.1) | reference only, never Payload 4 guidance; ipal-kit features first |
|
||||
|
||||
**Our rules win.** Every `ext-*` SKILL.md starts with an override note; when an external skill conflicts with
|
||||
this file, the project's `AGENTS.md` or `DESIGN.md`, those win — ipal-kit first, Payload data fetching over `swr`,
|
||||
`DESIGN.md` tokens, Payload 3 not 4. `ext-*` folders are touched only with `--external`, and only those with
|
||||
ipal-kit's `SOURCE.md`; do not name the project's own skills `ext-…`. Use them only after the owner chose them
|
||||
("Project decisions").
|
||||
|
||||
**`tsconfig.json` must exclude the skills directory** (it contains `.ts`/`.tsx` templates that
|
||||
break `tsc` and `next build`): `"exclude": ["node_modules", ".agents"]` (with `--dest
|
||||
.claude/skills` — `".claude"`). Without it `ipal-skills` prints a warning and exits with
|
||||
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Addy Osmani
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+475
@@ -0,0 +1,475 @@
|
||||
---
|
||||
name: ext-accessibility
|
||||
description: Audit and improve web accessibility following WCAG 2.2 guidelines. Use when asked to "improve accessibility", "a11y audit", "WCAG compliance", "screen reader support", "keyboard navigation", or "make accessible".
|
||||
license: MIT
|
||||
metadata:
|
||||
author: web-quality-skills
|
||||
version: "2.0"
|
||||
---
|
||||
|
||||
> **Project rules win.** Vendored by @intecion/ipal-kit as guidance. When this skill conflicts with
|
||||
> `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md`, the project's `AGENTS.md` or `DESIGN.md`, those win:
|
||||
> ipal-kit features first (the `ipal-reference` skill), Payload 3 + Next 16 App Router, data from Server Components
|
||||
> through Payload / `@/lib/content`, every visible text from the CMS, design values from `DESIGN.md` tokens.
|
||||
> Never add a dependency this skill suggests without the owner's decision.
|
||||
>
|
||||
> **Tools:** never run `npx lighthouse` / `npx @axe-core/cli` unpinned — add them as devDependencies at fixed versions
|
||||
> first. Use the ipal-kit components (CookieBanner, AccessibilityWidget, RenderForm…) and fix their markup through
|
||||
> their props or a plugin gap report, not by copying them.
|
||||
|
||||
|
||||
# Accessibility (a11y)
|
||||
|
||||
Comprehensive accessibility guidelines based on WCAG 2.2 and Lighthouse accessibility audits. Goal: make content usable by everyone, including people with disabilities.
|
||||
|
||||
## Evidence-led audit workflow
|
||||
|
||||
When a rendered page is available:
|
||||
|
||||
1. Run a live Lighthouse Accessibility audit when that capability is available; with Chrome DevTools MCP, use `lighthouse_audit`. Use mobile navigation mode for a general public page or snapshot mode when reloading would lose authenticated or user-created state.
|
||||
2. Use failed audit nodes to localize the relevant component or template instead of searching the whole repository for generic patterns.
|
||||
3. Inspect a rendered accessibility-tree snapshot for names, roles, states, landmarks, and heading structure; with Chrome DevTools MCP, use `take_snapshot`. Exercise the affected flow with the keyboard.
|
||||
4. Fix the source, then re-run the same audit and manual interaction.
|
||||
|
||||
If the live tools are unavailable, use Lighthouse CLI or axe for automated coverage and complete the same manual checks. Automated tools detect only a subset of accessibility barriers: a score of 100 is not WCAG conformance, and a low score does not replace issue-level evidence.
|
||||
|
||||
## WCAG Principles: POUR
|
||||
|
||||
| Principle | Description |
|
||||
|-----------|-------------|
|
||||
| **P**erceivable | Content can be perceived through different senses |
|
||||
| **O**perable | Interface can be operated by all users |
|
||||
| **U**nderstandable | Content and interface are understandable |
|
||||
| **R**obust | Content works with assistive technologies |
|
||||
|
||||
## Conformance levels
|
||||
|
||||
| Level | Requirement | Target |
|
||||
|-------|-------------|--------|
|
||||
| **A** | Minimum accessibility | Must pass |
|
||||
| **AA** | Standard compliance | Should pass (legal requirement in many jurisdictions) |
|
||||
| **AAA** | Enhanced accessibility | Nice to have |
|
||||
|
||||
---
|
||||
|
||||
## Perceivable
|
||||
|
||||
### Text alternatives (1.1)
|
||||
|
||||
**Images require alt text:**
|
||||
```html
|
||||
<!-- ❌ Missing alt -->
|
||||
<img src="chart.png">
|
||||
|
||||
<!-- ✅ Descriptive alt -->
|
||||
<img src="chart.png" alt="Bar chart showing 40% increase in Q3 sales">
|
||||
|
||||
<!-- ✅ Decorative image (empty alt) -->
|
||||
<img src="decorative-border.png" alt="" role="presentation">
|
||||
|
||||
<!-- ✅ Complex image with longer description -->
|
||||
<figure>
|
||||
<img src="infographic.png" alt="2024 market trends infographic"
|
||||
aria-describedby="infographic-desc">
|
||||
<figcaption id="infographic-desc">
|
||||
<!-- Detailed description -->
|
||||
</figcaption>
|
||||
</figure>
|
||||
```
|
||||
|
||||
**Icon buttons need accessible names:**
|
||||
```html
|
||||
<!-- ❌ No accessible name -->
|
||||
<button><svg><!-- menu icon --></svg></button>
|
||||
|
||||
<!-- ✅ Using aria-label -->
|
||||
<button aria-label="Open menu">
|
||||
<svg aria-hidden="true"><!-- menu icon --></svg>
|
||||
</button>
|
||||
|
||||
<!-- ✅ Using visually hidden text -->
|
||||
<button>
|
||||
<svg aria-hidden="true"><!-- menu icon --></svg>
|
||||
<span class="visually-hidden">Open menu</span>
|
||||
</button>
|
||||
```
|
||||
|
||||
**Visually hidden class:**
|
||||
```css
|
||||
.visually-hidden {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
padding: 0;
|
||||
margin: -1px;
|
||||
overflow: hidden;
|
||||
clip: rect(0, 0, 0, 0);
|
||||
white-space: nowrap;
|
||||
border: 0;
|
||||
}
|
||||
```
|
||||
|
||||
### Color contrast (1.4.3, 1.4.6)
|
||||
|
||||
| Text Size | AA minimum | AAA enhanced |
|
||||
|-----------|------------|--------------|
|
||||
| Normal text (< 18px / < 14px bold) | 4.5:1 | 7:1 |
|
||||
| Large text (≥ 18px / ≥ 14px bold) | 3:1 | 4.5:1 |
|
||||
| UI components & graphics | 3:1 | 3:1 |
|
||||
|
||||
```css
|
||||
/* ❌ Low contrast (2.5:1) */
|
||||
.low-contrast {
|
||||
color: #999;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
/* ✅ Sufficient contrast (7:1) */
|
||||
.high-contrast {
|
||||
color: #333;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
/* ✅ Focus states need contrast too (3:1 against background, WCAG 1.4.11) */
|
||||
:focus-visible {
|
||||
outline: 2px solid currentColor;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
```
|
||||
|
||||
**Don't rely on color alone:**
|
||||
```html
|
||||
<!-- ❌ Only color indicates error -->
|
||||
<input class="error-border">
|
||||
<style>.error-border { border-color: red; }</style>
|
||||
|
||||
<!-- ✅ Color + icon + text -->
|
||||
<div class="field-error">
|
||||
<input aria-invalid="true" aria-describedby="email-error">
|
||||
<span id="email-error" class="error-message">
|
||||
<svg aria-hidden="true"><!-- error icon --></svg>
|
||||
Please enter a valid email address
|
||||
</span>
|
||||
</div>
|
||||
```
|
||||
|
||||
### Media alternatives (1.2)
|
||||
|
||||
```html
|
||||
<!-- Video with captions -->
|
||||
<video controls>
|
||||
<source src="video.mp4" type="video/mp4">
|
||||
<track kind="captions" src="captions.vtt" srclang="en" label="English" default>
|
||||
<track kind="descriptions" src="descriptions.vtt" srclang="en" label="Descriptions">
|
||||
</video>
|
||||
|
||||
<!-- Audio with transcript -->
|
||||
<audio controls>
|
||||
<source src="podcast.mp3" type="audio/mp3">
|
||||
</audio>
|
||||
<details>
|
||||
<summary>Transcript</summary>
|
||||
<p>Full transcript text...</p>
|
||||
</details>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Operable
|
||||
|
||||
### Keyboard accessible (2.1)
|
||||
|
||||
**All functionality must be keyboard accessible.** Prefer native interactive elements — `<button>`, `<a href>`, and form controls handle Enter/Space activation, focus, and assistive-tech semantics for free. Only add manual keyboard handling when you cannot use a native element.
|
||||
|
||||
```html
|
||||
<!-- ❌ Non-interactive element with click only: not focusable, no keyboard activation -->
|
||||
<div class="card" onclick="handleAction()">Open</div>
|
||||
|
||||
<!-- ✅ Best: use a native button -->
|
||||
<button type="button" onclick="handleAction()">Open</button>
|
||||
```
|
||||
|
||||
```javascript
|
||||
// ✅ When you MUST use a non-interactive element (e.g. div with role="button"),
|
||||
// make it focusable AND handle keyboard activation. Do NOT add this to a native
|
||||
// <button> — Enter/Space already fire click, so you'd double-trigger.
|
||||
element.setAttribute('role', 'button');
|
||||
element.setAttribute('tabindex', '0');
|
||||
element.addEventListener('click', handleAction);
|
||||
element.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
handleAction();
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
**No keyboard traps.** Users must be able to Tab into and out of every component. Use the [modal focus trap pattern](references/A11Y-PATTERNS.md#modal-focus-trap) for dialogs—the native `<dialog>` element handles this automatically.
|
||||
|
||||
### Focus visible (2.4.7)
|
||||
|
||||
```css
|
||||
/* ❌ Never remove focus outlines */
|
||||
*:focus { outline: none; }
|
||||
|
||||
/* ✅ Use :focus-visible for keyboard-only focus */
|
||||
:focus {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
:focus-visible {
|
||||
outline: 2px solid currentColor; /* inherits text color → already contrast-checked */
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
/* ✅ Or pick a brand color and verify ≥3:1 contrast against every background it lands on */
|
||||
button:focus-visible {
|
||||
box-shadow: 0 0 0 3px rgba(0, 95, 204, 0.5);
|
||||
}
|
||||
```
|
||||
|
||||
### Focus not obscured (2.4.11) — new in 2.2
|
||||
|
||||
When an element receives keyboard focus, it must not be entirely hidden by other author-created content such as sticky headers, footers, or overlapping panels. At Level AAA (2.4.12), no part of the focused element may be hidden.
|
||||
|
||||
```css
|
||||
/* ✅ Account for sticky headers when scrolling to focused elements */
|
||||
:target {
|
||||
scroll-margin-top: 80px;
|
||||
}
|
||||
|
||||
/* ✅ Ensure focused items clear fixed/sticky bars */
|
||||
:focus {
|
||||
scroll-margin-top: 80px;
|
||||
scroll-margin-bottom: 60px;
|
||||
}
|
||||
```
|
||||
|
||||
### Skip links (2.4.1)
|
||||
|
||||
Provide a skip link so keyboard users can bypass repetitive navigation. See the [skip link pattern](references/A11Y-PATTERNS.md#skip-link) for full markup and styles.
|
||||
|
||||
### Target size (2.5.8) — new in 2.2
|
||||
|
||||
Interactive targets must be at least **24 × 24 CSS pixels** (AA). Exceptions: inline text links, elements where the browser controls the size, and targets where a 24px circle centered on the bounding box does not overlap another target.
|
||||
|
||||
```css
|
||||
/* ✅ Minimum target size */
|
||||
button,
|
||||
[role="button"],
|
||||
input[type="checkbox"] + label,
|
||||
input[type="radio"] + label {
|
||||
min-width: 24px;
|
||||
min-height: 24px;
|
||||
}
|
||||
|
||||
/* ✅ Comfortable target size (recommended 44×44) */
|
||||
.touch-target {
|
||||
min-width: 44px;
|
||||
min-height: 44px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
```
|
||||
|
||||
### Dragging movements (2.5.7) — new in 2.2
|
||||
|
||||
Any action that requires dragging must have a single-pointer alternative (e.g., buttons, inputs). See the [dragging movements pattern](references/A11Y-PATTERNS.md#dragging-movements) for a sortable-list example.
|
||||
|
||||
### Timing (2.2)
|
||||
|
||||
```javascript
|
||||
// Allow users to extend time limits
|
||||
function showSessionWarning() {
|
||||
const modal = createModal({
|
||||
title: 'Session Expiring',
|
||||
content: 'Your session will expire in 2 minutes.',
|
||||
actions: [
|
||||
{ label: 'Extend session', action: extendSession },
|
||||
{ label: 'Log out', action: logout }
|
||||
],
|
||||
timeout: 120000
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### Motion (2.3)
|
||||
|
||||
```css
|
||||
/* Respect reduced motion preference */
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
animation-duration: 0.01ms !important;
|
||||
animation-iteration-count: 1 !important;
|
||||
transition-duration: 0.01ms !important;
|
||||
scroll-behavior: auto !important;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Understandable
|
||||
|
||||
### Page language (3.1.1)
|
||||
|
||||
```html
|
||||
<!-- ❌ No language specified -->
|
||||
<html>
|
||||
|
||||
<!-- ✅ Language specified -->
|
||||
<html lang="en">
|
||||
|
||||
<!-- ✅ Language changes within page -->
|
||||
<p>The French word for hello is <span lang="fr">bonjour</span>.</p>
|
||||
```
|
||||
|
||||
### Consistent navigation (3.2.3)
|
||||
|
||||
```html
|
||||
<!-- Navigation should be consistent across pages -->
|
||||
<nav aria-label="Main">
|
||||
<ul>
|
||||
<li><a href="/" aria-current="page">Home</a></li>
|
||||
<li><a href="/products">Products</a></li>
|
||||
<li><a href="/about">About</a></li>
|
||||
</ul>
|
||||
</nav>
|
||||
```
|
||||
|
||||
### Consistent help (3.2.6) — new in 2.2
|
||||
|
||||
If a help mechanism (contact info, chat widget, FAQ link, self-help option) is repeated across multiple pages, it must appear in the **same relative order** each time. Users who rely on consistent placement shouldn't have to hunt for help on every page.
|
||||
|
||||
### Form labels (3.3.2)
|
||||
|
||||
Every input needs a programmatically associated label. See the [form labels pattern](references/A11Y-PATTERNS.md#form-labels) for explicit, implicit, and instructional examples.
|
||||
|
||||
### Error handling (3.3.1, 3.3.3)
|
||||
|
||||
Announce errors to screen readers with `role="alert"` or `aria-live`, set `aria-invalid="true"` on invalid fields, and focus the first error on submit. See the [error handling pattern](references/A11Y-PATTERNS.md#error-handling) for full markup and JS.
|
||||
|
||||
### Redundant entry (3.3.7) — new in 2.2
|
||||
|
||||
Don't force users to re-enter information they already provided in the same session. Auto-populate from earlier steps, or let users select from previously entered values. Exceptions: security re-confirmation and content that has expired.
|
||||
|
||||
```html
|
||||
<!-- ✅ Auto-fill shipping address from billing -->
|
||||
<fieldset>
|
||||
<legend>Shipping address</legend>
|
||||
<label>
|
||||
<input type="checkbox" id="same-as-billing" checked>
|
||||
Same as billing address
|
||||
</label>
|
||||
<!-- Fields auto-populated when checked -->
|
||||
</fieldset>
|
||||
```
|
||||
|
||||
### Accessible authentication (3.3.8) — new in 2.2
|
||||
|
||||
Login flows must not rely on cognitive function tests (e.g., remembering a password, solving a puzzle) unless at least one of:
|
||||
- A copy-paste or autofill mechanism is available
|
||||
- An alternative method exists (e.g., passkey, SSO, email link)
|
||||
- The test uses object recognition or personal content (AA only; AAA removes this exception)
|
||||
|
||||
```html
|
||||
<!-- ✅ Allow paste in password fields -->
|
||||
<input type="password" id="password" autocomplete="current-password">
|
||||
|
||||
<!-- ✅ Offer passwordless alternatives -->
|
||||
<button type="button">Sign in with passkey</button>
|
||||
<button type="button">Email me a login link</button>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Robust
|
||||
|
||||
### ARIA usage (4.1.2)
|
||||
|
||||
**Prefer native elements:**
|
||||
```html
|
||||
<!-- ❌ ARIA role on div -->
|
||||
<div role="button" tabindex="0">Click me</div>
|
||||
|
||||
<!-- ✅ Native button -->
|
||||
<button>Click me</button>
|
||||
|
||||
<!-- ❌ ARIA checkbox -->
|
||||
<div role="checkbox" aria-checked="false">Option</div>
|
||||
|
||||
<!-- ✅ Native checkbox -->
|
||||
<label><input type="checkbox"> Option</label>
|
||||
```
|
||||
|
||||
**When ARIA is needed,** use the correct roles and states. See the [ARIA tabs pattern](references/A11Y-PATTERNS.md#aria-tabs) for a complete tablist example.
|
||||
|
||||
### Live regions (4.1.3)
|
||||
|
||||
Use `aria-live` regions to announce dynamic content changes without moving focus. See the [live regions pattern](references/A11Y-PATTERNS.md#live-regions-and-notifications) for markup and a `showNotification()` helper.
|
||||
|
||||
---
|
||||
|
||||
## Testing checklist
|
||||
|
||||
### Automated testing
|
||||
|
||||
Prefer a live Lighthouse audit that returns failing rendered nodes directly to the agent. With Chrome DevTools MCP, this is `lighthouse_audit`. Otherwise:
|
||||
|
||||
```bash
|
||||
# Lighthouse accessibility audit
|
||||
npx lighthouse https://example.com --only-categories=accessibility
|
||||
|
||||
# axe-core
|
||||
npm install @axe-core/cli -g
|
||||
axe https://example.com
|
||||
```
|
||||
|
||||
### Manual testing
|
||||
|
||||
- [ ] **Keyboard navigation:** Tab through entire page, use Enter/Space to activate
|
||||
- [ ] **Screen reader:** Test with VoiceOver (Mac), NVDA (Windows), or TalkBack (Android)
|
||||
- [ ] **Zoom:** Content usable at 200% zoom
|
||||
- [ ] **High contrast:** Test with Windows High Contrast Mode
|
||||
- [ ] **Reduced motion:** Test with `prefers-reduced-motion: reduce`
|
||||
- [ ] **Focus order:** Logical and follows visual order
|
||||
- [ ] **Target size:** Interactive elements meet 24×24px minimum
|
||||
|
||||
See the [screen reader commands reference](references/A11Y-PATTERNS.md#screen-reader-commands) for VoiceOver and NVDA shortcuts.
|
||||
|
||||
---
|
||||
|
||||
## Common issues by impact
|
||||
|
||||
### Critical (fix immediately)
|
||||
1. Missing form labels
|
||||
2. Missing image alt text
|
||||
3. Insufficient color contrast
|
||||
4. Keyboard traps
|
||||
5. No focus indicators
|
||||
|
||||
### Serious (fix before launch)
|
||||
1. Missing page language
|
||||
2. Missing heading structure
|
||||
3. Non-descriptive link text
|
||||
4. Auto-playing media
|
||||
5. Missing skip links
|
||||
|
||||
### Moderate (fix soon)
|
||||
1. Missing ARIA labels on icons
|
||||
2. Inconsistent navigation
|
||||
3. Missing error identification
|
||||
4. Timing without controls
|
||||
5. Missing landmark regions
|
||||
|
||||
## References
|
||||
|
||||
- [WCAG 2.2 Quick Reference](https://www.w3.org/WAI/WCAG22/quickref/)
|
||||
- [WAI-ARIA Authoring Practices](https://www.w3.org/WAI/ARIA/apg/)
|
||||
- [Deque axe Rules](https://dequeuniversity.com/rules/axe/)
|
||||
- [Web Quality Audit](../web-quality-audit/SKILL.md)
|
||||
- [WCAG criteria reference](references/WCAG.md)
|
||||
- [Accessibility code patterns](references/A11Y-PATTERNS.md)
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
# ext-accessibility
|
||||
|
||||
Vendored by @intecion/ipal-kit (`ipal-skills --external`). Do not edit — regenerate with
|
||||
`scripts/vendor-external-skills.mjs` in the ipal-kit repository.
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Publisher | Addy Osmani |
|
||||
| Source | https://github.com/addyosmani/web-quality-skills/tree/afa8da942115f2961fdbfa80807ea0b232ff6c00/skills/accessibility |
|
||||
| Commit | `afa8da942115f2961fdbfa80807ea0b232ff6c00` |
|
||||
| Licence | MIT (see the LICENSE file in this folder) |
|
||||
|
||||
Changes from the upstream text: the `name` in the SKILL.md frontmatter is `ext-accessibility`, and an
|
||||
override note (project rules win) is inserted after the frontmatter. Nothing else is changed.
|
||||
@@ -0,0 +1,233 @@
|
||||
# Accessibility Code Patterns
|
||||
|
||||
Practical, copy-paste-ready patterns for common accessibility requirements. Each pattern is self-contained and linked from the main [SKILL.md](../SKILL.md).
|
||||
|
||||
---
|
||||
|
||||
## Modal focus trap
|
||||
|
||||
Trap keyboard focus inside a modal dialog so Tab/Shift+Tab cycle through its focusable elements and Escape closes it.
|
||||
|
||||
```javascript
|
||||
function openModal(modal) {
|
||||
const focusableElements = modal.querySelectorAll(
|
||||
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
|
||||
);
|
||||
const firstElement = focusableElements[0];
|
||||
const lastElement = focusableElements[focusableElements.length - 1];
|
||||
|
||||
modal.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Tab') {
|
||||
if (e.shiftKey && document.activeElement === firstElement) {
|
||||
e.preventDefault();
|
||||
lastElement.focus();
|
||||
} else if (!e.shiftKey && document.activeElement === lastElement) {
|
||||
e.preventDefault();
|
||||
firstElement.focus();
|
||||
}
|
||||
}
|
||||
if (e.key === 'Escape') {
|
||||
closeModal();
|
||||
}
|
||||
});
|
||||
|
||||
firstElement.focus();
|
||||
}
|
||||
```
|
||||
|
||||
The native `<dialog>` element handles focus trapping automatically—prefer it when browser support allows.
|
||||
|
||||
---
|
||||
|
||||
## Skip link
|
||||
|
||||
Allows keyboard users to bypass repetitive navigation and jump straight to main content.
|
||||
|
||||
```html
|
||||
<body>
|
||||
<a href="#main-content" class="skip-link">Skip to main content</a>
|
||||
<header><!-- navigation --></header>
|
||||
<main id="main-content" tabindex="-1">
|
||||
<!-- main content -->
|
||||
</main>
|
||||
</body>
|
||||
```
|
||||
|
||||
```css
|
||||
.skip-link {
|
||||
position: absolute;
|
||||
top: -40px;
|
||||
left: 0;
|
||||
background: #000;
|
||||
color: #fff;
|
||||
padding: 8px 16px;
|
||||
z-index: 100;
|
||||
}
|
||||
|
||||
.skip-link:focus {
|
||||
top: 0;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Error handling
|
||||
|
||||
Announce errors to screen readers and focus the first invalid field on submit.
|
||||
|
||||
```html
|
||||
<form novalidate>
|
||||
<div class="field" aria-live="polite">
|
||||
<label for="email">Email</label>
|
||||
<input type="email" id="email"
|
||||
aria-invalid="true"
|
||||
aria-describedby="email-error">
|
||||
<p id="email-error" class="error" role="alert">
|
||||
Please enter a valid email address (e.g., name@example.com)
|
||||
</p>
|
||||
</div>
|
||||
</form>
|
||||
```
|
||||
|
||||
```javascript
|
||||
form.addEventListener('submit', (e) => {
|
||||
const firstError = form.querySelector('[aria-invalid="true"]');
|
||||
if (firstError) {
|
||||
e.preventDefault();
|
||||
firstError.focus();
|
||||
|
||||
const errorSummary = document.getElementById('error-summary');
|
||||
errorSummary.textContent =
|
||||
`${errors.length} errors found. Please fix them and try again.`;
|
||||
errorSummary.focus();
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Form labels
|
||||
|
||||
Every input needs an associated label—either explicit (`for`/`id`) or implicit (wrapping `<label>`).
|
||||
|
||||
```html
|
||||
<!-- ❌ No label association -->
|
||||
<input type="email" placeholder="Email">
|
||||
|
||||
<!-- ✅ Explicit label -->
|
||||
<label for="email">Email address</label>
|
||||
<input type="email" id="email" name="email"
|
||||
autocomplete="email" required>
|
||||
|
||||
<!-- ✅ Implicit label -->
|
||||
<label>
|
||||
Email address
|
||||
<input type="email" name="email" autocomplete="email" required>
|
||||
</label>
|
||||
|
||||
<!-- ✅ With instructions -->
|
||||
<label for="password">Password</label>
|
||||
<input type="password" id="password"
|
||||
aria-describedby="password-requirements">
|
||||
<p id="password-requirements">
|
||||
Must be at least 8 characters with one number.
|
||||
</p>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Dragging movements
|
||||
|
||||
Any action triggered by dragging must offer a single-pointer alternative (WCAG 2.5.7).
|
||||
|
||||
```html
|
||||
<!-- ❌ Drag-only reorder -->
|
||||
<ul class="sortable-list" draggable="true">
|
||||
<li>Item 1</li>
|
||||
<li>Item 2</li>
|
||||
</ul>
|
||||
|
||||
<!-- ✅ Drag + button alternatives -->
|
||||
<ul class="sortable-list">
|
||||
<li>
|
||||
<span>Item 1</span>
|
||||
<button aria-label="Move Item 1 up">↑</button>
|
||||
<button aria-label="Move Item 1 down">↓</button>
|
||||
</li>
|
||||
<li>
|
||||
<span>Item 2</span>
|
||||
<button aria-label="Move Item 2 up">↑</button>
|
||||
<button aria-label="Move Item 2 down">↓</button>
|
||||
</li>
|
||||
</ul>
|
||||
```
|
||||
|
||||
Also applies to sliders, map panning, colour pickers, and similar drag-based widgets—always provide an equivalent click/tap or keyboard path.
|
||||
|
||||
---
|
||||
|
||||
## ARIA tabs
|
||||
|
||||
Tabs require `role="tablist"`, `role="tab"`, and `role="tabpanel"` with proper `aria-selected`, `aria-controls`, and keyboard support.
|
||||
|
||||
```html
|
||||
<div role="tablist" aria-label="Product information">
|
||||
<button role="tab" id="tab-1" aria-selected="true"
|
||||
aria-controls="panel-1">Description</button>
|
||||
<button role="tab" id="tab-2" aria-selected="false"
|
||||
aria-controls="panel-2" tabindex="-1">Reviews</button>
|
||||
</div>
|
||||
<div role="tabpanel" id="panel-1" aria-labelledby="tab-1">
|
||||
<!-- Panel content -->
|
||||
</div>
|
||||
<div role="tabpanel" id="panel-2" aria-labelledby="tab-2" hidden>
|
||||
<!-- Panel content -->
|
||||
</div>
|
||||
```
|
||||
|
||||
Arrow keys should move focus between tabs; the active tab receives `tabindex="0"` while inactive tabs use `tabindex="-1"`.
|
||||
|
||||
---
|
||||
|
||||
## Live regions and notifications
|
||||
|
||||
Use `aria-live` to announce dynamic content changes to screen readers without moving focus.
|
||||
|
||||
```html
|
||||
<!-- Status updates (polite — waits for pause in speech) -->
|
||||
<div aria-live="polite" aria-atomic="true" class="status">
|
||||
<!-- Content updates announced to screen readers -->
|
||||
</div>
|
||||
|
||||
<!-- Urgent alerts (assertive — interrupts) -->
|
||||
<div role="alert" aria-live="assertive">
|
||||
<!-- Interrupts current announcement -->
|
||||
</div>
|
||||
```
|
||||
|
||||
```javascript
|
||||
function showNotification(message, type = 'polite') {
|
||||
const container = document.getElementById(`${type}-announcer`);
|
||||
container.textContent = '';
|
||||
requestAnimationFrame(() => {
|
||||
container.textContent = message;
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
Clear the container before writing to ensure the same message triggers a new announcement.
|
||||
|
||||
---
|
||||
|
||||
## Screen reader commands
|
||||
|
||||
Quick reference for the most common screen reader shortcuts.
|
||||
|
||||
| Action | VoiceOver (Mac) | NVDA (Windows) |
|
||||
|--------|-----------------|----------------|
|
||||
| Start/Stop | ⌘ + F5 | Ctrl + Alt + N |
|
||||
| Next item | VO + → | ↓ |
|
||||
| Previous item | VO + ← | ↑ |
|
||||
| Activate | VO + Space | Enter |
|
||||
| Headings list | VO + U, then arrows | H / Shift + H |
|
||||
| Links list | VO + U | K / Shift + K |
|
||||
@@ -0,0 +1,191 @@
|
||||
# WCAG 2.2 Quick Reference
|
||||
|
||||
## Success criteria by level
|
||||
|
||||
### Level A (minimum)
|
||||
|
||||
| Criterion | Description |
|
||||
|-----------|-------------|
|
||||
| **1.1.1** Non-text Content | All images, icons have text alternatives |
|
||||
| **1.2.1** Audio-only/Video-only | Provide transcript or audio description |
|
||||
| **1.2.2** Captions | Video with audio has captions |
|
||||
| **1.2.3** Audio Description | Video has audio description |
|
||||
| **1.3.1** Info and Relationships | Information conveyed through presentation is available programmatically |
|
||||
| **1.3.2** Meaningful Sequence | Reading order is logical |
|
||||
| **1.3.3** Sensory Characteristics | Instructions don't rely solely on shape, color, size, location, orientation, or sound |
|
||||
| **1.4.1** Use of Color | Color is not the only visual means of conveying information |
|
||||
| **1.4.2** Audio Control | Audio playing automatically can be paused/stopped |
|
||||
| **2.1.1** Keyboard | All functionality available via keyboard |
|
||||
| **2.1.2** No Keyboard Trap | Keyboard focus can be moved away from any component |
|
||||
| **2.1.4** Character Key Shortcuts | Single-key shortcuts can be turned off or remapped |
|
||||
| **2.2.1** Timing Adjustable | Time limits can be extended |
|
||||
| **2.2.2** Pause, Stop, Hide | Moving/blinking content can be paused |
|
||||
| **2.3.1** Three Flashes | Nothing flashes more than 3 times per second |
|
||||
| **2.4.1** Bypass Blocks | Skip link or landmark navigation available |
|
||||
| **2.4.2** Page Titled | Pages have descriptive titles |
|
||||
| **2.4.3** Focus Order | Focus order preserves meaning |
|
||||
| **2.4.4** Link Purpose | Link purpose clear from link text or context |
|
||||
| **2.5.1** Pointer Gestures | Multi-point gestures have single-pointer alternatives |
|
||||
| **2.5.2** Pointer Cancellation | Down-event doesn't trigger action (use up-event or click) |
|
||||
| **2.5.3** Label in Name | Accessible name contains visible label text |
|
||||
| **2.5.4** Motion Actuation | Motion-triggered functions have alternatives |
|
||||
| **3.1.1** Language of Page | Default language specified in HTML |
|
||||
| **3.2.1** On Focus | Focus doesn't trigger unexpected changes |
|
||||
| **3.2.2** On Input | Input doesn't trigger unexpected changes |
|
||||
| **3.2.6** Consistent Help | Help mechanisms appear in the same relative order across pages |
|
||||
| **3.3.1** Error Identification | Input errors clearly described |
|
||||
| **3.3.2** Labels or Instructions | Form inputs have labels or instructions |
|
||||
| **3.3.7** Redundant Entry | Information previously entered is auto-populated or available to select |
|
||||
| **4.1.2** Name, Role, Value | UI components have accessible names and correct roles |
|
||||
|
||||
### Level AA (standard)
|
||||
|
||||
| Criterion | Description |
|
||||
|-----------|-------------|
|
||||
| **1.2.4** Captions (Live) | Live audio has captions |
|
||||
| **1.2.5** Audio Description | Pre-recorded video has audio description |
|
||||
| **1.3.4** Orientation | Content doesn't restrict orientation |
|
||||
| **1.3.5** Identify Input Purpose | Input purpose can be programmatically determined |
|
||||
| **1.4.3** Contrast (Minimum) | 4.5:1 for normal text, 3:1 for large text |
|
||||
| **1.4.4** Resize Text | Text can be resized to 200% without loss of functionality |
|
||||
| **1.4.5** Images of Text | Text used instead of images of text |
|
||||
| **1.4.10** Reflow | Content reflows at 320px width without horizontal scroll |
|
||||
| **1.4.11** Non-text Contrast | UI components have 3:1 contrast |
|
||||
| **1.4.12** Text Spacing | Content adapts to text spacing changes |
|
||||
| **1.4.13** Content on Hover/Focus | Additional content is dismissible, hoverable, persistent |
|
||||
| **2.4.5** Multiple Ways | Multiple ways to find pages |
|
||||
| **2.4.6** Headings and Labels | Headings and labels are descriptive |
|
||||
| **2.4.7** Focus Visible | Focus indicator is visible |
|
||||
| **2.4.11** Focus Not Obscured (Minimum) | Focused element is not entirely hidden by author-created content |
|
||||
| **2.5.7** Dragging Movements | Dragging actions have single-pointer alternatives |
|
||||
| **2.5.8** Target Size (Minimum) | Interactive targets are at least 24×24 CSS pixels (with exceptions) |
|
||||
| **3.1.2** Language of Parts | Language changes are marked |
|
||||
| **3.2.3** Consistent Navigation | Navigation is consistent across pages |
|
||||
| **3.2.4** Consistent Identification | Same functionality uses same labels |
|
||||
| **3.3.3** Error Suggestion | Error corrections suggested when known |
|
||||
| **3.3.4** Error Prevention (Legal) | Actions can be reversed or confirmed |
|
||||
| **3.3.8** Accessible Authentication (Minimum) | No cognitive function test for login unless an alternative or assistance is provided |
|
||||
| **4.1.3** Status Messages | Status messages announced to screen readers |
|
||||
|
||||
### Level AAA (enhanced)
|
||||
|
||||
| Criterion | Description |
|
||||
|-----------|-------------|
|
||||
| **1.4.6** Contrast (Enhanced) | 7:1 for normal text, 4.5:1 for large text |
|
||||
| **1.4.8** Visual Presentation | Foreground/background colors can be selected |
|
||||
| **1.4.9** Images of Text (No Exception) | No images of text |
|
||||
| **2.1.3** Keyboard (No Exception) | All functionality keyboard accessible |
|
||||
| **2.2.3** No Timing | No time limits |
|
||||
| **2.2.4** Interruptions | Interruptions can be postponed |
|
||||
| **2.2.5** Re-authenticating | Data preserved on re-authentication |
|
||||
| **2.2.6** Timeouts | Users warned about data loss from inactivity |
|
||||
| **2.3.2** Three Flashes | No content flashes more than 3 times |
|
||||
| **2.3.3** Animation from Interactions | Motion animation can be disabled |
|
||||
| **2.4.8** Location | User location within site is available |
|
||||
| **2.4.9** Link Purpose (Link Only) | Link purpose clear from link text alone |
|
||||
| **2.4.10** Section Headings | Sections have headings |
|
||||
| **2.4.12** Focus Not Obscured (Enhanced) | No part of the focused element is hidden by author-created content |
|
||||
| **2.4.13** Focus Appearance | Focus indicator has sufficient area, contrast, and is not obscured |
|
||||
| **3.1.3** Unusual Words | Definitions available for unusual words |
|
||||
| **3.1.4** Abbreviations | Abbreviations expanded |
|
||||
| **3.1.5** Reading Level | Alternative content for complex text |
|
||||
| **3.1.6** Pronunciation | Pronunciation available where needed |
|
||||
| **3.2.5** Change on Request | Changes initiated only by user |
|
||||
| **3.3.5** Help | Context-sensitive help available |
|
||||
| **3.3.6** Error Prevention (All) | All form submissions can be reviewed |
|
||||
| **3.3.9** Accessible Authentication (Enhanced) | No cognitive function test for login (no object or personal content recognition exceptions) |
|
||||
|
||||
## Common ARIA patterns
|
||||
|
||||
### Buttons
|
||||
```html
|
||||
<button>Label</button>
|
||||
<!-- or -->
|
||||
<button aria-label="Close dialog">×</button>
|
||||
```
|
||||
|
||||
### Links
|
||||
```html
|
||||
<a href="/page">Descriptive link text</a>
|
||||
<!-- External links -->
|
||||
<a href="https://external.com" target="_blank" rel="noopener">
|
||||
External site
|
||||
<span class="visually-hidden">(opens in new tab)</span>
|
||||
</a>
|
||||
```
|
||||
|
||||
### Form fields
|
||||
```html
|
||||
<label for="email">Email address</label>
|
||||
<input type="email" id="email" aria-describedby="email-hint">
|
||||
<p id="email-hint">We'll never share your email.</p>
|
||||
```
|
||||
|
||||
### Error states
|
||||
```html
|
||||
<label for="email">Email</label>
|
||||
<input type="email" id="email" aria-invalid="true" aria-describedby="email-error">
|
||||
<p id="email-error" role="alert">Please enter a valid email address.</p>
|
||||
```
|
||||
|
||||
### Navigation
|
||||
```html
|
||||
<nav aria-label="Main">
|
||||
<ul>
|
||||
<li><a href="/" aria-current="page">Home</a></li>
|
||||
<li><a href="/about">About</a></li>
|
||||
</ul>
|
||||
</nav>
|
||||
```
|
||||
|
||||
### Modals
|
||||
```html
|
||||
<div role="dialog" aria-modal="true" aria-labelledby="dialog-title">
|
||||
<h2 id="dialog-title">Confirm Action</h2>
|
||||
<!-- content -->
|
||||
</div>
|
||||
```
|
||||
|
||||
### Live regions
|
||||
```html
|
||||
<!-- Polite (waits for pause in speech) -->
|
||||
<div aria-live="polite">Status update here</div>
|
||||
|
||||
<!-- Assertive (interrupts immediately) -->
|
||||
<div aria-live="assertive" role="alert">Error message here</div>
|
||||
|
||||
<!-- Status (polite, implicit) -->
|
||||
<div role="status">Loading complete</div>
|
||||
```
|
||||
|
||||
## What changed from 2.1 to 2.2
|
||||
|
||||
| Change | Criterion | Level |
|
||||
|--------|-----------|-------|
|
||||
| **Removed** | 4.1.1 Parsing | A |
|
||||
| **Added** | 2.4.11 Focus Not Obscured (Minimum) | AA |
|
||||
| **Added** | 2.4.12 Focus Not Obscured (Enhanced) | AAA |
|
||||
| **Added** | 2.4.13 Focus Appearance | AAA |
|
||||
| **Added** | 2.5.7 Dragging Movements | AA |
|
||||
| **Added** | 2.5.8 Target Size (Minimum) | AA |
|
||||
| **Added** | 3.2.6 Consistent Help | A |
|
||||
| **Added** | 3.3.7 Redundant Entry | A |
|
||||
| **Added** | 3.3.8 Accessible Authentication (Minimum) | AA |
|
||||
| **Added** | 3.3.9 Accessible Authentication (Enhanced) | AAA |
|
||||
|
||||
## Testing tools
|
||||
|
||||
| Tool | Type | URL |
|
||||
|------|------|-----|
|
||||
| axe DevTools | Browser extension | [deque.com/axe](https://www.deque.com/axe/) |
|
||||
| WAVE | Browser extension | [wave.webaim.org](https://wave.webaim.org/) |
|
||||
| Lighthouse | Built into Chrome | DevTools → Lighthouse |
|
||||
| NVDA | Screen reader (Windows) | [nvaccess.org](https://www.nvaccess.org/) |
|
||||
| VoiceOver | Screen reader (Mac) | Built into macOS |
|
||||
| Colour Contrast Analyser | Desktop app | [tpgi.com](https://www.tpgi.com/color-contrast-checker/) |
|
||||
|
||||
## Sources
|
||||
|
||||
- [WCAG 2.2 W3C Recommendation](https://www.w3.org/TR/WCAG22/)
|
||||
- [WCAG 2.2 Quick Reference](https://www.w3.org/WAI/WCAG22/quickref/)
|
||||
- [What's New in WCAG 2.2](https://www.w3.org/WAI/standards-guidelines/wcag/new-in-22/)
|
||||
@@ -0,0 +1,946 @@
|
||||
# React Composition Patterns
|
||||
|
||||
**Version 1.0.0**
|
||||
Engineering
|
||||
January 2026
|
||||
|
||||
> **Note:**
|
||||
> This document is mainly for agents and LLMs to follow when maintaining,
|
||||
> generating, or refactoring React codebases using composition. Humans
|
||||
> may also find it useful, but guidance here is optimized for automation
|
||||
> and consistency by AI-assisted workflows.
|
||||
|
||||
---
|
||||
|
||||
## Abstract
|
||||
|
||||
Composition patterns for building flexible, maintainable React components. Avoid boolean prop proliferation by using compound components, lifting state, and composing internals. These patterns make codebases easier for both humans and AI agents to work with as they scale.
|
||||
|
||||
---
|
||||
|
||||
## Table of Contents
|
||||
|
||||
1. [Component Architecture](#1-component-architecture) — **HIGH**
|
||||
- 1.1 [Avoid Boolean Prop Proliferation](#11-avoid-boolean-prop-proliferation)
|
||||
- 1.2 [Use Compound Components](#12-use-compound-components)
|
||||
2. [State Management](#2-state-management) — **MEDIUM**
|
||||
- 2.1 [Decouple State Management from UI](#21-decouple-state-management-from-ui)
|
||||
- 2.2 [Define Generic Context Interfaces for Dependency Injection](#22-define-generic-context-interfaces-for-dependency-injection)
|
||||
- 2.3 [Lift State into Provider Components](#23-lift-state-into-provider-components)
|
||||
3. [Implementation Patterns](#3-implementation-patterns) — **MEDIUM**
|
||||
- 3.1 [Create Explicit Component Variants](#31-create-explicit-component-variants)
|
||||
- 3.2 [Prefer Composing Children Over Render Props](#32-prefer-composing-children-over-render-props)
|
||||
4. [React 19 APIs](#4-react-19-apis) — **MEDIUM**
|
||||
- 4.1 [React 19 API Changes](#41-react-19-api-changes)
|
||||
|
||||
---
|
||||
|
||||
## 1. Component Architecture
|
||||
|
||||
**Impact: HIGH**
|
||||
|
||||
Fundamental patterns for structuring components to avoid prop
|
||||
proliferation and enable flexible composition.
|
||||
|
||||
### 1.1 Avoid Boolean Prop Proliferation
|
||||
|
||||
**Impact: CRITICAL (prevents unmaintainable component variants)**
|
||||
|
||||
Don't add boolean props like `isThread`, `isEditing`, `isDMThread` to customize
|
||||
|
||||
component behavior. Each boolean doubles possible states and creates
|
||||
|
||||
unmaintainable conditional logic. Use composition instead.
|
||||
|
||||
**Incorrect: boolean props create exponential complexity**
|
||||
|
||||
```tsx
|
||||
function Composer({
|
||||
onSubmit,
|
||||
isThread,
|
||||
channelId,
|
||||
isDMThread,
|
||||
dmId,
|
||||
isEditing,
|
||||
isForwarding,
|
||||
}: Props) {
|
||||
return (
|
||||
<form>
|
||||
<Header />
|
||||
<Input />
|
||||
{isDMThread ? (
|
||||
<AlsoSendToDMField id={dmId} />
|
||||
) : isThread ? (
|
||||
<AlsoSendToChannelField id={channelId} />
|
||||
) : null}
|
||||
{isEditing ? (
|
||||
<EditActions />
|
||||
) : isForwarding ? (
|
||||
<ForwardActions />
|
||||
) : (
|
||||
<DefaultActions />
|
||||
)}
|
||||
<Footer onSubmit={onSubmit} />
|
||||
</form>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct: composition eliminates conditionals**
|
||||
|
||||
```tsx
|
||||
// Channel composer
|
||||
function ChannelComposer() {
|
||||
return (
|
||||
<Composer.Frame>
|
||||
<Composer.Header />
|
||||
<Composer.Input />
|
||||
<Composer.Footer>
|
||||
<Composer.Attachments />
|
||||
<Composer.Formatting />
|
||||
<Composer.Emojis />
|
||||
<Composer.Submit />
|
||||
</Composer.Footer>
|
||||
</Composer.Frame>
|
||||
)
|
||||
}
|
||||
|
||||
// Thread composer - adds "also send to channel" field
|
||||
function ThreadComposer({ channelId }: { channelId: string }) {
|
||||
return (
|
||||
<Composer.Frame>
|
||||
<Composer.Header />
|
||||
<Composer.Input />
|
||||
<AlsoSendToChannelField id={channelId} />
|
||||
<Composer.Footer>
|
||||
<Composer.Formatting />
|
||||
<Composer.Emojis />
|
||||
<Composer.Submit />
|
||||
</Composer.Footer>
|
||||
</Composer.Frame>
|
||||
)
|
||||
}
|
||||
|
||||
// Edit composer - different footer actions
|
||||
function EditComposer() {
|
||||
return (
|
||||
<Composer.Frame>
|
||||
<Composer.Input />
|
||||
<Composer.Footer>
|
||||
<Composer.Formatting />
|
||||
<Composer.Emojis />
|
||||
<Composer.CancelEdit />
|
||||
<Composer.SaveEdit />
|
||||
</Composer.Footer>
|
||||
</Composer.Frame>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
Each variant is explicit about what it renders. We can share internals without
|
||||
|
||||
sharing a single monolithic parent.
|
||||
|
||||
### 1.2 Use Compound Components
|
||||
|
||||
**Impact: HIGH (enables flexible composition without prop drilling)**
|
||||
|
||||
Structure complex components as compound components with a shared context. Each
|
||||
|
||||
subcomponent accesses shared state via context, not props. Consumers compose the
|
||||
|
||||
pieces they need.
|
||||
|
||||
**Incorrect: monolithic component with render props**
|
||||
|
||||
```tsx
|
||||
function Composer({
|
||||
renderHeader,
|
||||
renderFooter,
|
||||
renderActions,
|
||||
showAttachments,
|
||||
showFormatting,
|
||||
showEmojis,
|
||||
}: Props) {
|
||||
return (
|
||||
<form>
|
||||
{renderHeader?.()}
|
||||
<Input />
|
||||
{showAttachments && <Attachments />}
|
||||
{renderFooter ? (
|
||||
renderFooter()
|
||||
) : (
|
||||
<Footer>
|
||||
{showFormatting && <Formatting />}
|
||||
{showEmojis && <Emojis />}
|
||||
{renderActions?.()}
|
||||
</Footer>
|
||||
)}
|
||||
</form>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct: compound components with shared context**
|
||||
|
||||
```tsx
|
||||
const ComposerContext = createContext<ComposerContextValue | null>(null)
|
||||
|
||||
function ComposerProvider({ children, state, actions, meta }: ProviderProps) {
|
||||
return (
|
||||
<ComposerContext value={{ state, actions, meta }}>
|
||||
{children}
|
||||
</ComposerContext>
|
||||
)
|
||||
}
|
||||
|
||||
function ComposerFrame({ children }: { children: React.ReactNode }) {
|
||||
return <form>{children}</form>
|
||||
}
|
||||
|
||||
function ComposerInput() {
|
||||
const {
|
||||
state,
|
||||
actions: { update },
|
||||
meta: { inputRef },
|
||||
} = use(ComposerContext)
|
||||
return (
|
||||
<TextInput
|
||||
ref={inputRef}
|
||||
value={state.input}
|
||||
onChangeText={(text) => update((s) => ({ ...s, input: text }))}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ComposerSubmit() {
|
||||
const {
|
||||
actions: { submit },
|
||||
} = use(ComposerContext)
|
||||
return <Button onPress={submit}>Send</Button>
|
||||
}
|
||||
|
||||
// Export as compound component
|
||||
const Composer = {
|
||||
Provider: ComposerProvider,
|
||||
Frame: ComposerFrame,
|
||||
Input: ComposerInput,
|
||||
Submit: ComposerSubmit,
|
||||
Header: ComposerHeader,
|
||||
Footer: ComposerFooter,
|
||||
Attachments: ComposerAttachments,
|
||||
Formatting: ComposerFormatting,
|
||||
Emojis: ComposerEmojis,
|
||||
}
|
||||
```
|
||||
|
||||
**Usage:**
|
||||
|
||||
```tsx
|
||||
<Composer.Provider state={state} actions={actions} meta={meta}>
|
||||
<Composer.Frame>
|
||||
<Composer.Header />
|
||||
<Composer.Input />
|
||||
<Composer.Footer>
|
||||
<Composer.Formatting />
|
||||
<Composer.Submit />
|
||||
</Composer.Footer>
|
||||
</Composer.Frame>
|
||||
</Composer.Provider>
|
||||
```
|
||||
|
||||
Consumers explicitly compose exactly what they need. No hidden conditionals. And the state, actions and meta are dependency-injected by a parent provider, allowing multiple usages of the same component structure.
|
||||
|
||||
---
|
||||
|
||||
## 2. State Management
|
||||
|
||||
**Impact: MEDIUM**
|
||||
|
||||
Patterns for lifting state and managing shared context across
|
||||
composed components.
|
||||
|
||||
### 2.1 Decouple State Management from UI
|
||||
|
||||
**Impact: MEDIUM (enables swapping state implementations without changing UI)**
|
||||
|
||||
The provider component should be the only place that knows how state is managed.
|
||||
|
||||
UI components consume the context interface—they don't know if state comes from
|
||||
|
||||
useState, Zustand, or a server sync.
|
||||
|
||||
**Incorrect: UI coupled to state implementation**
|
||||
|
||||
```tsx
|
||||
function ChannelComposer({ channelId }: { channelId: string }) {
|
||||
// UI component knows about global state implementation
|
||||
const state = useGlobalChannelState(channelId)
|
||||
const { submit, updateInput } = useChannelSync(channelId)
|
||||
|
||||
return (
|
||||
<Composer.Frame>
|
||||
<Composer.Input
|
||||
value={state.input}
|
||||
onChange={(text) => sync.updateInput(text)}
|
||||
/>
|
||||
<Composer.Submit onPress={() => sync.submit()} />
|
||||
</Composer.Frame>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct: state management isolated in provider**
|
||||
|
||||
```tsx
|
||||
// Provider handles all state management details
|
||||
function ChannelProvider({
|
||||
channelId,
|
||||
children,
|
||||
}: {
|
||||
channelId: string
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
const { state, update, submit } = useGlobalChannel(channelId)
|
||||
const inputRef = useRef(null)
|
||||
|
||||
return (
|
||||
<Composer.Provider
|
||||
state={state}
|
||||
actions={{ update, submit }}
|
||||
meta={{ inputRef }}
|
||||
>
|
||||
{children}
|
||||
</Composer.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
// UI component only knows about the context interface
|
||||
function ChannelComposer() {
|
||||
return (
|
||||
<Composer.Frame>
|
||||
<Composer.Header />
|
||||
<Composer.Input />
|
||||
<Composer.Footer>
|
||||
<Composer.Submit />
|
||||
</Composer.Footer>
|
||||
</Composer.Frame>
|
||||
)
|
||||
}
|
||||
|
||||
// Usage
|
||||
function Channel({ channelId }: { channelId: string }) {
|
||||
return (
|
||||
<ChannelProvider channelId={channelId}>
|
||||
<ChannelComposer />
|
||||
</ChannelProvider>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Different providers, same UI:**
|
||||
|
||||
```tsx
|
||||
// Local state for ephemeral forms
|
||||
function ForwardMessageProvider({ children }) {
|
||||
const [state, setState] = useState(initialState)
|
||||
const forwardMessage = useForwardMessage()
|
||||
|
||||
return (
|
||||
<Composer.Provider
|
||||
state={state}
|
||||
actions={{ update: setState, submit: forwardMessage }}
|
||||
>
|
||||
{children}
|
||||
</Composer.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
// Global synced state for channels
|
||||
function ChannelProvider({ channelId, children }) {
|
||||
const { state, update, submit } = useGlobalChannel(channelId)
|
||||
|
||||
return (
|
||||
<Composer.Provider state={state} actions={{ update, submit }}>
|
||||
{children}
|
||||
</Composer.Provider>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
The same `Composer.Input` component works with both providers because it only
|
||||
|
||||
depends on the context interface, not the implementation.
|
||||
|
||||
### 2.2 Define Generic Context Interfaces for Dependency Injection
|
||||
|
||||
**Impact: HIGH (enables dependency-injectable state across use-cases)**
|
||||
|
||||
Define a **generic interface** for your component context with three parts:
|
||||
|
||||
`state`, `actions`, and `meta`. This interface is a contract that any provider
|
||||
|
||||
can implement—enabling the same UI components to work with completely different
|
||||
|
||||
state implementations.
|
||||
|
||||
**Core principle:** Lift state, compose internals, make state
|
||||
|
||||
dependency-injectable.
|
||||
|
||||
**Incorrect: UI coupled to specific state implementation**
|
||||
|
||||
```tsx
|
||||
function ComposerInput() {
|
||||
// Tightly coupled to a specific hook
|
||||
const { input, setInput } = useChannelComposerState()
|
||||
return <TextInput value={input} onChangeText={setInput} />
|
||||
}
|
||||
```
|
||||
|
||||
**Correct: generic interface enables dependency injection**
|
||||
|
||||
```tsx
|
||||
// Define a GENERIC interface that any provider can implement
|
||||
interface ComposerState {
|
||||
input: string
|
||||
attachments: Attachment[]
|
||||
isSubmitting: boolean
|
||||
}
|
||||
|
||||
interface ComposerActions {
|
||||
update: (updater: (state: ComposerState) => ComposerState) => void
|
||||
submit: () => void
|
||||
}
|
||||
|
||||
interface ComposerMeta {
|
||||
inputRef: React.RefObject<TextInput>
|
||||
}
|
||||
|
||||
interface ComposerContextValue {
|
||||
state: ComposerState
|
||||
actions: ComposerActions
|
||||
meta: ComposerMeta
|
||||
}
|
||||
|
||||
const ComposerContext = createContext<ComposerContextValue | null>(null)
|
||||
```
|
||||
|
||||
**UI components consume the interface, not the implementation:**
|
||||
|
||||
```tsx
|
||||
function ComposerInput() {
|
||||
const {
|
||||
state,
|
||||
actions: { update },
|
||||
meta,
|
||||
} = use(ComposerContext)
|
||||
|
||||
// This component works with ANY provider that implements the interface
|
||||
return (
|
||||
<TextInput
|
||||
ref={meta.inputRef}
|
||||
value={state.input}
|
||||
onChangeText={(text) => update((s) => ({ ...s, input: text }))}
|
||||
/>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Different providers implement the same interface:**
|
||||
|
||||
```tsx
|
||||
// Provider A: Local state for ephemeral forms
|
||||
function ForwardMessageProvider({ children }: { children: React.ReactNode }) {
|
||||
const [state, setState] = useState(initialState)
|
||||
const inputRef = useRef(null)
|
||||
const submit = useForwardMessage()
|
||||
|
||||
return (
|
||||
<ComposerContext
|
||||
value={{
|
||||
state,
|
||||
actions: { update: setState, submit },
|
||||
meta: { inputRef },
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</ComposerContext>
|
||||
)
|
||||
}
|
||||
|
||||
// Provider B: Global synced state for channels
|
||||
function ChannelProvider({ channelId, children }: Props) {
|
||||
const { state, update, submit } = useGlobalChannel(channelId)
|
||||
const inputRef = useRef(null)
|
||||
|
||||
return (
|
||||
<ComposerContext
|
||||
value={{
|
||||
state,
|
||||
actions: { update, submit },
|
||||
meta: { inputRef },
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</ComposerContext>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**The same composed UI works with both:**
|
||||
|
||||
```tsx
|
||||
// Works with ForwardMessageProvider (local state)
|
||||
<ForwardMessageProvider>
|
||||
<Composer.Frame>
|
||||
<Composer.Input />
|
||||
<Composer.Submit />
|
||||
</Composer.Frame>
|
||||
</ForwardMessageProvider>
|
||||
|
||||
// Works with ChannelProvider (global synced state)
|
||||
<ChannelProvider channelId="abc">
|
||||
<Composer.Frame>
|
||||
<Composer.Input />
|
||||
<Composer.Submit />
|
||||
</Composer.Frame>
|
||||
</ChannelProvider>
|
||||
```
|
||||
|
||||
**Custom UI outside the component can access state and actions:**
|
||||
|
||||
```tsx
|
||||
function ForwardMessageDialog() {
|
||||
return (
|
||||
<ForwardMessageProvider>
|
||||
<Dialog>
|
||||
{/* The composer UI */}
|
||||
<Composer.Frame>
|
||||
<Composer.Input placeholder="Add a message, if you'd like." />
|
||||
<Composer.Footer>
|
||||
<Composer.Formatting />
|
||||
<Composer.Emojis />
|
||||
</Composer.Footer>
|
||||
</Composer.Frame>
|
||||
|
||||
{/* Custom UI OUTSIDE the composer, but INSIDE the provider */}
|
||||
<MessagePreview />
|
||||
|
||||
{/* Actions at the bottom of the dialog */}
|
||||
<DialogActions>
|
||||
<CancelButton />
|
||||
<ForwardButton />
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
</ForwardMessageProvider>
|
||||
)
|
||||
}
|
||||
|
||||
// This button lives OUTSIDE Composer.Frame but can still submit based on its context!
|
||||
function ForwardButton() {
|
||||
const {
|
||||
actions: { submit },
|
||||
} = use(ComposerContext)
|
||||
return <Button onPress={submit}>Forward</Button>
|
||||
}
|
||||
|
||||
// This preview lives OUTSIDE Composer.Frame but can read composer's state!
|
||||
function MessagePreview() {
|
||||
const { state } = use(ComposerContext)
|
||||
return <Preview message={state.input} attachments={state.attachments} />
|
||||
}
|
||||
```
|
||||
|
||||
The provider boundary is what matters—not the visual nesting. Components that
|
||||
|
||||
need shared state don't have to be inside the `Composer.Frame`. They just need
|
||||
|
||||
to be within the provider.
|
||||
|
||||
The `ForwardButton` and `MessagePreview` are not visually inside the composer
|
||||
|
||||
box, but they can still access its state and actions. This is the power of
|
||||
|
||||
lifting state into providers.
|
||||
|
||||
The UI is reusable bits you compose together. The state is dependency-injected
|
||||
|
||||
by the provider. Swap the provider, keep the UI.
|
||||
|
||||
### 2.3 Lift State into Provider Components
|
||||
|
||||
**Impact: HIGH (enables state sharing outside component boundaries)**
|
||||
|
||||
Move state management into dedicated provider components. This allows sibling
|
||||
|
||||
components outside the main UI to access and modify state without prop drilling
|
||||
|
||||
or awkward refs.
|
||||
|
||||
**Incorrect: state trapped inside component**
|
||||
|
||||
```tsx
|
||||
function ForwardMessageComposer() {
|
||||
const [state, setState] = useState(initialState)
|
||||
const forwardMessage = useForwardMessage()
|
||||
|
||||
return (
|
||||
<Composer.Frame>
|
||||
<Composer.Input />
|
||||
<Composer.Footer />
|
||||
</Composer.Frame>
|
||||
)
|
||||
}
|
||||
|
||||
// Problem: How does this button access composer state?
|
||||
function ForwardMessageDialog() {
|
||||
return (
|
||||
<Dialog>
|
||||
<ForwardMessageComposer />
|
||||
<MessagePreview /> {/* Needs composer state */}
|
||||
<DialogActions>
|
||||
<CancelButton />
|
||||
<ForwardButton /> {/* Needs to call submit */}
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Incorrect: useEffect to sync state up**
|
||||
|
||||
```tsx
|
||||
function ForwardMessageDialog() {
|
||||
const [input, setInput] = useState('')
|
||||
return (
|
||||
<Dialog>
|
||||
<ForwardMessageComposer onInputChange={setInput} />
|
||||
<MessagePreview input={input} />
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
function ForwardMessageComposer({ onInputChange }) {
|
||||
const [state, setState] = useState(initialState)
|
||||
useEffect(() => {
|
||||
onInputChange(state.input) // Sync on every change 😬
|
||||
}, [state.input])
|
||||
}
|
||||
```
|
||||
|
||||
**Incorrect: reading state from ref on submit**
|
||||
|
||||
```tsx
|
||||
function ForwardMessageDialog() {
|
||||
const stateRef = useRef(null)
|
||||
return (
|
||||
<Dialog>
|
||||
<ForwardMessageComposer stateRef={stateRef} />
|
||||
<ForwardButton onPress={() => submit(stateRef.current)} />
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct: state lifted to provider**
|
||||
|
||||
```tsx
|
||||
function ForwardMessageProvider({ children }: { children: React.ReactNode }) {
|
||||
const [state, setState] = useState(initialState)
|
||||
const forwardMessage = useForwardMessage()
|
||||
const inputRef = useRef(null)
|
||||
|
||||
return (
|
||||
<Composer.Provider
|
||||
state={state}
|
||||
actions={{ update: setState, submit: forwardMessage }}
|
||||
meta={{ inputRef }}
|
||||
>
|
||||
{children}
|
||||
</Composer.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
function ForwardMessageDialog() {
|
||||
return (
|
||||
<ForwardMessageProvider>
|
||||
<Dialog>
|
||||
<ForwardMessageComposer />
|
||||
<MessagePreview /> {/* Custom components can access state and actions */}
|
||||
<DialogActions>
|
||||
<CancelButton />
|
||||
<ForwardButton /> {/* Custom components can access state and actions */}
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
</ForwardMessageProvider>
|
||||
)
|
||||
}
|
||||
|
||||
function ForwardButton() {
|
||||
const { actions } = use(Composer.Context)
|
||||
return <Button onPress={actions.submit}>Forward</Button>
|
||||
}
|
||||
```
|
||||
|
||||
The ForwardButton lives outside the Composer.Frame but still has access to the
|
||||
|
||||
submit action because it's within the provider. Even though it's a one-off
|
||||
|
||||
component, it can still access the composer's state and actions from outside the
|
||||
|
||||
UI itself.
|
||||
|
||||
**Key insight:** Components that need shared state don't have to be visually
|
||||
|
||||
nested inside each other—they just need to be within the same provider.
|
||||
|
||||
---
|
||||
|
||||
## 3. Implementation Patterns
|
||||
|
||||
**Impact: MEDIUM**
|
||||
|
||||
Specific techniques for implementing compound components and
|
||||
context providers.
|
||||
|
||||
### 3.1 Create Explicit Component Variants
|
||||
|
||||
**Impact: MEDIUM (self-documenting code, no hidden conditionals)**
|
||||
|
||||
Instead of one component with many boolean props, create explicit variant
|
||||
|
||||
components. Each variant composes the pieces it needs. The code documents
|
||||
|
||||
itself.
|
||||
|
||||
**Incorrect: one component, many modes**
|
||||
|
||||
```tsx
|
||||
// What does this component actually render?
|
||||
<Composer
|
||||
isThread
|
||||
isEditing={false}
|
||||
channelId='abc'
|
||||
showAttachments
|
||||
showFormatting={false}
|
||||
/>
|
||||
```
|
||||
|
||||
**Correct: explicit variants**
|
||||
|
||||
```tsx
|
||||
// Immediately clear what this renders
|
||||
<ThreadComposer channelId="abc" />
|
||||
|
||||
// Or
|
||||
<EditMessageComposer messageId="xyz" />
|
||||
|
||||
// Or
|
||||
<ForwardMessageComposer messageId="123" />
|
||||
```
|
||||
|
||||
Each implementation is unique, explicit and self-contained. Yet they can each
|
||||
|
||||
use shared parts.
|
||||
|
||||
**Implementation:**
|
||||
|
||||
```tsx
|
||||
function ThreadComposer({ channelId }: { channelId: string }) {
|
||||
return (
|
||||
<ThreadProvider channelId={channelId}>
|
||||
<Composer.Frame>
|
||||
<Composer.Input />
|
||||
<AlsoSendToChannelField channelId={channelId} />
|
||||
<Composer.Footer>
|
||||
<Composer.Formatting />
|
||||
<Composer.Emojis />
|
||||
<Composer.Submit />
|
||||
</Composer.Footer>
|
||||
</Composer.Frame>
|
||||
</ThreadProvider>
|
||||
)
|
||||
}
|
||||
|
||||
function EditMessageComposer({ messageId }: { messageId: string }) {
|
||||
return (
|
||||
<EditMessageProvider messageId={messageId}>
|
||||
<Composer.Frame>
|
||||
<Composer.Input />
|
||||
<Composer.Footer>
|
||||
<Composer.Formatting />
|
||||
<Composer.Emojis />
|
||||
<Composer.CancelEdit />
|
||||
<Composer.SaveEdit />
|
||||
</Composer.Footer>
|
||||
</Composer.Frame>
|
||||
</EditMessageProvider>
|
||||
)
|
||||
}
|
||||
|
||||
function ForwardMessageComposer({ messageId }: { messageId: string }) {
|
||||
return (
|
||||
<ForwardMessageProvider messageId={messageId}>
|
||||
<Composer.Frame>
|
||||
<Composer.Input placeholder="Add a message, if you'd like." />
|
||||
<Composer.Footer>
|
||||
<Composer.Formatting />
|
||||
<Composer.Emojis />
|
||||
<Composer.Mentions />
|
||||
</Composer.Footer>
|
||||
</Composer.Frame>
|
||||
</ForwardMessageProvider>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
Each variant is explicit about:
|
||||
|
||||
- What provider/state it uses
|
||||
|
||||
- What UI elements it includes
|
||||
|
||||
- What actions are available
|
||||
|
||||
No boolean prop combinations to reason about. No impossible states.
|
||||
|
||||
### 3.2 Prefer Composing Children Over Render Props
|
||||
|
||||
**Impact: MEDIUM (cleaner composition, better readability)**
|
||||
|
||||
Use `children` for composition instead of `renderX` props. Children are more
|
||||
|
||||
readable, compose naturally, and don't require understanding callback
|
||||
|
||||
signatures.
|
||||
|
||||
**Incorrect: render props**
|
||||
|
||||
```tsx
|
||||
function Composer({
|
||||
renderHeader,
|
||||
renderFooter,
|
||||
renderActions,
|
||||
}: {
|
||||
renderHeader?: () => React.ReactNode
|
||||
renderFooter?: () => React.ReactNode
|
||||
renderActions?: () => React.ReactNode
|
||||
}) {
|
||||
return (
|
||||
<form>
|
||||
{renderHeader?.()}
|
||||
<Input />
|
||||
{renderFooter ? renderFooter() : <DefaultFooter />}
|
||||
{renderActions?.()}
|
||||
</form>
|
||||
)
|
||||
}
|
||||
|
||||
// Usage is awkward and inflexible
|
||||
return (
|
||||
<Composer
|
||||
renderHeader={() => <CustomHeader />}
|
||||
renderFooter={() => (
|
||||
<>
|
||||
<Formatting />
|
||||
<Emojis />
|
||||
</>
|
||||
)}
|
||||
renderActions={() => <SubmitButton />}
|
||||
/>
|
||||
)
|
||||
```
|
||||
|
||||
**Correct: compound components with children**
|
||||
|
||||
```tsx
|
||||
function ComposerFrame({ children }: { children: React.ReactNode }) {
|
||||
return <form>{children}</form>
|
||||
}
|
||||
|
||||
function ComposerFooter({ children }: { children: React.ReactNode }) {
|
||||
return <footer className='flex'>{children}</footer>
|
||||
}
|
||||
|
||||
// Usage is flexible
|
||||
return (
|
||||
<Composer.Frame>
|
||||
<CustomHeader />
|
||||
<Composer.Input />
|
||||
<Composer.Footer>
|
||||
<Composer.Formatting />
|
||||
<Composer.Emojis />
|
||||
<SubmitButton />
|
||||
</Composer.Footer>
|
||||
</Composer.Frame>
|
||||
)
|
||||
```
|
||||
|
||||
**When render props are appropriate:**
|
||||
|
||||
```tsx
|
||||
// Render props work well when you need to pass data back
|
||||
<List
|
||||
data={items}
|
||||
renderItem={({ item, index }) => <Item item={item} index={index} />}
|
||||
/>
|
||||
```
|
||||
|
||||
Use render props when the parent needs to provide data or state to the child.
|
||||
|
||||
Use children when composing static structure.
|
||||
|
||||
---
|
||||
|
||||
## 4. React 19 APIs
|
||||
|
||||
**Impact: MEDIUM**
|
||||
|
||||
React 19+ only. Don't use `forwardRef`; use `use()` instead of `useContext()`.
|
||||
|
||||
### 4.1 React 19 API Changes
|
||||
|
||||
**Impact: MEDIUM (cleaner component definitions and context usage)**
|
||||
|
||||
> **⚠️ React 19+ only.** Skip this if you're on React 18 or earlier.
|
||||
|
||||
In React 19, `ref` is now a regular prop (no `forwardRef` wrapper needed), and `use()` replaces `useContext()`.
|
||||
|
||||
**Incorrect: forwardRef in React 19**
|
||||
|
||||
```tsx
|
||||
const ComposerInput = forwardRef<TextInput, Props>((props, ref) => {
|
||||
return <TextInput ref={ref} {...props} />
|
||||
})
|
||||
```
|
||||
|
||||
**Correct: ref as a regular prop**
|
||||
|
||||
```tsx
|
||||
function ComposerInput({ ref, ...props }: Props & { ref?: React.Ref<TextInput> }) {
|
||||
return <TextInput ref={ref} {...props} />
|
||||
}
|
||||
```
|
||||
|
||||
**Incorrect: useContext in React 19**
|
||||
|
||||
```tsx
|
||||
const value = useContext(MyContext)
|
||||
```
|
||||
|
||||
**Correct: use instead of useContext**
|
||||
|
||||
```tsx
|
||||
const value = use(MyContext)
|
||||
```
|
||||
|
||||
`use()` can also be called conditionally, unlike `useContext()`.
|
||||
|
||||
---
|
||||
|
||||
## References
|
||||
|
||||
1. [https://react.dev](https://react.dev)
|
||||
2. [https://react.dev/learn/passing-data-deeply-with-context](https://react.dev/learn/passing-data-deeply-with-context)
|
||||
3. [https://react.dev/reference/react/use](https://react.dev/reference/react/use)
|
||||
@@ -0,0 +1,17 @@
|
||||
MIT License
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
|
||||
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
|
||||
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of
|
||||
the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
|
||||
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
||||
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
The upstream repository (https://github.com/vercel-labs/agent-skills) declares the MIT licence in its README and in
|
||||
the SKILL.md frontmatter; it ships no LICENSE file with a copyright line. Copyright: Vercel.
|
||||
@@ -0,0 +1,60 @@
|
||||
# React Composition Patterns
|
||||
|
||||
A structured repository for React composition patterns that scale. These
|
||||
patterns help avoid boolean prop proliferation by using compound components,
|
||||
lifting state, and composing internals.
|
||||
|
||||
## Structure
|
||||
|
||||
- `rules/` - Individual rule files (one per rule)
|
||||
- `_sections.md` - Section metadata (titles, impacts, descriptions)
|
||||
- `_template.md` - Template for creating new rules
|
||||
- `area-description.md` - Individual rule files
|
||||
- `metadata.json` - Document metadata (version, organization, abstract)
|
||||
- **`AGENTS.md`** - Compiled output (generated)
|
||||
|
||||
## Rules
|
||||
|
||||
### Component Architecture (CRITICAL)
|
||||
|
||||
- `architecture-avoid-boolean-props.md` - Don't add boolean props to customize
|
||||
behavior
|
||||
- `architecture-compound-components.md` - Structure as compound components with
|
||||
shared context
|
||||
|
||||
### State Management (HIGH)
|
||||
|
||||
- `state-lift-state.md` - Lift state into provider components
|
||||
- `state-context-interface.md` - Define clear context interfaces
|
||||
(state/actions/meta)
|
||||
- `state-decouple-implementation.md` - Decouple state management from UI
|
||||
|
||||
### Implementation Patterns (MEDIUM)
|
||||
|
||||
- `patterns-children-over-render-props.md` - Prefer children over renderX props
|
||||
- `patterns-explicit-variants.md` - Create explicit component variants
|
||||
|
||||
## Core Principles
|
||||
|
||||
1. **Composition over configuration** — Instead of adding props, let consumers
|
||||
compose
|
||||
2. **Lift your state** — State in providers, not trapped in components
|
||||
3. **Compose your internals** — Subcomponents access context, not props
|
||||
4. **Explicit variants** — Create ThreadComposer, EditComposer, not Composer
|
||||
with isThread
|
||||
|
||||
## Creating a New Rule
|
||||
|
||||
1. Copy `rules/_template.md` to `rules/area-description.md`
|
||||
2. Choose the appropriate area prefix:
|
||||
- `architecture-` for Component Architecture
|
||||
- `state-` for State Management
|
||||
- `patterns-` for Implementation Patterns
|
||||
3. Fill in the frontmatter and content
|
||||
4. Ensure you have clear examples with explanations
|
||||
|
||||
## Impact Levels
|
||||
|
||||
- `CRITICAL` - Foundational patterns, prevents unmaintainable code
|
||||
- `HIGH` - Significant maintainability improvements
|
||||
- `MEDIUM` - Good practices for cleaner code
|
||||
@@ -0,0 +1,99 @@
|
||||
---
|
||||
name: ext-composition-patterns
|
||||
description:
|
||||
React composition patterns that scale. Use when refactoring components with
|
||||
boolean prop proliferation, building flexible component libraries, or
|
||||
designing reusable APIs. Triggers on tasks involving compound components,
|
||||
render props, context providers, or component architecture. Includes React 19
|
||||
API changes.
|
||||
license: MIT
|
||||
metadata:
|
||||
author: vercel
|
||||
version: '1.0.0'
|
||||
---
|
||||
|
||||
> **Project rules win.** Vendored by @intecion/ipal-kit as guidance. When this skill conflicts with
|
||||
> `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md`, the project's `AGENTS.md` or `DESIGN.md`, those win:
|
||||
> ipal-kit features first (the `ipal-reference` skill), Payload 3 + Next 16 App Router, data from Server Components
|
||||
> through Payload / `@/lib/content`, every visible text from the CMS, design values from `DESIGN.md` tokens.
|
||||
> Never add a dependency this skill suggests without the owner's decision.
|
||||
>
|
||||
> **Blocks:** composition applies inside a block's own components; the block schema, shared fields and
|
||||
> `RenderBlocks` follow AGENT.md §6.
|
||||
|
||||
|
||||
# React Composition Patterns
|
||||
|
||||
Composition patterns for building flexible, maintainable React components. Avoid
|
||||
boolean prop proliferation by using compound components, lifting state, and
|
||||
composing internals. These patterns make codebases easier for both humans and AI
|
||||
agents to work with as they scale.
|
||||
|
||||
## When to Apply
|
||||
|
||||
Reference these guidelines when:
|
||||
|
||||
- Refactoring components with many boolean props
|
||||
- Building reusable component libraries
|
||||
- Designing flexible component APIs
|
||||
- Reviewing component architecture
|
||||
- Working with compound components or context providers
|
||||
|
||||
## Rule Categories by Priority
|
||||
|
||||
| Priority | Category | Impact | Prefix |
|
||||
| -------- | ----------------------- | ------ | --------------- |
|
||||
| 1 | Component Architecture | HIGH | `architecture-` |
|
||||
| 2 | State Management | MEDIUM | `state-` |
|
||||
| 3 | Implementation Patterns | MEDIUM | `patterns-` |
|
||||
| 4 | React 19 APIs | MEDIUM | `react19-` |
|
||||
|
||||
## Quick Reference
|
||||
|
||||
### 1. Component Architecture (HIGH)
|
||||
|
||||
- `architecture-avoid-boolean-props` - Don't add boolean props to customize
|
||||
behavior; use composition
|
||||
- `architecture-compound-components` - Structure complex components with shared
|
||||
context
|
||||
|
||||
### 2. State Management (MEDIUM)
|
||||
|
||||
- `state-decouple-implementation` - Provider is the only place that knows how
|
||||
state is managed
|
||||
- `state-context-interface` - Define generic interface with state, actions, meta
|
||||
for dependency injection
|
||||
- `state-lift-state` - Move state into provider components for sibling access
|
||||
|
||||
### 3. Implementation Patterns (MEDIUM)
|
||||
|
||||
- `patterns-explicit-variants` - Create explicit variant components instead of
|
||||
boolean modes
|
||||
- `patterns-children-over-render-props` - Use children for composition instead
|
||||
of renderX props
|
||||
|
||||
### 4. React 19 APIs (MEDIUM)
|
||||
|
||||
> **⚠️ React 19+ only.** Skip this section if using React 18 or earlier.
|
||||
|
||||
- `react19-no-forwardref` - Don't use `forwardRef`; use `use()` instead of `useContext()`
|
||||
|
||||
## How to Use
|
||||
|
||||
Read individual rule files for detailed explanations and code examples:
|
||||
|
||||
```
|
||||
rules/architecture-avoid-boolean-props.md
|
||||
rules/state-context-interface.md
|
||||
```
|
||||
|
||||
Each rule file contains:
|
||||
|
||||
- Brief explanation of why it matters
|
||||
- Incorrect code example with explanation
|
||||
- Correct code example with explanation
|
||||
- Additional context and references
|
||||
|
||||
## Full Compiled Document
|
||||
|
||||
For the complete guide with all rules expanded: `AGENTS.md`
|
||||
@@ -0,0 +1,14 @@
|
||||
# ext-composition-patterns
|
||||
|
||||
Vendored by @intecion/ipal-kit (`ipal-skills --external`). Do not edit — regenerate with
|
||||
`scripts/vendor-external-skills.mjs` in the ipal-kit repository.
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Publisher | Vercel |
|
||||
| Source | https://github.com/vercel-labs/agent-skills/tree/1a2c79d4e6c4a2283dc2c614b6538cbe1ed5ca62/skills/composition-patterns |
|
||||
| Commit | `1a2c79d4e6c4a2283dc2c614b6538cbe1ed5ca62` |
|
||||
| Licence | MIT (see the LICENSE file in this folder) |
|
||||
|
||||
Changes from the upstream text: the `name` in the SKILL.md frontmatter is `ext-composition-patterns`, and an
|
||||
override note (project rules win) is inserted after the frontmatter. Nothing else is changed.
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"version": "1.0.0",
|
||||
"organization": "Engineering",
|
||||
"date": "January 2026",
|
||||
"abstract": "Composition patterns for building flexible, maintainable React components. Avoid boolean prop proliferation by using compound components, lifting state, and composing internals. These patterns make codebases easier for both humans and AI agents to work with as they scale.",
|
||||
"references": [
|
||||
"https://react.dev",
|
||||
"https://react.dev/learn/passing-data-deeply-with-context",
|
||||
"https://react.dev/reference/react/use"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
# Sections
|
||||
|
||||
This file defines all sections, their ordering, impact levels, and descriptions.
|
||||
The section ID (in parentheses) is the filename prefix used to group rules.
|
||||
|
||||
---
|
||||
|
||||
## 1. Component Architecture (architecture)
|
||||
|
||||
**Impact:** HIGH
|
||||
**Description:** Fundamental patterns for structuring components to avoid prop
|
||||
proliferation and enable flexible composition.
|
||||
|
||||
## 2. State Management (state)
|
||||
|
||||
**Impact:** MEDIUM
|
||||
**Description:** Patterns for lifting state and managing shared context across
|
||||
composed components.
|
||||
|
||||
## 3. Implementation Patterns (patterns)
|
||||
|
||||
**Impact:** MEDIUM
|
||||
**Description:** Specific techniques for implementing compound components and
|
||||
context providers.
|
||||
|
||||
## 4. React 19 APIs (react19)
|
||||
|
||||
**Impact:** MEDIUM
|
||||
**Description:** React 19+ only. Don't use `forwardRef`; use `use()` instead of `useContext()`.
|
||||
@@ -0,0 +1,24 @@
|
||||
---
|
||||
title: Rule Title Here
|
||||
impact: MEDIUM
|
||||
impactDescription: brief description of impact
|
||||
tags: composition, components
|
||||
---
|
||||
|
||||
## Rule Title Here
|
||||
|
||||
Brief explanation of the rule and why it matters.
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```tsx
|
||||
// Bad code example
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```tsx
|
||||
// Good code example
|
||||
```
|
||||
|
||||
Reference: [Link](https://example.com)
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
---
|
||||
title: Avoid Boolean Prop Proliferation
|
||||
impact: CRITICAL
|
||||
impactDescription: prevents unmaintainable component variants
|
||||
tags: composition, props, architecture
|
||||
---
|
||||
|
||||
## Avoid Boolean Prop Proliferation
|
||||
|
||||
Don't add boolean props like `isThread`, `isEditing`, `isDMThread` to customize
|
||||
component behavior. Each boolean doubles possible states and creates
|
||||
unmaintainable conditional logic. Use composition instead.
|
||||
|
||||
**Incorrect (boolean props create exponential complexity):**
|
||||
|
||||
```tsx
|
||||
function Composer({
|
||||
onSubmit,
|
||||
isThread,
|
||||
channelId,
|
||||
isDMThread,
|
||||
dmId,
|
||||
isEditing,
|
||||
isForwarding,
|
||||
}: Props) {
|
||||
return (
|
||||
<form>
|
||||
<Header />
|
||||
<Input />
|
||||
{isDMThread ? (
|
||||
<AlsoSendToDMField id={dmId} />
|
||||
) : isThread ? (
|
||||
<AlsoSendToChannelField id={channelId} />
|
||||
) : null}
|
||||
{isEditing ? (
|
||||
<EditActions />
|
||||
) : isForwarding ? (
|
||||
<ForwardActions />
|
||||
) : (
|
||||
<DefaultActions />
|
||||
)}
|
||||
<Footer onSubmit={onSubmit} />
|
||||
</form>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (composition eliminates conditionals):**
|
||||
|
||||
```tsx
|
||||
// Channel composer
|
||||
function ChannelComposer() {
|
||||
return (
|
||||
<Composer.Frame>
|
||||
<Composer.Header />
|
||||
<Composer.Input />
|
||||
<Composer.Footer>
|
||||
<Composer.Attachments />
|
||||
<Composer.Formatting />
|
||||
<Composer.Emojis />
|
||||
<Composer.Submit />
|
||||
</Composer.Footer>
|
||||
</Composer.Frame>
|
||||
)
|
||||
}
|
||||
|
||||
// Thread composer - adds "also send to channel" field
|
||||
function ThreadComposer({ channelId }: { channelId: string }) {
|
||||
return (
|
||||
<Composer.Frame>
|
||||
<Composer.Header />
|
||||
<Composer.Input />
|
||||
<AlsoSendToChannelField id={channelId} />
|
||||
<Composer.Footer>
|
||||
<Composer.Formatting />
|
||||
<Composer.Emojis />
|
||||
<Composer.Submit />
|
||||
</Composer.Footer>
|
||||
</Composer.Frame>
|
||||
)
|
||||
}
|
||||
|
||||
// Edit composer - different footer actions
|
||||
function EditComposer() {
|
||||
return (
|
||||
<Composer.Frame>
|
||||
<Composer.Input />
|
||||
<Composer.Footer>
|
||||
<Composer.Formatting />
|
||||
<Composer.Emojis />
|
||||
<Composer.CancelEdit />
|
||||
<Composer.SaveEdit />
|
||||
</Composer.Footer>
|
||||
</Composer.Frame>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
Each variant is explicit about what it renders. We can share internals without
|
||||
sharing a single monolithic parent.
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
---
|
||||
title: Use Compound Components
|
||||
impact: HIGH
|
||||
impactDescription: enables flexible composition without prop drilling
|
||||
tags: composition, compound-components, architecture
|
||||
---
|
||||
|
||||
## Use Compound Components
|
||||
|
||||
Structure complex components as compound components with a shared context. Each
|
||||
subcomponent accesses shared state via context, not props. Consumers compose the
|
||||
pieces they need.
|
||||
|
||||
**Incorrect (monolithic component with render props):**
|
||||
|
||||
```tsx
|
||||
function Composer({
|
||||
renderHeader,
|
||||
renderFooter,
|
||||
renderActions,
|
||||
showAttachments,
|
||||
showFormatting,
|
||||
showEmojis,
|
||||
}: Props) {
|
||||
return (
|
||||
<form>
|
||||
{renderHeader?.()}
|
||||
<Input />
|
||||
{showAttachments && <Attachments />}
|
||||
{renderFooter ? (
|
||||
renderFooter()
|
||||
) : (
|
||||
<Footer>
|
||||
{showFormatting && <Formatting />}
|
||||
{showEmojis && <Emojis />}
|
||||
{renderActions?.()}
|
||||
</Footer>
|
||||
)}
|
||||
</form>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (compound components with shared context):**
|
||||
|
||||
```tsx
|
||||
const ComposerContext = createContext<ComposerContextValue | null>(null)
|
||||
|
||||
function ComposerProvider({ children, state, actions, meta }: ProviderProps) {
|
||||
return (
|
||||
<ComposerContext value={{ state, actions, meta }}>
|
||||
{children}
|
||||
</ComposerContext>
|
||||
)
|
||||
}
|
||||
|
||||
function ComposerFrame({ children }: { children: React.ReactNode }) {
|
||||
return <form>{children}</form>
|
||||
}
|
||||
|
||||
function ComposerInput() {
|
||||
const {
|
||||
state,
|
||||
actions: { update },
|
||||
meta: { inputRef },
|
||||
} = use(ComposerContext)
|
||||
return (
|
||||
<TextInput
|
||||
ref={inputRef}
|
||||
value={state.input}
|
||||
onChangeText={(text) => update((s) => ({ ...s, input: text }))}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ComposerSubmit() {
|
||||
const {
|
||||
actions: { submit },
|
||||
} = use(ComposerContext)
|
||||
return <Button onPress={submit}>Send</Button>
|
||||
}
|
||||
|
||||
// Export as compound component
|
||||
const Composer = {
|
||||
Provider: ComposerProvider,
|
||||
Frame: ComposerFrame,
|
||||
Input: ComposerInput,
|
||||
Submit: ComposerSubmit,
|
||||
Header: ComposerHeader,
|
||||
Footer: ComposerFooter,
|
||||
Attachments: ComposerAttachments,
|
||||
Formatting: ComposerFormatting,
|
||||
Emojis: ComposerEmojis,
|
||||
}
|
||||
```
|
||||
|
||||
**Usage:**
|
||||
|
||||
```tsx
|
||||
<Composer.Provider state={state} actions={actions} meta={meta}>
|
||||
<Composer.Frame>
|
||||
<Composer.Header />
|
||||
<Composer.Input />
|
||||
<Composer.Footer>
|
||||
<Composer.Formatting />
|
||||
<Composer.Submit />
|
||||
</Composer.Footer>
|
||||
</Composer.Frame>
|
||||
</Composer.Provider>
|
||||
```
|
||||
|
||||
Consumers explicitly compose exactly what they need. No hidden conditionals. And the state, actions and meta are dependency-injected by a parent provider, allowing multiple usages of the same component structure.
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
---
|
||||
title: Prefer Composing Children Over Render Props
|
||||
impact: MEDIUM
|
||||
impactDescription: cleaner composition, better readability
|
||||
tags: composition, children, render-props
|
||||
---
|
||||
|
||||
## Prefer Children Over Render Props
|
||||
|
||||
Use `children` for composition instead of `renderX` props. Children are more
|
||||
readable, compose naturally, and don't require understanding callback
|
||||
signatures.
|
||||
|
||||
**Incorrect (render props):**
|
||||
|
||||
```tsx
|
||||
function Composer({
|
||||
renderHeader,
|
||||
renderFooter,
|
||||
renderActions,
|
||||
}: {
|
||||
renderHeader?: () => React.ReactNode
|
||||
renderFooter?: () => React.ReactNode
|
||||
renderActions?: () => React.ReactNode
|
||||
}) {
|
||||
return (
|
||||
<form>
|
||||
{renderHeader?.()}
|
||||
<Input />
|
||||
{renderFooter ? renderFooter() : <DefaultFooter />}
|
||||
{renderActions?.()}
|
||||
</form>
|
||||
)
|
||||
}
|
||||
|
||||
// Usage is awkward and inflexible
|
||||
return (
|
||||
<Composer
|
||||
renderHeader={() => <CustomHeader />}
|
||||
renderFooter={() => (
|
||||
<>
|
||||
<Formatting />
|
||||
<Emojis />
|
||||
</>
|
||||
)}
|
||||
renderActions={() => <SubmitButton />}
|
||||
/>
|
||||
)
|
||||
```
|
||||
|
||||
**Correct (compound components with children):**
|
||||
|
||||
```tsx
|
||||
function ComposerFrame({ children }: { children: React.ReactNode }) {
|
||||
return <form>{children}</form>
|
||||
}
|
||||
|
||||
function ComposerFooter({ children }: { children: React.ReactNode }) {
|
||||
return <footer className='flex'>{children}</footer>
|
||||
}
|
||||
|
||||
// Usage is flexible
|
||||
return (
|
||||
<Composer.Frame>
|
||||
<CustomHeader />
|
||||
<Composer.Input />
|
||||
<Composer.Footer>
|
||||
<Composer.Formatting />
|
||||
<Composer.Emojis />
|
||||
<SubmitButton />
|
||||
</Composer.Footer>
|
||||
</Composer.Frame>
|
||||
)
|
||||
```
|
||||
|
||||
**When render props are appropriate:**
|
||||
|
||||
```tsx
|
||||
// Render props work well when you need to pass data back
|
||||
<List
|
||||
data={items}
|
||||
renderItem={({ item, index }) => <Item item={item} index={index} />}
|
||||
/>
|
||||
```
|
||||
|
||||
Use render props when the parent needs to provide data or state to the child.
|
||||
Use children when composing static structure.
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
---
|
||||
title: Create Explicit Component Variants
|
||||
impact: MEDIUM
|
||||
impactDescription: self-documenting code, no hidden conditionals
|
||||
tags: composition, variants, architecture
|
||||
---
|
||||
|
||||
## Create Explicit Component Variants
|
||||
|
||||
Instead of one component with many boolean props, create explicit variant
|
||||
components. Each variant composes the pieces it needs. The code documents
|
||||
itself.
|
||||
|
||||
**Incorrect (one component, many modes):**
|
||||
|
||||
```tsx
|
||||
// What does this component actually render?
|
||||
<Composer
|
||||
isThread
|
||||
isEditing={false}
|
||||
channelId='abc'
|
||||
showAttachments
|
||||
showFormatting={false}
|
||||
/>
|
||||
```
|
||||
|
||||
**Correct (explicit variants):**
|
||||
|
||||
```tsx
|
||||
// Immediately clear what this renders
|
||||
<ThreadComposer channelId="abc" />
|
||||
|
||||
// Or
|
||||
<EditMessageComposer messageId="xyz" />
|
||||
|
||||
// Or
|
||||
<ForwardMessageComposer messageId="123" />
|
||||
```
|
||||
|
||||
Each implementation is unique, explicit and self-contained. Yet they can each
|
||||
use shared parts.
|
||||
|
||||
**Implementation:**
|
||||
|
||||
```tsx
|
||||
function ThreadComposer({ channelId }: { channelId: string }) {
|
||||
return (
|
||||
<ThreadProvider channelId={channelId}>
|
||||
<Composer.Frame>
|
||||
<Composer.Input />
|
||||
<AlsoSendToChannelField channelId={channelId} />
|
||||
<Composer.Footer>
|
||||
<Composer.Formatting />
|
||||
<Composer.Emojis />
|
||||
<Composer.Submit />
|
||||
</Composer.Footer>
|
||||
</Composer.Frame>
|
||||
</ThreadProvider>
|
||||
)
|
||||
}
|
||||
|
||||
function EditMessageComposer({ messageId }: { messageId: string }) {
|
||||
return (
|
||||
<EditMessageProvider messageId={messageId}>
|
||||
<Composer.Frame>
|
||||
<Composer.Input />
|
||||
<Composer.Footer>
|
||||
<Composer.Formatting />
|
||||
<Composer.Emojis />
|
||||
<Composer.CancelEdit />
|
||||
<Composer.SaveEdit />
|
||||
</Composer.Footer>
|
||||
</Composer.Frame>
|
||||
</EditMessageProvider>
|
||||
)
|
||||
}
|
||||
|
||||
function ForwardMessageComposer({ messageId }: { messageId: string }) {
|
||||
return (
|
||||
<ForwardMessageProvider messageId={messageId}>
|
||||
<Composer.Frame>
|
||||
<Composer.Input placeholder="Add a message, if you'd like." />
|
||||
<Composer.Footer>
|
||||
<Composer.Formatting />
|
||||
<Composer.Emojis />
|
||||
<Composer.Mentions />
|
||||
</Composer.Footer>
|
||||
</Composer.Frame>
|
||||
</ForwardMessageProvider>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
Each variant is explicit about:
|
||||
|
||||
- What provider/state it uses
|
||||
- What UI elements it includes
|
||||
- What actions are available
|
||||
|
||||
No boolean prop combinations to reason about. No impossible states.
|
||||
@@ -0,0 +1,42 @@
|
||||
---
|
||||
title: React 19 API Changes
|
||||
impact: MEDIUM
|
||||
impactDescription: cleaner component definitions and context usage
|
||||
tags: react19, refs, context, hooks
|
||||
---
|
||||
|
||||
## React 19 API Changes
|
||||
|
||||
> **⚠️ React 19+ only.** Skip this if you're on React 18 or earlier.
|
||||
|
||||
In React 19, `ref` is now a regular prop (no `forwardRef` wrapper needed), and `use()` replaces `useContext()`.
|
||||
|
||||
**Incorrect (forwardRef in React 19):**
|
||||
|
||||
```tsx
|
||||
const ComposerInput = forwardRef<TextInput, Props>((props, ref) => {
|
||||
return <TextInput ref={ref} {...props} />
|
||||
})
|
||||
```
|
||||
|
||||
**Correct (ref as a regular prop):**
|
||||
|
||||
```tsx
|
||||
function ComposerInput({ ref, ...props }: Props & { ref?: React.Ref<TextInput> }) {
|
||||
return <TextInput ref={ref} {...props} />
|
||||
}
|
||||
```
|
||||
|
||||
**Incorrect (useContext in React 19):**
|
||||
|
||||
```tsx
|
||||
const value = useContext(MyContext)
|
||||
```
|
||||
|
||||
**Correct (use instead of useContext):**
|
||||
|
||||
```tsx
|
||||
const value = use(MyContext)
|
||||
```
|
||||
|
||||
`use()` can also be called conditionally, unlike `useContext()`.
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
---
|
||||
title: Define Generic Context Interfaces for Dependency Injection
|
||||
impact: HIGH
|
||||
impactDescription: enables dependency-injectable state across use-cases
|
||||
tags: composition, context, state, typescript, dependency-injection
|
||||
---
|
||||
|
||||
## Define Generic Context Interfaces for Dependency Injection
|
||||
|
||||
Define a **generic interface** for your component context with three parts:
|
||||
`state`, `actions`, and `meta`. This interface is a contract that any provider
|
||||
can implement—enabling the same UI components to work with completely different
|
||||
state implementations.
|
||||
|
||||
**Core principle:** Lift state, compose internals, make state
|
||||
dependency-injectable.
|
||||
|
||||
**Incorrect (UI coupled to specific state implementation):**
|
||||
|
||||
```tsx
|
||||
function ComposerInput() {
|
||||
// Tightly coupled to a specific hook
|
||||
const { input, setInput } = useChannelComposerState()
|
||||
return <TextInput value={input} onChangeText={setInput} />
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (generic interface enables dependency injection):**
|
||||
|
||||
```tsx
|
||||
// Define a GENERIC interface that any provider can implement
|
||||
interface ComposerState {
|
||||
input: string
|
||||
attachments: Attachment[]
|
||||
isSubmitting: boolean
|
||||
}
|
||||
|
||||
interface ComposerActions {
|
||||
update: (updater: (state: ComposerState) => ComposerState) => void
|
||||
submit: () => void
|
||||
}
|
||||
|
||||
interface ComposerMeta {
|
||||
inputRef: React.RefObject<TextInput>
|
||||
}
|
||||
|
||||
interface ComposerContextValue {
|
||||
state: ComposerState
|
||||
actions: ComposerActions
|
||||
meta: ComposerMeta
|
||||
}
|
||||
|
||||
const ComposerContext = createContext<ComposerContextValue | null>(null)
|
||||
```
|
||||
|
||||
**UI components consume the interface, not the implementation:**
|
||||
|
||||
```tsx
|
||||
function ComposerInput() {
|
||||
const {
|
||||
state,
|
||||
actions: { update },
|
||||
meta,
|
||||
} = use(ComposerContext)
|
||||
|
||||
// This component works with ANY provider that implements the interface
|
||||
return (
|
||||
<TextInput
|
||||
ref={meta.inputRef}
|
||||
value={state.input}
|
||||
onChangeText={(text) => update((s) => ({ ...s, input: text }))}
|
||||
/>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Different providers implement the same interface:**
|
||||
|
||||
```tsx
|
||||
// Provider A: Local state for ephemeral forms
|
||||
function ForwardMessageProvider({ children }: { children: React.ReactNode }) {
|
||||
const [state, setState] = useState(initialState)
|
||||
const inputRef = useRef(null)
|
||||
const submit = useForwardMessage()
|
||||
|
||||
return (
|
||||
<ComposerContext
|
||||
value={{
|
||||
state,
|
||||
actions: { update: setState, submit },
|
||||
meta: { inputRef },
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</ComposerContext>
|
||||
)
|
||||
}
|
||||
|
||||
// Provider B: Global synced state for channels
|
||||
function ChannelProvider({ channelId, children }: Props) {
|
||||
const { state, update, submit } = useGlobalChannel(channelId)
|
||||
const inputRef = useRef(null)
|
||||
|
||||
return (
|
||||
<ComposerContext
|
||||
value={{
|
||||
state,
|
||||
actions: { update, submit },
|
||||
meta: { inputRef },
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</ComposerContext>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**The same composed UI works with both:**
|
||||
|
||||
```tsx
|
||||
// Works with ForwardMessageProvider (local state)
|
||||
<ForwardMessageProvider>
|
||||
<Composer.Frame>
|
||||
<Composer.Input />
|
||||
<Composer.Submit />
|
||||
</Composer.Frame>
|
||||
</ForwardMessageProvider>
|
||||
|
||||
// Works with ChannelProvider (global synced state)
|
||||
<ChannelProvider channelId="abc">
|
||||
<Composer.Frame>
|
||||
<Composer.Input />
|
||||
<Composer.Submit />
|
||||
</Composer.Frame>
|
||||
</ChannelProvider>
|
||||
```
|
||||
|
||||
**Custom UI outside the component can access state and actions:**
|
||||
|
||||
The provider boundary is what matters—not the visual nesting. Components that
|
||||
need shared state don't have to be inside the `Composer.Frame`. They just need
|
||||
to be within the provider.
|
||||
|
||||
```tsx
|
||||
function ForwardMessageDialog() {
|
||||
return (
|
||||
<ForwardMessageProvider>
|
||||
<Dialog>
|
||||
{/* The composer UI */}
|
||||
<Composer.Frame>
|
||||
<Composer.Input placeholder="Add a message, if you'd like." />
|
||||
<Composer.Footer>
|
||||
<Composer.Formatting />
|
||||
<Composer.Emojis />
|
||||
</Composer.Footer>
|
||||
</Composer.Frame>
|
||||
|
||||
{/* Custom UI OUTSIDE the composer, but INSIDE the provider */}
|
||||
<MessagePreview />
|
||||
|
||||
{/* Actions at the bottom of the dialog */}
|
||||
<DialogActions>
|
||||
<CancelButton />
|
||||
<ForwardButton />
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
</ForwardMessageProvider>
|
||||
)
|
||||
}
|
||||
|
||||
// This button lives OUTSIDE Composer.Frame but can still submit based on its context!
|
||||
function ForwardButton() {
|
||||
const {
|
||||
actions: { submit },
|
||||
} = use(ComposerContext)
|
||||
return <Button onPress={submit}>Forward</Button>
|
||||
}
|
||||
|
||||
// This preview lives OUTSIDE Composer.Frame but can read composer's state!
|
||||
function MessagePreview() {
|
||||
const { state } = use(ComposerContext)
|
||||
return <Preview message={state.input} attachments={state.attachments} />
|
||||
}
|
||||
```
|
||||
|
||||
The `ForwardButton` and `MessagePreview` are not visually inside the composer
|
||||
box, but they can still access its state and actions. This is the power of
|
||||
lifting state into providers.
|
||||
|
||||
The UI is reusable bits you compose together. The state is dependency-injected
|
||||
by the provider. Swap the provider, keep the UI.
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
---
|
||||
title: Decouple State Management from UI
|
||||
impact: MEDIUM
|
||||
impactDescription: enables swapping state implementations without changing UI
|
||||
tags: composition, state, architecture
|
||||
---
|
||||
|
||||
## Decouple State Management from UI
|
||||
|
||||
The provider component should be the only place that knows how state is managed.
|
||||
UI components consume the context interface—they don't know if state comes from
|
||||
useState, Zustand, or a server sync.
|
||||
|
||||
**Incorrect (UI coupled to state implementation):**
|
||||
|
||||
```tsx
|
||||
function ChannelComposer({ channelId }: { channelId: string }) {
|
||||
// UI component knows about global state implementation
|
||||
const state = useGlobalChannelState(channelId)
|
||||
const { submit, updateInput } = useChannelSync(channelId)
|
||||
|
||||
return (
|
||||
<Composer.Frame>
|
||||
<Composer.Input
|
||||
value={state.input}
|
||||
onChange={(text) => sync.updateInput(text)}
|
||||
/>
|
||||
<Composer.Submit onPress={() => sync.submit()} />
|
||||
</Composer.Frame>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (state management isolated in provider):**
|
||||
|
||||
```tsx
|
||||
// Provider handles all state management details
|
||||
function ChannelProvider({
|
||||
channelId,
|
||||
children,
|
||||
}: {
|
||||
channelId: string
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
const { state, update, submit } = useGlobalChannel(channelId)
|
||||
const inputRef = useRef(null)
|
||||
|
||||
return (
|
||||
<Composer.Provider
|
||||
state={state}
|
||||
actions={{ update, submit }}
|
||||
meta={{ inputRef }}
|
||||
>
|
||||
{children}
|
||||
</Composer.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
// UI component only knows about the context interface
|
||||
function ChannelComposer() {
|
||||
return (
|
||||
<Composer.Frame>
|
||||
<Composer.Header />
|
||||
<Composer.Input />
|
||||
<Composer.Footer>
|
||||
<Composer.Submit />
|
||||
</Composer.Footer>
|
||||
</Composer.Frame>
|
||||
)
|
||||
}
|
||||
|
||||
// Usage
|
||||
function Channel({ channelId }: { channelId: string }) {
|
||||
return (
|
||||
<ChannelProvider channelId={channelId}>
|
||||
<ChannelComposer />
|
||||
</ChannelProvider>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Different providers, same UI:**
|
||||
|
||||
```tsx
|
||||
// Local state for ephemeral forms
|
||||
function ForwardMessageProvider({ children }) {
|
||||
const [state, setState] = useState(initialState)
|
||||
const forwardMessage = useForwardMessage()
|
||||
|
||||
return (
|
||||
<Composer.Provider
|
||||
state={state}
|
||||
actions={{ update: setState, submit: forwardMessage }}
|
||||
>
|
||||
{children}
|
||||
</Composer.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
// Global synced state for channels
|
||||
function ChannelProvider({ channelId, children }) {
|
||||
const { state, update, submit } = useGlobalChannel(channelId)
|
||||
|
||||
return (
|
||||
<Composer.Provider state={state} actions={{ update, submit }}>
|
||||
{children}
|
||||
</Composer.Provider>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
The same `Composer.Input` component works with both providers because it only
|
||||
depends on the context interface, not the implementation.
|
||||
@@ -0,0 +1,125 @@
|
||||
---
|
||||
title: Lift State into Provider Components
|
||||
impact: HIGH
|
||||
impactDescription: enables state sharing outside component boundaries
|
||||
tags: composition, state, context, providers
|
||||
---
|
||||
|
||||
## Lift State into Provider Components
|
||||
|
||||
Move state management into dedicated provider components. This allows sibling
|
||||
components outside the main UI to access and modify state without prop drilling
|
||||
or awkward refs.
|
||||
|
||||
**Incorrect (state trapped inside component):**
|
||||
|
||||
```tsx
|
||||
function ForwardMessageComposer() {
|
||||
const [state, setState] = useState(initialState)
|
||||
const forwardMessage = useForwardMessage()
|
||||
|
||||
return (
|
||||
<Composer.Frame>
|
||||
<Composer.Input />
|
||||
<Composer.Footer />
|
||||
</Composer.Frame>
|
||||
)
|
||||
}
|
||||
|
||||
// Problem: How does this button access composer state?
|
||||
function ForwardMessageDialog() {
|
||||
return (
|
||||
<Dialog>
|
||||
<ForwardMessageComposer />
|
||||
<MessagePreview /> {/* Needs composer state */}
|
||||
<DialogActions>
|
||||
<CancelButton />
|
||||
<ForwardButton /> {/* Needs to call submit */}
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Incorrect (useEffect to sync state up):**
|
||||
|
||||
```tsx
|
||||
function ForwardMessageDialog() {
|
||||
const [input, setInput] = useState('')
|
||||
return (
|
||||
<Dialog>
|
||||
<ForwardMessageComposer onInputChange={setInput} />
|
||||
<MessagePreview input={input} />
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
function ForwardMessageComposer({ onInputChange }) {
|
||||
const [state, setState] = useState(initialState)
|
||||
useEffect(() => {
|
||||
onInputChange(state.input) // Sync on every change 😬
|
||||
}, [state.input])
|
||||
}
|
||||
```
|
||||
|
||||
**Incorrect (reading state from ref on submit):**
|
||||
|
||||
```tsx
|
||||
function ForwardMessageDialog() {
|
||||
const stateRef = useRef(null)
|
||||
return (
|
||||
<Dialog>
|
||||
<ForwardMessageComposer stateRef={stateRef} />
|
||||
<ForwardButton onPress={() => submit(stateRef.current)} />
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (state lifted to provider):**
|
||||
|
||||
```tsx
|
||||
function ForwardMessageProvider({ children }: { children: React.ReactNode }) {
|
||||
const [state, setState] = useState(initialState)
|
||||
const forwardMessage = useForwardMessage()
|
||||
const inputRef = useRef(null)
|
||||
|
||||
return (
|
||||
<Composer.Provider
|
||||
state={state}
|
||||
actions={{ update: setState, submit: forwardMessage }}
|
||||
meta={{ inputRef }}
|
||||
>
|
||||
{children}
|
||||
</Composer.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
function ForwardMessageDialog() {
|
||||
return (
|
||||
<ForwardMessageProvider>
|
||||
<Dialog>
|
||||
<ForwardMessageComposer />
|
||||
<MessagePreview /> {/* Custom components can access state and actions */}
|
||||
<DialogActions>
|
||||
<CancelButton />
|
||||
<ForwardButton /> {/* Custom components can access state and actions */}
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
</ForwardMessageProvider>
|
||||
)
|
||||
}
|
||||
|
||||
function ForwardButton() {
|
||||
const { actions } = use(Composer.Context)
|
||||
return <Button onPress={actions.submit}>Forward</Button>
|
||||
}
|
||||
```
|
||||
|
||||
The ForwardButton lives outside the Composer.Frame but still has access to the
|
||||
submit action because it's within the provider. Even though it's a one-off
|
||||
component, it can still access the composer's state and actions from outside the
|
||||
UI itself.
|
||||
|
||||
**Key insight:** Components that need shared state don't have to be visually
|
||||
nested inside each other—they just need to be within the same provider.
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
@@ -0,0 +1,81 @@
|
||||
---
|
||||
name: ext-frontend-design
|
||||
description: Guidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults.
|
||||
license: Complete terms in LICENSE.txt
|
||||
---
|
||||
|
||||
> **Project rules win.** Vendored by @intecion/ipal-kit as guidance. When this skill conflicts with
|
||||
> `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md`, the project's `AGENTS.md` or `DESIGN.md`, those win:
|
||||
> ipal-kit features first (the `ipal-reference` skill), Payload 3 + Next 16 App Router, data from Server Components
|
||||
> through Payload / `@/lib/content`, every visible text from the CMS, design values from `DESIGN.md` tokens.
|
||||
> Never add a dependency this skill suggests without the owner's decision.
|
||||
>
|
||||
> **Design tokens:** the project's `DESIGN.md` tokens win. Use this skill to write or extend `DESIGN.md` (with the
|
||||
> owner's approval); components never contain hex colours, font names or text — only Tailwind tokens and CMS text.
|
||||
|
||||
|
||||
# Frontend Design
|
||||
|
||||
Approach this as the design lead at a design studio known for giving every client a distinct visual identity that is not mistaken for anyone else's. This client has already rejected proposals that felt cliché or templated, and is paying for a distinctive point of view: make deliberate, opinionated choices about palette, typography, and layout that are specific to this brief, and take aesthetic risk if justified.
|
||||
|
||||
## Ground your designs in the subject matter
|
||||
|
||||
If the brief does not identify what the product or subject matter is, identify it yourself before designing, and confirm with the client. You can come up with one concrete subject, the design's audience, and the design's primary job, as a proposal. If there's any information in your memory about the client's preferences or context about what they're building, use that as a hint. The subject's industry, subject matter, materials, and vernacular are where distinctive visual choices come from — a design for a toy for girls aged 8–11 will be very aesthetically different from a dashboard for financial analysts. Build with the brief's real content and subject matter throughout.
|
||||
|
||||
## Design principles
|
||||
|
||||
For web designs, the hero is the first thing viewers will see. Open with the most characteristic thing in the subject's world, in the form that is most appropriate: a headline, an image, an animation, a live demo, an interactive moment, or other treatments. Be deliberate with your choice: a big number with a small label, supporting stats, and a gradient accent is the default treatment, so only use it if that's truly the best option.
|
||||
|
||||
Typography carries the personality of the page. You don't need a different typeface for display or headline text and body content: use one family or two, and if two, make them clearly distinct.
|
||||
|
||||
Choose your typefaces deliberately, not the default families you would reach for on any other project, and set a clear type scale following the default guidance of The Elements of Typographic Style with intentional weights, widths, and spacing. When type is used as a headline or visual element, use the type treatment itself as an active part of the design, not a neutral delivery vehicle for the content.
|
||||
|
||||
Default to line lengths of less than 80 characters. Serif typefaces can have slightly longer line lengths; give serif body text slightly more line-height than a sans-serif.
|
||||
|
||||
Avoid these default typographic treatments; they are the commonest tells of a generated page:
|
||||
- Accenting just a single word or phrase in a headline, like putting one word in italic/bold or a different color.
|
||||
- Using all caps for labels.
|
||||
- Adding unnecessary typographic labels above content.
|
||||
|
||||
Visual structure is information. Structural devices like outlines, borders, numbering, eyebrows, dividers, labels, etc., encode useful information about the content rather than decorate it. Many generic designs use numbered markers (01 / 02 / 03), but that's only appropriate if the content actually is a sequence — like a stepped process or a timeline. Before adding numbered markers, check the content really is a sequence.
|
||||
|
||||
Use non-user-triggered motion sparingly and deliberately, only to draw attention. A single orchestrated moment — one page-load sequence or one reveal — lands better than scattered effects; fade-and-slide-up entrances on each section and hover transitions on every card are the generic default and read as AI-generated. Motion that answers a person's action (opening, expanding, confirming) is welcome when it shows what changed.
|
||||
|
||||
Consider written content carefully. Often a design brief may not contain real content, and it's up to you to come up with copy and placeholder content. Copy can make a design feel as templated as the design itself. See the below section on writing for more guidance.
|
||||
|
||||
## Process: plan, review against the brief, build, critique
|
||||
|
||||
For calibration, AI-generated design right now clusters around some traits:
|
||||
1. a warm cream background (near #F4F1EA) with a high-contrast serif display and a terracotta or warm-clay accent (often near #D97757 — Anthropic's own Claude-interaction accent, so on a user's brief it reads as a tell);
|
||||
2. a near-black background with a single bright acid-green or vermilion accent;
|
||||
3. a broadsheet-style layout with hairline rules, zero border-radius, and dense newspaper-like columns;
|
||||
4. the SaaS-card kit: content chopped into identical rounded cards, one border-radius on everything regardless of hierarchy, the same soft grey shadow (rgba(0,0,0,.1)) under each, and gradient washes as decoration;
|
||||
5. template chrome that appears whatever the subject: a tracked-out ALL-CAPS eyebrow label above every heading; meta strings joined with middle dots ('A · B · C'); labels built as 'WORD — fragment' with a spaced em dash; tinted near-black (#0B0B0B, #111) standing in for black; a monospace face for small data labels; a '→' appended to link and button text.
|
||||
|
||||
All traits are legitimate for some briefs, but they are defaults rather than choices, and they appear regardless of subject. Where the brief pins down a visual direction, follow it exactly — the brief's own words always win, including when it asks for one of these looks. Where it leaves an axis free, don't spend that freedom on one of these defaults. As with a hired human designer, there's often a careful balance between doing what you're good at and taking each project as a chance to experiment and learn.
|
||||
|
||||
Work in two passes. First, brainstorm a short design plan based on the client's design brief: create a compact token system with color, type, layout, and principles.
|
||||
- Color: describe the core base palette as 4–6 named hex values.
|
||||
- Type: the typefaces and their roles.
|
||||
- Layout: a layout concept, using one-sentence prose descriptions and ASCII wireframes to ideate and compare. Include alignment guidance; should the content be left aligned, center aligned, justified?
|
||||
- Principles: the high-level guidance for what makes this page unique.
|
||||
|
||||
Then review that plan against the brief before building: if any part of it reads like the generic default you would produce for any similar page (work through a similar prompt to see if you arrive somewhere similar) rather than a choice made for this specific brief — revise that part, say what you changed and why. Only after you've confirmed the relative uniqueness of your design plan should you start to write the code, following the revised plan.
|
||||
|
||||
When writing the code, be careful of structuring your CSS selector specificities. It's easy to generate CSS classes that cancel each other out (especially with a type-based selector like .section and an element-based selector like .cta). This can happen often with padding/margin between sections.
|
||||
|
||||
## Restraint and self-critique
|
||||
|
||||
Spend your boldness in one place. Let one element be the memorable thing, keep everything around it quiet and disciplined, and cut any decoration that does not serve the brief. Build to a quality floor without announcing it: responsive down to mobile, visible keyboard focus, reduced motion respected, visually accessible, harmonious color palettes. Critique your own work as you build, taking screenshots to review if your environment supports it — a picture is worth 1000 tokens. Consider Chanel's advice: before leaving the house, take a look in the mirror and remove one accessory. Human creatives have memory and always try to do something new, so if you have a space to quickly jot down notes about what you've tried, it can help you in future passes.
|
||||
|
||||
## More on writing in design
|
||||
|
||||
Words appear in a design for one reason: to make it easier to understand and use. They are design content, not decoration. Bring the same intentionality and minimalism to copywriting that you would bring to spacing and color. Before writing anything, ask what the design needs to say, and how it can best be said to help the person navigate the experience.
|
||||
|
||||
Write from the end user's perspective. Name things by what users will understand in simple language, not by how the system is built. A user manages notifications, not webhook config. Describe what something is or does in plain terms rather than selling it. Being specific and legible to new users is always better than being clever.
|
||||
|
||||
Use active voice as default. A CTA says exactly what happens when it is used: "Save changes," not "Submit." An action keeps the same name through the whole flow, so the button that says "Publish" produces a toast that says "Published." The vocabulary of an interface is the signposting for someone navigating the product. Cohesion and consistency are how people learn their way around.
|
||||
|
||||
Treat failure and emptiness as moments for direction, not mood. Explain what went wrong and how to fix it, in the interface's voice rather than a person's. Errors don't apologize, and they are never vague about what happened. An empty screen is an invitation to act.
|
||||
|
||||
Keep the tone conversational: plain verbs, sentence case, no filler, with tone matched to the brand and the audience. Let each written element do exactly one job.
|
||||
@@ -0,0 +1,14 @@
|
||||
# ext-frontend-design
|
||||
|
||||
Vendored by @intecion/ipal-kit (`ipal-skills --external`). Do not edit — regenerate with
|
||||
`scripts/vendor-external-skills.mjs` in the ipal-kit repository.
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Publisher | Anthropic |
|
||||
| Source | https://github.com/anthropics/skills/tree/ca45fc496a3436251f191354091d557da31c15b5/skills/frontend-design |
|
||||
| Commit | `ca45fc496a3436251f191354091d557da31c15b5` |
|
||||
| Licence | Apache-2.0 (see the LICENSE file in this folder) |
|
||||
|
||||
Changes from the upstream text: the `name` in the SKILL.md frontmatter is `ext-frontend-design`, and an
|
||||
override note (project rules win) is inserted after the frontmatter. Nothing else is changed.
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2018-2025 Payload CMS, Inc. <info@payloadcms.com>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
'Software'), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
||||
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
||||
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
+459
@@ -0,0 +1,459 @@
|
||||
---
|
||||
name: ext-payload
|
||||
description: Use when working with Payload CMS projects (payload.config.ts, collections, fields, hooks, access control, Payload API). Use when debugging validation errors, security issues, relationship queries, transactions, or hook behavior.
|
||||
---
|
||||
|
||||
> **Project rules win.** Vendored by @intecion/ipal-kit as guidance. When this skill conflicts with
|
||||
> `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md`, the project's `AGENTS.md` or `DESIGN.md`, those win:
|
||||
> ipal-kit features first (the `ipal-reference` skill), Payload 3 + Next 16 App Router, data from Server Components
|
||||
> through Payload / `@/lib/content`, every visible text from the CMS, design values from `DESIGN.md` tokens.
|
||||
> Never add a dependency this skill suggests without the owner's decision.
|
||||
>
|
||||
> **Reference only — Payload 3 (v3.92.1).** Never apply Payload 4 guidance. ipal-kit already provides users and roles,
|
||||
> 2FA, SEO, forms, i18n, the site globals, revalidation and storage — check the `ipal-reference` skill before you
|
||||
> write Payload config, hooks or access rules by hand.
|
||||
|
||||
|
||||
# Payload CMS Application Development
|
||||
|
||||
Payload is a Next.js native CMS with TypeScript-first architecture, providing admin panel, database management, REST/GraphQL APIs, authentication, and file storage.
|
||||
|
||||
## Quick Reference
|
||||
|
||||
| Task | Solution | Details |
|
||||
| ------------------------ | ----------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Auto-generate slugs | `slugField()` | [FIELDS.md#slug-field-helper](reference/FIELDS.md#slug-field-helper) |
|
||||
| Restrict content by user | Access control with query | [ACCESS-CONTROL.md#row-level-security-with-complex-queries](reference/ACCESS-CONTROL.md#row-level-security-with-complex-queries) |
|
||||
| Local API user ops | `user` + `overrideAccess: false` | [QUERIES.md#access-control-in-local-api](reference/QUERIES.md#access-control-in-local-api) |
|
||||
| Draft/publish workflow | `versions: { drafts: true }` | [COLLECTIONS.md#versioning--drafts](reference/COLLECTIONS.md#versioning--drafts) |
|
||||
| Computed fields | `virtual: true` with afterRead | [FIELDS.md#virtual-fields](reference/FIELDS.md#virtual-fields) |
|
||||
| Conditional fields | `admin.condition` | [FIELDS.md#conditional-fields](reference/FIELDS.md#conditional-fields) |
|
||||
| Custom field validation | `validate` function | [FIELDS.md#validation](reference/FIELDS.md#validation) |
|
||||
| Filter relationship list | `filterOptions` on field | [FIELDS.md#relationship](reference/FIELDS.md#relationship) |
|
||||
| Select specific fields | `select` parameter | [QUERIES.md#field-selection](reference/QUERIES.md#field-selection) |
|
||||
| Auto-set author/dates | beforeChange hook | [HOOKS.md#collection-hooks](reference/HOOKS.md#collection-hooks) |
|
||||
| Prevent hook loops | `req.context` check | [HOOKS.md#context](reference/HOOKS.md#context) |
|
||||
| Cascading deletes | beforeDelete hook | [HOOKS.md#collection-hooks](reference/HOOKS.md#collection-hooks) |
|
||||
| Geospatial queries | `point` field with `near`/`within` | [FIELDS.md#point-geolocation](reference/FIELDS.md#point-geolocation) |
|
||||
| Reverse relationships | `join` field type | [FIELDS.md#join-fields](reference/FIELDS.md#join-fields) |
|
||||
| Next.js revalidation | Context control in afterChange | [HOOKS.md#nextjs-revalidation-with-context-control](reference/HOOKS.md#nextjs-revalidation-with-context-control) |
|
||||
| Query by relationship | Nested property syntax | [QUERIES.md#nested-properties](reference/QUERIES.md#nested-properties) |
|
||||
| Complex queries | AND/OR logic | [QUERIES.md#andor-logic](reference/QUERIES.md#andor-logic) |
|
||||
| Transactions | Pass `req` to operations | [ADAPTERS.md#threading-req-through-operations](reference/ADAPTERS.md#threading-req-through-operations) |
|
||||
| Background jobs | Jobs queue with tasks | [ADVANCED.md#jobs-queue](reference/ADVANCED.md#jobs-queue) |
|
||||
| Custom API routes | Collection custom endpoints | [ADVANCED.md#custom-endpoints](reference/ADVANCED.md#custom-endpoints) |
|
||||
| Cloud storage | Storage adapter plugins | [ADAPTERS.md#storage-adapters](reference/ADAPTERS.md#storage-adapters) |
|
||||
| Multi-language | `localization` config + `localized: true` | [ADVANCED.md#localization](reference/ADVANCED.md#localization) |
|
||||
| Create plugin | `(options) => (config) => Config` | [PLUGIN-DEVELOPMENT.md#plugin-architecture](reference/PLUGIN-DEVELOPMENT.md#plugin-architecture) |
|
||||
| Plugin package setup | Package structure with SWC | [PLUGIN-DEVELOPMENT.md#plugin-package-structure](reference/PLUGIN-DEVELOPMENT.md#plugin-package-structure) |
|
||||
| Add fields to collection | Map collections, spread fields | [PLUGIN-DEVELOPMENT.md#adding-fields-to-collections](reference/PLUGIN-DEVELOPMENT.md#adding-fields-to-collections) |
|
||||
| Plugin hooks | Preserve existing hooks in array | [PLUGIN-DEVELOPMENT.md#adding-hooks](reference/PLUGIN-DEVELOPMENT.md#adding-hooks) |
|
||||
| Check field type | Type guard functions | [FIELD-TYPE-GUARDS.md](reference/FIELD-TYPE-GUARDS.md) |
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
npx create-payload-app@latest my-app
|
||||
cd my-app
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
### Minimal Config
|
||||
|
||||
```ts
|
||||
import { buildConfig } from 'payload'
|
||||
import { mongooseAdapter } from '@payloadcms/db-mongodb'
|
||||
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
||||
import path from 'path'
|
||||
import { fileURLToPath } from 'url'
|
||||
|
||||
const filename = fileURLToPath(import.meta.url)
|
||||
const dirname = path.dirname(filename)
|
||||
|
||||
export default buildConfig({
|
||||
admin: {
|
||||
user: 'users',
|
||||
importMap: {
|
||||
baseDir: path.resolve(dirname),
|
||||
},
|
||||
},
|
||||
collections: [Users, Media],
|
||||
editor: lexicalEditor(),
|
||||
secret: process.env.PAYLOAD_SECRET,
|
||||
typescript: {
|
||||
outputFile: path.resolve(dirname, 'payload-types.ts'),
|
||||
},
|
||||
db: mongooseAdapter({
|
||||
url: process.env.DATABASE_URL,
|
||||
}),
|
||||
})
|
||||
```
|
||||
|
||||
## Essential Patterns
|
||||
|
||||
### Basic Collection
|
||||
|
||||
```ts
|
||||
import type { CollectionConfig } from 'payload'
|
||||
|
||||
export const Posts: CollectionConfig = {
|
||||
slug: 'posts',
|
||||
admin: {
|
||||
useAsTitle: 'title',
|
||||
defaultColumns: ['title', 'author', 'status', 'createdAt'],
|
||||
},
|
||||
fields: [
|
||||
{ name: 'title', type: 'text', required: true },
|
||||
{ name: 'slug', type: 'text', unique: true, index: true },
|
||||
{ name: 'content', type: 'richText' },
|
||||
{ name: 'author', type: 'relationship', relationTo: 'users' },
|
||||
],
|
||||
timestamps: true,
|
||||
}
|
||||
```
|
||||
|
||||
For more collection patterns (auth, upload, drafts, live preview), see [COLLECTIONS.md](reference/COLLECTIONS.md).
|
||||
|
||||
### Common Fields
|
||||
|
||||
```ts
|
||||
// Text field
|
||||
{ name: 'title', type: 'text', required: true }
|
||||
|
||||
// Relationship
|
||||
{ name: 'author', type: 'relationship', relationTo: 'users', required: true }
|
||||
|
||||
// Rich text
|
||||
{ name: 'content', type: 'richText', required: true }
|
||||
|
||||
// Select
|
||||
{ name: 'status', type: 'select', options: ['draft', 'published'], defaultValue: 'draft' }
|
||||
|
||||
// Upload
|
||||
{ name: 'image', type: 'upload', relationTo: 'media' }
|
||||
```
|
||||
|
||||
For all field types (array, blocks, point, join, virtual, conditional, etc.), see [FIELDS.md](reference/FIELDS.md).
|
||||
|
||||
### Hook Example
|
||||
|
||||
```ts
|
||||
export const Posts: CollectionConfig = {
|
||||
slug: 'posts',
|
||||
hooks: {
|
||||
beforeChange: [
|
||||
async ({ data, operation }) => {
|
||||
if (operation === 'create') {
|
||||
data.slug = slugify(data.title)
|
||||
}
|
||||
return data
|
||||
},
|
||||
],
|
||||
},
|
||||
fields: [{ name: 'title', type: 'text' }],
|
||||
}
|
||||
```
|
||||
|
||||
For all hook patterns, see [HOOKS.md](reference/HOOKS.md). For access control, see [ACCESS-CONTROL.md](reference/ACCESS-CONTROL.md).
|
||||
|
||||
### Access Control with Type Safety
|
||||
|
||||
```ts
|
||||
import type { Access } from 'payload'
|
||||
import type { User } from '@/payload-types'
|
||||
|
||||
// Type-safe access control
|
||||
export const adminOnly: Access = ({ req }) => {
|
||||
const user = req.user as User
|
||||
return user?.roles?.includes('admin') || false
|
||||
}
|
||||
|
||||
// Row-level access control
|
||||
export const ownPostsOnly: Access = ({ req }) => {
|
||||
const user = req.user as User
|
||||
if (!user) return false
|
||||
if (user.roles?.includes('admin')) return true
|
||||
|
||||
return {
|
||||
author: { equals: user.id },
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Query Example
|
||||
|
||||
```ts
|
||||
// Local API
|
||||
const posts = await payload.find({
|
||||
collection: 'posts',
|
||||
where: {
|
||||
status: { equals: 'published' },
|
||||
'author.name': { contains: 'john' },
|
||||
},
|
||||
depth: 2,
|
||||
limit: 10,
|
||||
sort: '-createdAt',
|
||||
})
|
||||
|
||||
// Query with populated relationships
|
||||
const post = await payload.findByID({
|
||||
collection: 'posts',
|
||||
id: '123',
|
||||
depth: 2, // Populates relationships (default is 2)
|
||||
})
|
||||
// Returns: { author: { id: "user123", name: "John" } }
|
||||
|
||||
// Without depth, relationships return IDs only
|
||||
const post = await payload.findByID({
|
||||
collection: 'posts',
|
||||
id: '123',
|
||||
depth: 0,
|
||||
})
|
||||
// Returns: { author: "user123" }
|
||||
```
|
||||
|
||||
For all query operators and REST/GraphQL examples, see [QUERIES.md](reference/QUERIES.md).
|
||||
|
||||
### Getting Payload Instance
|
||||
|
||||
```ts
|
||||
// In API routes (Next.js)
|
||||
import { getPayload } from 'payload'
|
||||
import config from '@payload-config'
|
||||
|
||||
export async function GET() {
|
||||
const payload = await getPayload({ config })
|
||||
|
||||
const posts = await payload.find({
|
||||
collection: 'posts',
|
||||
})
|
||||
|
||||
return Response.json(posts)
|
||||
}
|
||||
|
||||
// In Server Components
|
||||
import { getPayload } from 'payload'
|
||||
import config from '@payload-config'
|
||||
|
||||
export default async function Page() {
|
||||
const payload = await getPayload({ config })
|
||||
const { docs } = await payload.find({ collection: 'posts' })
|
||||
|
||||
return <div>{docs.map(post => <h1 key={post.id}>{post.title}</h1>)}</div>
|
||||
}
|
||||
```
|
||||
|
||||
## Security Pitfalls
|
||||
|
||||
### 1. Local API Access Control (CRITICAL)
|
||||
|
||||
**By default, Local API operations bypass ALL access control**, even when passing a user.
|
||||
|
||||
```ts
|
||||
// ❌ SECURITY BUG: Passes user but ignores their permissions
|
||||
await payload.find({
|
||||
collection: 'posts',
|
||||
user: someUser, // Access control is BYPASSED!
|
||||
})
|
||||
|
||||
// ✅ SECURE: Actually enforces the user's permissions
|
||||
await payload.find({
|
||||
collection: 'posts',
|
||||
user: someUser,
|
||||
overrideAccess: false, // REQUIRED for access control
|
||||
})
|
||||
```
|
||||
|
||||
**When to use each:**
|
||||
|
||||
- `overrideAccess: true` (default) - Server-side operations you trust (cron jobs, system tasks)
|
||||
- `overrideAccess: false` - When operating on behalf of a user (API routes, webhooks)
|
||||
|
||||
See [QUERIES.md#access-control-in-local-api](reference/QUERIES.md#access-control-in-local-api).
|
||||
|
||||
### 2. Transaction Failures in Hooks
|
||||
|
||||
**Nested operations in hooks without `req` break transaction atomicity.**
|
||||
|
||||
```ts
|
||||
// ❌ DATA CORRUPTION RISK: Separate transaction
|
||||
hooks: {
|
||||
afterChange: [
|
||||
async ({ doc, req }) => {
|
||||
await req.payload.create({
|
||||
collection: 'audit-log',
|
||||
data: { docId: doc.id },
|
||||
// Missing req - runs in separate transaction!
|
||||
})
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
// ✅ ATOMIC: Same transaction
|
||||
hooks: {
|
||||
afterChange: [
|
||||
async ({ doc, req }) => {
|
||||
await req.payload.create({
|
||||
collection: 'audit-log',
|
||||
data: { docId: doc.id },
|
||||
req, // Maintains atomicity
|
||||
})
|
||||
},
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
See [ADAPTERS.md#threading-req-through-operations](reference/ADAPTERS.md#threading-req-through-operations).
|
||||
|
||||
### 3. Infinite Hook Loops
|
||||
|
||||
**Hooks triggering operations that trigger the same hooks create infinite loops.**
|
||||
|
||||
```ts
|
||||
// ❌ INFINITE LOOP
|
||||
hooks: {
|
||||
afterChange: [
|
||||
async ({ doc, req }) => {
|
||||
await req.payload.update({
|
||||
collection: 'posts',
|
||||
id: doc.id,
|
||||
data: { views: doc.views + 1 },
|
||||
req,
|
||||
}) // Triggers afterChange again!
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
// ✅ SAFE: Use context flag
|
||||
hooks: {
|
||||
afterChange: [
|
||||
async ({ doc, req, context }) => {
|
||||
if (context.skipHooks) return
|
||||
|
||||
await req.payload.update({
|
||||
collection: 'posts',
|
||||
id: doc.id,
|
||||
data: { views: doc.views + 1 },
|
||||
context: { skipHooks: true },
|
||||
req,
|
||||
})
|
||||
},
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
See [HOOKS.md#context](reference/HOOKS.md#context).
|
||||
|
||||
## Project Structure
|
||||
|
||||
```txt
|
||||
src/
|
||||
├── app/
|
||||
│ ├── (frontend)/
|
||||
│ │ └── page.tsx
|
||||
│ └── (payload)/
|
||||
│ └── admin/[[...segments]]/page.tsx
|
||||
├── collections/
|
||||
│ ├── Posts.ts
|
||||
│ ├── Media.ts
|
||||
│ └── Users.ts
|
||||
├── globals/
|
||||
│ └── Header.ts
|
||||
├── components/
|
||||
│ └── CustomField.tsx
|
||||
├── hooks/
|
||||
│ └── slugify.ts
|
||||
└── payload.config.ts
|
||||
```
|
||||
|
||||
## Type Generation
|
||||
|
||||
```ts
|
||||
// payload.config.ts
|
||||
export default buildConfig({
|
||||
typescript: {
|
||||
outputFile: path.resolve(dirname, 'payload-types.ts'),
|
||||
},
|
||||
// ...
|
||||
})
|
||||
|
||||
// Usage
|
||||
import type { Post, User } from '@/payload-types'
|
||||
```
|
||||
|
||||
## Common Gotchas
|
||||
|
||||
1. **Local API bypasses access control** unless you pass `overrideAccess: false`
|
||||
2. **Missing `req` in nested operations** breaks transaction atomicity
|
||||
3. **Hook loops** — operations in hooks can re-trigger the same hooks; use `req.context` flags
|
||||
4. **Field-level access** returns boolean only, no query constraints
|
||||
5. **Relationship depth** defaults to 2; set `depth: 0` for IDs only
|
||||
6. **Draft status** — `_status` field is auto-injected when drafts are enabled
|
||||
7. **Types are stale** until you run `generate:types`
|
||||
8. **MongoDB transactions** require replica set configuration
|
||||
9. **SQLite transactions** are disabled by default; enable with `transactionOptions: {}`
|
||||
10. **Point fields** are not supported in SQLite
|
||||
|
||||
## Best Practices
|
||||
|
||||
### Security
|
||||
|
||||
- Default to restrictive access, gradually add permissions
|
||||
- Use `overrideAccess: false` when passing `user` to Local API
|
||||
- Field-level access only returns boolean (no query constraints)
|
||||
- Never trust client-provided data
|
||||
- Use `saveToJWT: true` for roles to avoid database lookups
|
||||
|
||||
### Performance
|
||||
|
||||
- Index frequently queried fields
|
||||
- Use `select` to limit returned fields
|
||||
- Set `maxDepth` on relationships to prevent over-fetching
|
||||
- Prefer query constraints over async operations in access control
|
||||
- Cache expensive operations in `req.context`
|
||||
|
||||
### Data Integrity
|
||||
|
||||
- Always pass `req` to nested operations in hooks
|
||||
- Use context flags to prevent infinite hook loops
|
||||
- Enable transactions for MongoDB (requires replica set) and Postgres
|
||||
- Use `beforeValidate` for data formatting
|
||||
- Use `beforeChange` for business logic
|
||||
|
||||
### Type Safety
|
||||
|
||||
- Run `generate:types` after schema changes
|
||||
- Import types from generated `payload-types.ts`
|
||||
- Type your user object: `import type { User } from '@/payload-types'`
|
||||
- Use `as const` for field options
|
||||
- Use field type guards for runtime type checking
|
||||
|
||||
### Organization
|
||||
|
||||
- Keep collections in separate files
|
||||
- Extract access control to `access/` directory
|
||||
- Extract hooks to `hooks/` directory
|
||||
- Use reusable field factories for common patterns
|
||||
- Document complex access control with comments
|
||||
|
||||
## Reference Documentation
|
||||
|
||||
- **[FIELDS.md](reference/FIELDS.md)** - All field types, validation, admin options
|
||||
- **[FIELD-TYPE-GUARDS.md](reference/FIELD-TYPE-GUARDS.md)** - Type guards for runtime field type checking and narrowing
|
||||
- **[COLLECTIONS.md](reference/COLLECTIONS.md)** - Collection configs, auth, upload, drafts, live preview
|
||||
- **[HOOKS.md](reference/HOOKS.md)** - Collection hooks, field hooks, context patterns
|
||||
- **[ACCESS-CONTROL.md](reference/ACCESS-CONTROL.md)** - Collection, field, global access control, RBAC, multi-tenant
|
||||
- **[ACCESS-CONTROL-ADVANCED.md](reference/ACCESS-CONTROL-ADVANCED.md)** - Context-aware, time-based, subscription-based access, factory functions, templates
|
||||
- **[QUERIES.md](reference/QUERIES.md)** - Query operators, Local/REST/GraphQL APIs
|
||||
- **[ENDPOINTS.md](reference/ENDPOINTS.md)** - Custom API endpoints: authentication, helpers, request/response patterns
|
||||
- **[ADAPTERS.md](reference/ADAPTERS.md)** - Database, storage, email adapters, transactions
|
||||
- **[ADVANCED.md](reference/ADVANCED.md)** - Authentication, jobs, endpoints, components, plugins, localization
|
||||
- **[PLUGIN-DEVELOPMENT.md](reference/PLUGIN-DEVELOPMENT.md)** - Plugin architecture, monorepo structure, patterns, best practices
|
||||
|
||||
## Resources
|
||||
|
||||
- llms-full.txt: <https://payloadcms.com/llms-full.txt>
|
||||
- Docs: <https://payloadcms.com/docs>
|
||||
- GitHub: <https://github.com/payloadcms/payload>
|
||||
- Examples: <https://github.com/payloadcms/payload/tree/3.x/examples>
|
||||
- Templates: <https://github.com/payloadcms/payload/tree/3.x/templates>
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
# ext-payload
|
||||
|
||||
Vendored by @intecion/ipal-kit (`ipal-skills --external`). Do not edit — regenerate with
|
||||
`scripts/vendor-external-skills.mjs` in the ipal-kit repository.
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Publisher | Payload CMS |
|
||||
| Source | https://github.com/payloadcms/payload/tree/9c396345dad3c831a34fd212299532e03dc4818f/tools/claude-plugin/skills/payload |
|
||||
| Commit | `9c396345dad3c831a34fd212299532e03dc4818f` |
|
||||
| Licence | MIT (see the LICENSE file in this folder) |
|
||||
|
||||
Changes from the upstream text: the `name` in the SKILL.md frontmatter is `ext-payload`, and an
|
||||
override note (project rules win) is inserted after the frontmatter. Nothing else is changed.
|
||||
@@ -0,0 +1,704 @@
|
||||
# Payload CMS Access Control - Advanced Patterns
|
||||
|
||||
Advanced access control patterns including context-aware access, time-based restrictions, factory functions, and production templates.
|
||||
|
||||
## Context-Aware Access Patterns
|
||||
|
||||
### Locale-Specific Access
|
||||
|
||||
Control access based on user locale for internationalized content.
|
||||
|
||||
```ts
|
||||
import type { Access } from 'payload'
|
||||
|
||||
export const localeSpecificAccess: Access = ({ req: { user, locale } }) => {
|
||||
// Authenticated users can access all locales
|
||||
if (user) return true
|
||||
|
||||
// Public users can only access English content
|
||||
if (locale === 'en') return true
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// Usage in collection
|
||||
export const Posts: CollectionConfig = {
|
||||
slug: 'posts',
|
||||
access: {
|
||||
read: localeSpecificAccess,
|
||||
},
|
||||
fields: [{ name: 'title', type: 'text', localized: true }],
|
||||
}
|
||||
```
|
||||
|
||||
**Source**: `docs/access-control/overview.mdx` (req.locale argument)
|
||||
|
||||
### Device-Specific Access
|
||||
|
||||
Restrict access based on device type or user agent.
|
||||
|
||||
```ts
|
||||
import type { Access } from 'payload'
|
||||
|
||||
export const mobileOnlyAccess: Access = ({ req: { headers } }) => {
|
||||
const userAgent = headers?.get('user-agent') || ''
|
||||
return /mobile|android|iphone/i.test(userAgent)
|
||||
}
|
||||
|
||||
export const desktopOnlyAccess: Access = ({ req: { headers } }) => {
|
||||
const userAgent = headers?.get('user-agent') || ''
|
||||
return !/mobile|android|iphone/i.test(userAgent)
|
||||
}
|
||||
|
||||
// Usage
|
||||
export const MobileContent: CollectionConfig = {
|
||||
slug: 'mobile-content',
|
||||
access: {
|
||||
read: mobileOnlyAccess,
|
||||
},
|
||||
fields: [{ name: 'title', type: 'text' }],
|
||||
}
|
||||
```
|
||||
|
||||
**Source**: Synthesized (headers pattern)
|
||||
|
||||
### IP-Based Access
|
||||
|
||||
Restrict access from specific IP addresses (requires middleware/proxy headers).
|
||||
|
||||
```ts
|
||||
import type { Access } from 'payload'
|
||||
|
||||
export const restrictedIpAccess = (allowedIps: string[]): Access => {
|
||||
return ({ req: { headers } }) => {
|
||||
const ip = headers?.get('x-forwarded-for') || headers?.get('x-real-ip')
|
||||
return allowedIps.includes(ip || '')
|
||||
}
|
||||
}
|
||||
|
||||
// Usage
|
||||
const internalIps = ['192.168.1.0/24', '10.0.0.5']
|
||||
|
||||
export const InternalDocs: CollectionConfig = {
|
||||
slug: 'internal-docs',
|
||||
access: {
|
||||
read: restrictedIpAccess(internalIps),
|
||||
},
|
||||
fields: [{ name: 'content', type: 'richText' }],
|
||||
}
|
||||
```
|
||||
|
||||
**Note**: Requires your server to pass IP address via headers (common with proxies/load balancers).
|
||||
|
||||
**Source**: Synthesized (headers pattern)
|
||||
|
||||
## Time-Based Access Patterns
|
||||
|
||||
### Today's Records Only
|
||||
|
||||
```ts
|
||||
import type { Access } from 'payload'
|
||||
|
||||
export const todayOnlyAccess: Access = ({ req: { user } }) => {
|
||||
if (!user) return false
|
||||
|
||||
const now = new Date()
|
||||
const startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate())
|
||||
const endOfDay = new Date(startOfDay.getTime() + 24 * 60 * 60 * 1000)
|
||||
|
||||
return {
|
||||
createdAt: {
|
||||
greater_than_equal: startOfDay.toISOString(),
|
||||
less_than: endOfDay.toISOString(),
|
||||
},
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Source**: `test/access-control/config.ts` (query constraint patterns)
|
||||
|
||||
### Recent Records (Last N Days)
|
||||
|
||||
```ts
|
||||
import type { Access } from 'payload'
|
||||
|
||||
export const recentRecordsAccess = (days: number): Access => {
|
||||
return ({ req: { user } }) => {
|
||||
if (!user) return false
|
||||
if (user.roles?.includes('admin')) return true
|
||||
|
||||
const cutoff = new Date()
|
||||
cutoff.setDate(cutoff.getDate() - days)
|
||||
|
||||
return {
|
||||
createdAt: {
|
||||
greater_than_equal: cutoff.toISOString(),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Usage: Users see only last 30 days, admins see all
|
||||
export const Logs: CollectionConfig = {
|
||||
slug: 'logs',
|
||||
access: {
|
||||
read: recentRecordsAccess(30),
|
||||
},
|
||||
fields: [{ name: 'message', type: 'text' }],
|
||||
}
|
||||
```
|
||||
|
||||
### Scheduled Content (Publish Date Range)
|
||||
|
||||
```ts
|
||||
import type { Access } from 'payload'
|
||||
|
||||
export const scheduledContentAccess: Access = ({ req: { user } }) => {
|
||||
// Editors see all content
|
||||
if (user?.roles?.includes('admin') || user?.roles?.includes('editor')) {
|
||||
return true
|
||||
}
|
||||
|
||||
const now = new Date().toISOString()
|
||||
|
||||
// Public sees only content within publish window
|
||||
return {
|
||||
and: [
|
||||
{ publishDate: { less_than_equal: now } },
|
||||
{
|
||||
or: [{ unpublishDate: { exists: false } }, { unpublishDate: { greater_than: now } }],
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Source**: Synthesized (query constraint + date patterns)
|
||||
|
||||
## Subscription-Based Access
|
||||
|
||||
### Active Subscription Required
|
||||
|
||||
```ts
|
||||
import type { Access } from 'payload'
|
||||
|
||||
export const activeSubscriptionAccess: Access = async ({ req: { user } }) => {
|
||||
if (!user) return false
|
||||
if (user.roles?.includes('admin')) return true
|
||||
|
||||
try {
|
||||
const subscription = await req.payload.findByID({
|
||||
collection: 'subscriptions',
|
||||
id: user.subscriptionId,
|
||||
})
|
||||
|
||||
return subscription?.status === 'active'
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// Usage
|
||||
export const PremiumContent: CollectionConfig = {
|
||||
slug: 'premium-content',
|
||||
access: {
|
||||
read: activeSubscriptionAccess,
|
||||
},
|
||||
fields: [{ name: 'title', type: 'text' }],
|
||||
}
|
||||
```
|
||||
|
||||
### Subscription Tier-Based Access
|
||||
|
||||
```ts
|
||||
import type { Access } from 'payload'
|
||||
|
||||
export const tierBasedAccess = (requiredTier: string): Access => {
|
||||
const tierHierarchy = ['free', 'basic', 'pro', 'enterprise']
|
||||
|
||||
return async ({ req: { user } }) => {
|
||||
if (!user) return false
|
||||
if (user.roles?.includes('admin')) return true
|
||||
|
||||
try {
|
||||
const subscription = await req.payload.findByID({
|
||||
collection: 'subscriptions',
|
||||
id: user.subscriptionId,
|
||||
})
|
||||
|
||||
if (subscription?.status !== 'active') return false
|
||||
|
||||
const userTierIndex = tierHierarchy.indexOf(subscription.tier)
|
||||
const requiredTierIndex = tierHierarchy.indexOf(requiredTier)
|
||||
|
||||
return userTierIndex >= requiredTierIndex
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Usage
|
||||
export const EnterpriseFeatures: CollectionConfig = {
|
||||
slug: 'enterprise-features',
|
||||
access: {
|
||||
read: tierBasedAccess('enterprise'),
|
||||
},
|
||||
fields: [{ name: 'feature', type: 'text' }],
|
||||
}
|
||||
```
|
||||
|
||||
**Source**: Synthesized (async + cross-collection pattern)
|
||||
|
||||
## Factory Functions
|
||||
|
||||
Reusable functions that generate access control configurations.
|
||||
|
||||
### createRoleBasedAccess
|
||||
|
||||
Generate access control for specific roles.
|
||||
|
||||
```ts
|
||||
import type { Access } from 'payload'
|
||||
|
||||
export function createRoleBasedAccess(roles: string[]): Access {
|
||||
return ({ req: { user } }) => {
|
||||
if (!user) return false
|
||||
return roles.some((role) => user.roles?.includes(role))
|
||||
}
|
||||
}
|
||||
|
||||
// Usage
|
||||
const adminOrEditor = createRoleBasedAccess(['admin', 'editor'])
|
||||
const moderatorAccess = createRoleBasedAccess(['admin', 'moderator'])
|
||||
|
||||
export const Posts: CollectionConfig = {
|
||||
slug: 'posts',
|
||||
access: {
|
||||
create: adminOrEditor,
|
||||
update: adminOrEditor,
|
||||
delete: moderatorAccess,
|
||||
},
|
||||
fields: [{ name: 'title', type: 'text' }],
|
||||
}
|
||||
```
|
||||
|
||||
**Source**: `test/access-control/config.ts`
|
||||
|
||||
### createOrgScopedAccess
|
||||
|
||||
Generate organization-scoped access with optional admin bypass.
|
||||
|
||||
```ts
|
||||
import type { Access } from 'payload'
|
||||
|
||||
export function createOrgScopedAccess(allowAdmin = true): Access {
|
||||
return ({ req: { user } }) => {
|
||||
if (!user) return false
|
||||
if (allowAdmin && user.roles?.includes('admin')) return true
|
||||
|
||||
return {
|
||||
organizationId: { in: user.organizationIds || [] },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Usage
|
||||
const orgScoped = createOrgScopedAccess() // Admins bypass
|
||||
const strictOrgScoped = createOrgScopedAccess(false) // Admins also scoped
|
||||
|
||||
export const Projects: CollectionConfig = {
|
||||
slug: 'projects',
|
||||
access: {
|
||||
read: orgScoped,
|
||||
update: orgScoped,
|
||||
delete: strictOrgScoped,
|
||||
},
|
||||
fields: [
|
||||
{ name: 'title', type: 'text' },
|
||||
{ name: 'organizationId', type: 'text', required: true },
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
**Source**: `test/access-control/config.ts`
|
||||
|
||||
### createTeamBasedAccess
|
||||
|
||||
Generate team-scoped access with configurable field name.
|
||||
|
||||
```ts
|
||||
import type { Access } from 'payload'
|
||||
|
||||
export function createTeamBasedAccess(teamField = 'teamId'): Access {
|
||||
return ({ req: { user } }) => {
|
||||
if (!user) return false
|
||||
if (user.roles?.includes('admin')) return true
|
||||
|
||||
return {
|
||||
[teamField]: { in: user.teamIds || [] },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Usage with custom field name
|
||||
const projectTeamAccess = createTeamBasedAccess('projectTeam')
|
||||
|
||||
export const Tasks: CollectionConfig = {
|
||||
slug: 'tasks',
|
||||
access: {
|
||||
read: projectTeamAccess,
|
||||
update: projectTeamAccess,
|
||||
},
|
||||
fields: [
|
||||
{ name: 'title', type: 'text' },
|
||||
{ name: 'projectTeam', type: 'text', required: true },
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
**Source**: Synthesized (org pattern variation)
|
||||
|
||||
### createTimeLimitedAccess
|
||||
|
||||
Generate access limited to records within specified days.
|
||||
|
||||
```ts
|
||||
import type { Access } from 'payload'
|
||||
|
||||
export function createTimeLimitedAccess(daysAccess: number): Access {
|
||||
return ({ req: { user } }) => {
|
||||
if (!user) return false
|
||||
if (user.roles?.includes('admin')) return true
|
||||
|
||||
const cutoff = new Date()
|
||||
cutoff.setDate(cutoff.getDate() - daysAccess)
|
||||
|
||||
return {
|
||||
createdAt: {
|
||||
greater_than_equal: cutoff.toISOString(),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Usage: Users see 90 days, admins see all
|
||||
export const ActivityLogs: CollectionConfig = {
|
||||
slug: 'activity-logs',
|
||||
access: {
|
||||
read: createTimeLimitedAccess(90),
|
||||
},
|
||||
fields: [{ name: 'action', type: 'text' }],
|
||||
}
|
||||
```
|
||||
|
||||
**Source**: Synthesized (time + query pattern)
|
||||
|
||||
## Configuration Templates
|
||||
|
||||
Complete collection configurations for common scenarios.
|
||||
|
||||
### Basic Authenticated Collection
|
||||
|
||||
```ts
|
||||
import type { CollectionConfig } from 'payload'
|
||||
|
||||
export const BasicCollection: CollectionConfig = {
|
||||
slug: 'basic-collection',
|
||||
access: {
|
||||
create: ({ req: { user } }) => Boolean(user),
|
||||
read: ({ req: { user } }) => Boolean(user),
|
||||
update: ({ req: { user } }) => Boolean(user),
|
||||
delete: ({ req: { user } }) => Boolean(user),
|
||||
},
|
||||
fields: [
|
||||
{ name: 'title', type: 'text', required: true },
|
||||
{ name: 'content', type: 'richText' },
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
**Source**: `docs/access-control/collections.mdx`
|
||||
|
||||
### Public + Authenticated Collection
|
||||
|
||||
```ts
|
||||
import type { CollectionConfig } from 'payload'
|
||||
|
||||
export const PublicAuthCollection: CollectionConfig = {
|
||||
slug: 'posts',
|
||||
access: {
|
||||
// Only admins/editors can create
|
||||
create: ({ req: { user } }) => {
|
||||
return user?.roles?.some((role) => ['admin', 'editor'].includes(role)) || false
|
||||
},
|
||||
|
||||
// Authenticated users see all, public sees only published
|
||||
read: ({ req: { user } }) => {
|
||||
if (user) return true
|
||||
return { _status: { equals: 'published' } }
|
||||
},
|
||||
|
||||
// Only admins/editors can update
|
||||
update: ({ req: { user } }) => {
|
||||
return user?.roles?.some((role) => ['admin', 'editor'].includes(role)) || false
|
||||
},
|
||||
|
||||
// Only admins can delete
|
||||
delete: ({ req: { user } }) => {
|
||||
return user?.roles?.includes('admin') || false
|
||||
},
|
||||
},
|
||||
versions: {
|
||||
drafts: true,
|
||||
},
|
||||
fields: [
|
||||
{ name: 'title', type: 'text', required: true },
|
||||
{ name: 'content', type: 'richText', required: true },
|
||||
{ name: 'author', type: 'relationship', relationTo: 'users' },
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
**Source**: `templates/website/src/collections/Posts/index.ts`
|
||||
|
||||
### Multi-User/Self-Service Collection
|
||||
|
||||
```ts
|
||||
import type { CollectionConfig } from 'payload'
|
||||
|
||||
export const SelfServiceCollection: CollectionConfig = {
|
||||
slug: 'users',
|
||||
auth: true,
|
||||
access: {
|
||||
// Admins can create users
|
||||
create: ({ req: { user } }) => user?.roles?.includes('admin') || false,
|
||||
|
||||
// Anyone can read user profiles
|
||||
read: () => true,
|
||||
|
||||
// Users can update self, admins can update anyone
|
||||
update: ({ req: { user }, id }) => {
|
||||
if (!user) return false
|
||||
if (user.roles?.includes('admin')) return true
|
||||
return user.id === id
|
||||
},
|
||||
|
||||
// Only admins can delete
|
||||
delete: ({ req: { user } }) => user?.roles?.includes('admin') || false,
|
||||
},
|
||||
fields: [
|
||||
{ name: 'name', type: 'text', required: true },
|
||||
{ name: 'email', type: 'email', required: true },
|
||||
{
|
||||
name: 'roles',
|
||||
type: 'select',
|
||||
hasMany: true,
|
||||
options: ['admin', 'editor', 'user'],
|
||||
access: {
|
||||
// Only admins can read/update roles
|
||||
read: ({ req: { user } }) => user?.roles?.includes('admin') || false,
|
||||
update: ({ req: { user } }) => user?.roles?.includes('admin') || false,
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
**Source**: `templates/website/src/collections/Users/index.ts`
|
||||
|
||||
## Debugging Tips
|
||||
|
||||
### Log Access Check Execution
|
||||
|
||||
```ts
|
||||
export const debugAccess: Access = ({ req: { user }, id }) => {
|
||||
console.log('Access check:', {
|
||||
userId: user?.id,
|
||||
userRoles: user?.roles,
|
||||
docId: id,
|
||||
timestamp: new Date().toISOString(),
|
||||
})
|
||||
return true
|
||||
}
|
||||
```
|
||||
|
||||
### Verify Arguments Availability
|
||||
|
||||
```ts
|
||||
export const checkArgsAccess: Access = (args) => {
|
||||
console.log('Available arguments:', {
|
||||
hasReq: 'req' in args,
|
||||
hasUser: args.req?.user ? 'yes' : 'no',
|
||||
hasId: args.id ? 'provided' : 'undefined',
|
||||
hasData: args.data ? 'provided' : 'undefined',
|
||||
})
|
||||
return true
|
||||
}
|
||||
```
|
||||
|
||||
### Measure Async Operation Timing
|
||||
|
||||
```ts
|
||||
export const timedAsyncAccess: Access = async ({ req }) => {
|
||||
const start = Date.now()
|
||||
|
||||
const result = await fetch('https://auth-service.example.com/validate', {
|
||||
headers: { userId: req.user?.id },
|
||||
})
|
||||
|
||||
console.log(`Access check took ${Date.now() - start}ms`)
|
||||
|
||||
return result.ok
|
||||
}
|
||||
```
|
||||
|
||||
### Test Access Without User
|
||||
|
||||
```ts
|
||||
// In test/development
|
||||
const testAccess = await payload.find({
|
||||
collection: 'posts',
|
||||
overrideAccess: false, // Enforce access control
|
||||
user: undefined, // Simulate no user
|
||||
})
|
||||
|
||||
console.log('Public access result:', testAccess.docs.length)
|
||||
```
|
||||
|
||||
**Source**: Synthesized (debugging best practices)
|
||||
|
||||
## Performance Considerations
|
||||
|
||||
### Async Operations Impact
|
||||
|
||||
```ts
|
||||
// ❌ Slow: Multiple sequential async calls
|
||||
export const slowAccess: Access = async ({ req: { user } }) => {
|
||||
const org = await req.payload.findByID({ collection: 'orgs', id: user.orgId })
|
||||
const team = await req.payload.findByID({ collection: 'teams', id: user.teamId })
|
||||
const subscription = await req.payload.findByID({ collection: 'subs', id: user.subId })
|
||||
|
||||
return org.active && team.active && subscription.active
|
||||
}
|
||||
|
||||
// ✅ Fast: Use query constraints or cache in context
|
||||
export const fastAccess: Access = ({ req: { user, context } }) => {
|
||||
// Cache expensive lookups
|
||||
if (!context.orgStatus) {
|
||||
context.orgStatus = checkOrgStatus(user.orgId)
|
||||
}
|
||||
|
||||
return context.orgStatus
|
||||
}
|
||||
```
|
||||
|
||||
### Query Constraint Optimization
|
||||
|
||||
```ts
|
||||
// ❌ Avoid: Non-indexed fields in constraints
|
||||
export const slowQuery: Access = () => ({
|
||||
'metadata.internalCode': { equals: 'ABC123' }, // Slow if not indexed
|
||||
})
|
||||
|
||||
// ✅ Better: Use indexed fields
|
||||
export const fastQuery: Access = () => ({
|
||||
status: { equals: 'active' }, // Indexed field
|
||||
organizationId: { in: ['org1', 'org2'] }, // Indexed field
|
||||
})
|
||||
```
|
||||
|
||||
### Field Access on Large Arrays
|
||||
|
||||
```ts
|
||||
// ❌ Slow: Complex access on array fields
|
||||
const arrayField: ArrayField = {
|
||||
name: 'items',
|
||||
type: 'array',
|
||||
fields: [
|
||||
{
|
||||
name: 'secretData',
|
||||
type: 'text',
|
||||
access: {
|
||||
read: async ({ req }) => {
|
||||
// Async call runs for EVERY array item
|
||||
const result = await expensiveCheck()
|
||||
return result
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
// ✅ Fast: Simple checks or cache result
|
||||
const optimizedArrayField: ArrayField = {
|
||||
name: 'items',
|
||||
type: 'array',
|
||||
fields: [
|
||||
{
|
||||
name: 'secretData',
|
||||
type: 'text',
|
||||
access: {
|
||||
read: ({ req: { user }, context }) => {
|
||||
// Cache once, reuse for all items
|
||||
if (context.canReadSecret === undefined) {
|
||||
context.canReadSecret = user?.roles?.includes('admin')
|
||||
}
|
||||
return context.canReadSecret
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
### Avoid N+1 Queries
|
||||
|
||||
```ts
|
||||
// ❌ N+1 Problem: Query per access check
|
||||
export const n1Access: Access = async ({ req, id }) => {
|
||||
// Runs for EACH document in list
|
||||
const doc = await req.payload.findByID({ collection: 'docs', id })
|
||||
return doc.isPublic
|
||||
}
|
||||
|
||||
// ✅ Better: Use query constraint to filter at DB level
|
||||
export const efficientAccess: Access = () => {
|
||||
return { isPublic: { equals: true } }
|
||||
}
|
||||
```
|
||||
|
||||
**Performance Best Practices:**
|
||||
|
||||
1. **Minimize Async Operations**: Use query constraints over async lookups when possible
|
||||
2. **Cache Expensive Checks**: Store results in `req.context` for reuse
|
||||
3. **Index Query Fields**: Ensure fields in query constraints are indexed
|
||||
4. **Avoid Complex Logic in Array Fields**: Simple boolean checks preferred
|
||||
5. **Use Query Constraints**: Let database filter rather than loading all records
|
||||
|
||||
**Source**: Synthesized (operational best practices)
|
||||
|
||||
## Enhanced Best Practices
|
||||
|
||||
Comprehensive security and implementation guidelines:
|
||||
|
||||
1. **Default Deny**: Start with restrictive access, gradually add permissions
|
||||
2. **Type Guards**: Use TypeScript for user type safety and better IDE support
|
||||
3. **Validate Data**: Never trust frontend-provided IDs or data
|
||||
4. **Async for Critical Checks**: Use async operations for important security decisions
|
||||
5. **Consistent Logic**: Apply same rules at field and collection levels
|
||||
6. **Test Edge Cases**: Test with no user, wrong user, admin user scenarios
|
||||
7. **Monitor Access**: Log failed access attempts for security review
|
||||
8. **Regular Audit**: Review access rules quarterly or after major changes
|
||||
9. **Cache Wisely**: Use `req.context` for expensive operations
|
||||
10. **Document Intent**: Add comments explaining complex access rules
|
||||
11. **Avoid Secrets in Client**: Never expose sensitive logic to client-side
|
||||
12. **Rate Limit External Calls**: Protect against DoS on external validation services
|
||||
13. **Handle Errors Gracefully**: Access functions should return `false` on error, not throw
|
||||
14. **Use Environment Vars**: Store configuration (IPs, API keys) in env vars
|
||||
15. **Test Local API**: Remember to set `overrideAccess: false` when testing
|
||||
16. **Consider Performance**: Measure impact of async operations on login time
|
||||
17. **Version Control**: Track access control changes in git history
|
||||
18. **Principle of Least Privilege**: Grant minimum access required for functionality
|
||||
|
||||
**Sources**: `docs/access-control/*.mdx`, synthesized best practices
|
||||
@@ -0,0 +1,697 @@
|
||||
# Payload CMS Access Control Reference
|
||||
|
||||
Complete reference for access control patterns across collections, fields, and globals.
|
||||
|
||||
## At a Glance
|
||||
|
||||
| Feature | Scope | Returns | Use Case |
|
||||
| --------------------- | --------------------------------------------------------- | ---------------------- | ---------------------------------- |
|
||||
| **Collection Access** | create, read, update, delete, admin, unlock, readVersions | boolean \| Where query | Document-level permissions |
|
||||
| **Field Access** | create, read, update | boolean only | Field-level visibility/editability |
|
||||
| **Global Access** | read, update, readVersions | boolean \| Where query | Global document permissions |
|
||||
|
||||
## Three Layers of Access Control
|
||||
|
||||
Payload provides three distinct access control layers:
|
||||
|
||||
1. **Collection-Level**: Controls operations on entire documents (create, read, update, delete, admin, unlock, readVersions)
|
||||
2. **Field-Level**: Controls access to individual fields (create, read, update)
|
||||
3. **Global-Level**: Controls access to global documents (read, update, readVersions)
|
||||
|
||||
## Return Value Types
|
||||
|
||||
Access control functions can return:
|
||||
|
||||
- **Boolean**: `true` (allow) or `false` (deny)
|
||||
- **Query Constraint**: `Where` object for row-level security (collection-level only)
|
||||
|
||||
Field-level access does NOT support query constraints - only boolean returns.
|
||||
|
||||
## Operation Decision Tree
|
||||
|
||||
```txt
|
||||
User makes request
|
||||
│
|
||||
├─ Collection access check
|
||||
│ ├─ Returns false? → Deny entire operation
|
||||
│ ├─ Returns true? → Continue
|
||||
│ └─ Returns Where? → Apply query constraint
|
||||
│
|
||||
├─ Field access check (if applicable)
|
||||
│ ├─ Returns false? → Field omitted from result
|
||||
│ └─ Returns true? → Include field
|
||||
│
|
||||
└─ Operation completed
|
||||
```
|
||||
|
||||
## Collection Access Control
|
||||
|
||||
### Basic Patterns
|
||||
|
||||
```ts
|
||||
import type { CollectionConfig, Access } from 'payload'
|
||||
|
||||
export const Posts: CollectionConfig = {
|
||||
slug: 'posts',
|
||||
access: {
|
||||
// Boolean: Only authenticated users can create
|
||||
create: ({ req: { user } }) => Boolean(user),
|
||||
|
||||
// Query constraint: Public sees published, users see all
|
||||
read: ({ req: { user } }) => {
|
||||
if (user) return true
|
||||
return { status: { equals: 'published' } }
|
||||
},
|
||||
|
||||
// User-specific: Admins or document owner
|
||||
update: ({ req: { user }, id }) => {
|
||||
if (user?.roles?.includes('admin')) return true
|
||||
return { author: { equals: user?.id } }
|
||||
},
|
||||
|
||||
// Async: Check related data
|
||||
delete: async ({ req, id }) => {
|
||||
const hasComments = await req.payload.count({
|
||||
collection: 'comments',
|
||||
where: { post: { equals: id } },
|
||||
})
|
||||
return hasComments === 0
|
||||
},
|
||||
|
||||
// Admin panel visibility
|
||||
admin: ({ req: { user } }) => {
|
||||
return user?.roles?.includes('admin') || user?.roles?.includes('editor')
|
||||
},
|
||||
},
|
||||
fields: [
|
||||
{ name: 'title', type: 'text' },
|
||||
{ name: 'status', type: 'select', options: ['draft', 'published'] },
|
||||
{ name: 'author', type: 'relationship', relationTo: 'users' },
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
### Role-Based Access Control (RBAC) Pattern
|
||||
|
||||
Payload does NOT provide a roles system by default. The following is a commonly accepted pattern for implementing role-based access control in auth collections:
|
||||
|
||||
```ts
|
||||
import type { CollectionConfig } from 'payload'
|
||||
|
||||
export const Users: CollectionConfig = {
|
||||
slug: 'users',
|
||||
auth: true,
|
||||
fields: [
|
||||
{ name: 'name', type: 'text', required: true },
|
||||
{ name: 'email', type: 'email', required: true },
|
||||
{
|
||||
name: 'roles',
|
||||
type: 'select',
|
||||
hasMany: true,
|
||||
options: ['admin', 'editor', 'user'],
|
||||
defaultValue: ['user'],
|
||||
required: true,
|
||||
// Save roles to JWT for access control without database lookups
|
||||
saveToJWT: true,
|
||||
access: {
|
||||
// Only admins can update roles
|
||||
update: ({ req: { user } }) => user?.roles?.includes('admin'),
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
**Important Notes:**
|
||||
|
||||
1. **Not Built-In**: Payload does not provide a roles system out of the box. You must add a `roles` field to your auth collection.
|
||||
2. **Save to JWT**: Use `saveToJWT: true` to include roles in the JWT token, enabling role checks without database queries.
|
||||
3. **Default Value**: Set a `defaultValue` to automatically assign new users a default role.
|
||||
4. **Access Control**: Restrict who can modify roles (typically only admins).
|
||||
5. **Role Options**: Define your own role hierarchy based on your application needs.
|
||||
|
||||
**Using Roles in Access Control:**
|
||||
|
||||
```ts
|
||||
import type { Access } from 'payload'
|
||||
|
||||
// Check for specific role
|
||||
export const adminOnly: Access = ({ req: { user } }) => {
|
||||
return user?.roles?.includes('admin')
|
||||
}
|
||||
|
||||
// Check for multiple roles
|
||||
export const adminOrEditor: Access = ({ req: { user } }) => {
|
||||
return Boolean(user?.roles?.some((role) => ['admin', 'editor'].includes(role)))
|
||||
}
|
||||
|
||||
// Role hierarchy check
|
||||
export const hasMinimumRole: Access = ({ req: { user } }, minRole: string) => {
|
||||
const roleHierarchy = ['user', 'editor', 'admin']
|
||||
const userHighestRole = Math.max(...(user?.roles?.map((r) => roleHierarchy.indexOf(r)) || [-1]))
|
||||
const requiredRoleIndex = roleHierarchy.indexOf(minRole)
|
||||
|
||||
return userHighestRole >= requiredRoleIndex
|
||||
}
|
||||
```
|
||||
|
||||
### Reusable Access Functions
|
||||
|
||||
```ts
|
||||
import type { Access } from 'payload'
|
||||
|
||||
// Anyone (public)
|
||||
export const anyone: Access = () => true
|
||||
|
||||
// Authenticated only
|
||||
export const authenticated: Access = ({ req: { user } }) => Boolean(user)
|
||||
|
||||
// Authenticated or published content
|
||||
export const authenticatedOrPublished: Access = ({ req: { user } }) => {
|
||||
if (user) return true
|
||||
return { _status: { equals: 'published' } }
|
||||
}
|
||||
|
||||
// Admin only
|
||||
export const admins: Access = ({ req: { user } }) => {
|
||||
return user?.roles?.includes('admin')
|
||||
}
|
||||
|
||||
// Admin or editor
|
||||
export const adminsOrEditors: Access = ({ req: { user } }) => {
|
||||
return Boolean(user?.roles?.some((role) => ['admin', 'editor'].includes(role)))
|
||||
}
|
||||
|
||||
// Self or admin
|
||||
export const adminsOrSelf: Access = ({ req: { user } }) => {
|
||||
if (user?.roles?.includes('admin')) return true
|
||||
return { id: { equals: user?.id } }
|
||||
}
|
||||
|
||||
// Usage
|
||||
export const Posts: CollectionConfig = {
|
||||
slug: 'posts',
|
||||
access: {
|
||||
create: authenticated,
|
||||
read: authenticatedOrPublished,
|
||||
update: adminsOrEditors,
|
||||
delete: admins,
|
||||
},
|
||||
fields: [{ name: 'title', type: 'text' }],
|
||||
}
|
||||
```
|
||||
|
||||
### Row-Level Security with Complex Queries
|
||||
|
||||
```ts
|
||||
import type { Access } from 'payload'
|
||||
|
||||
// Organization-scoped access
|
||||
export const organizationScoped: Access = ({ req: { user } }) => {
|
||||
if (user?.roles?.includes('admin')) return true
|
||||
|
||||
// Users see only their organization's data
|
||||
return {
|
||||
organization: {
|
||||
equals: user?.organization,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Multiple conditions with AND
|
||||
export const complexAccess: Access = ({ req: { user } }) => {
|
||||
return {
|
||||
and: [
|
||||
{ status: { equals: 'published' } },
|
||||
{ 'author.isActive': { equals: true } },
|
||||
{
|
||||
or: [{ visibility: { equals: 'public' } }, { author: { equals: user?.id } }],
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
// Team-based access
|
||||
export const teamMemberAccess: Access = ({ req: { user } }) => {
|
||||
if (!user) return false
|
||||
if (user.roles?.includes('admin')) return true
|
||||
|
||||
return {
|
||||
'team.members': {
|
||||
contains: user.id,
|
||||
},
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Header-Based Access (API Keys)
|
||||
|
||||
```ts
|
||||
import type { Access } from 'payload'
|
||||
|
||||
export const apiKeyAccess: Access = ({ req }) => {
|
||||
const apiKey = req.headers.get('x-api-key')
|
||||
|
||||
if (!apiKey) return false
|
||||
|
||||
// Validate against stored keys
|
||||
return apiKey === process.env.VALID_API_KEY
|
||||
}
|
||||
|
||||
// Bearer token validation
|
||||
export const bearerTokenAccess: Access = async ({ req }) => {
|
||||
const auth = req.headers.get('authorization')
|
||||
|
||||
if (!auth?.startsWith('Bearer ')) return false
|
||||
|
||||
const token = auth.slice(7)
|
||||
const isValid = await validateToken(token)
|
||||
|
||||
return isValid
|
||||
}
|
||||
```
|
||||
|
||||
## Field Access Control
|
||||
|
||||
Field access does NOT support query constraints - only boolean returns.
|
||||
|
||||
### Basic Field Access
|
||||
|
||||
```ts
|
||||
import type { NumberField, FieldAccess } from 'payload'
|
||||
|
||||
const salaryReadAccess: FieldAccess = ({ req: { user }, doc }) => {
|
||||
// Self can read own salary
|
||||
if (user?.id === doc?.id) return true
|
||||
// Admin can read all salaries
|
||||
return user?.roles?.includes('admin')
|
||||
}
|
||||
|
||||
const salaryUpdateAccess: FieldAccess = ({ req: { user } }) => {
|
||||
// Only admins can update salary
|
||||
return user?.roles?.includes('admin')
|
||||
}
|
||||
|
||||
const salaryField: NumberField = {
|
||||
name: 'salary',
|
||||
type: 'number',
|
||||
access: {
|
||||
read: salaryReadAccess,
|
||||
update: salaryUpdateAccess,
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Sibling Data Access
|
||||
|
||||
```ts
|
||||
import type { ArrayField, FieldAccess } from 'payload'
|
||||
|
||||
const contentReadAccess: FieldAccess = ({ req: { user }, siblingData }) => {
|
||||
// Authenticated users see all
|
||||
if (user) return true
|
||||
// Public sees only if marked public
|
||||
return siblingData?.isPublic === true
|
||||
}
|
||||
|
||||
const arrayField: ArrayField = {
|
||||
name: 'sections',
|
||||
type: 'array',
|
||||
fields: [
|
||||
{
|
||||
name: 'isPublic',
|
||||
type: 'checkbox',
|
||||
defaultValue: false,
|
||||
},
|
||||
{
|
||||
name: 'content',
|
||||
type: 'text',
|
||||
access: {
|
||||
read: contentReadAccess,
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
### Nested Field Access
|
||||
|
||||
```ts
|
||||
import type { GroupField, FieldAccess } from 'payload'
|
||||
|
||||
const internalOnlyAccess: FieldAccess = ({ req: { user } }) => {
|
||||
return user?.roles?.includes('admin') || user?.roles?.includes('internal')
|
||||
}
|
||||
|
||||
const groupField: GroupField = {
|
||||
name: 'internalMetadata',
|
||||
type: 'group',
|
||||
access: {
|
||||
read: internalOnlyAccess,
|
||||
update: internalOnlyAccess,
|
||||
},
|
||||
fields: [
|
||||
{ name: 'internalNotes', type: 'textarea' },
|
||||
{ name: 'priority', type: 'select', options: ['low', 'medium', 'high'] },
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
### Hiding Admin Fields
|
||||
|
||||
```ts
|
||||
import type { CollectionConfig } from 'payload'
|
||||
|
||||
export const Users: CollectionConfig = {
|
||||
slug: 'users',
|
||||
auth: true,
|
||||
fields: [
|
||||
{ name: 'name', type: 'text', required: true },
|
||||
{ name: 'email', type: 'email', required: true },
|
||||
{
|
||||
name: 'roles',
|
||||
type: 'select',
|
||||
hasMany: true,
|
||||
options: ['admin', 'editor', 'user'],
|
||||
access: {
|
||||
// Hide from UI, but still saved/queried
|
||||
read: ({ req: { user } }) => user?.roles?.includes('admin'),
|
||||
// Only admins can update roles
|
||||
update: ({ req: { user } }) => user?.roles?.includes('admin'),
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
## Global Access Control
|
||||
|
||||
```ts
|
||||
import type { GlobalConfig, Access } from 'payload'
|
||||
|
||||
const adminOnly: Access = ({ req: { user } }) => {
|
||||
return user?.roles?.includes('admin')
|
||||
}
|
||||
|
||||
export const SiteSettings: GlobalConfig = {
|
||||
slug: 'site-settings',
|
||||
access: {
|
||||
read: () => true, // Anyone can read settings
|
||||
update: adminOnly, // Only admins can update
|
||||
readVersions: adminOnly, // Only admins can see version history
|
||||
},
|
||||
fields: [
|
||||
{ name: 'siteName', type: 'text' },
|
||||
{ name: 'maintenanceMode', type: 'checkbox' },
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
## Multi-Tenant Access Control
|
||||
|
||||
```ts
|
||||
import type { Access, CollectionConfig } from 'payload'
|
||||
|
||||
// Add tenant field to user type
|
||||
interface User {
|
||||
id: string
|
||||
tenantId: string
|
||||
roles?: string[]
|
||||
}
|
||||
|
||||
// Tenant-scoped access
|
||||
const tenantAccess: Access = ({ req: { user } }) => {
|
||||
// No user = no access
|
||||
if (!user) return false
|
||||
|
||||
// Super admin sees all
|
||||
if (user.roles?.includes('super-admin')) return true
|
||||
|
||||
// Users see only their tenant's data
|
||||
return {
|
||||
tenant: {
|
||||
equals: (user as User).tenantId,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export const Posts: CollectionConfig = {
|
||||
slug: 'posts',
|
||||
access: {
|
||||
create: tenantAccess,
|
||||
read: tenantAccess,
|
||||
update: tenantAccess,
|
||||
delete: tenantAccess,
|
||||
},
|
||||
fields: [
|
||||
{ name: 'title', type: 'text' },
|
||||
{
|
||||
name: 'tenant',
|
||||
type: 'text',
|
||||
required: true,
|
||||
access: {
|
||||
// Tenant field hidden from non-admins
|
||||
update: ({ req: { user } }) => user?.roles?.includes('super-admin'),
|
||||
},
|
||||
hooks: {
|
||||
// Auto-set tenant on create
|
||||
beforeChange: [
|
||||
({ req, operation, value }) => {
|
||||
if (operation === 'create' && !value) {
|
||||
return (req.user as User)?.tenantId
|
||||
}
|
||||
return value
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
## Auth Collection Patterns
|
||||
|
||||
### Self or Admin Pattern
|
||||
|
||||
```ts
|
||||
import type { CollectionConfig } from 'payload'
|
||||
|
||||
export const Users: CollectionConfig = {
|
||||
slug: 'users',
|
||||
auth: true,
|
||||
access: {
|
||||
// Anyone can read user profiles
|
||||
read: () => true,
|
||||
|
||||
// Users can update themselves, admins can update anyone
|
||||
update: ({ req: { user }, id }) => {
|
||||
if (user?.roles?.includes('admin')) return true
|
||||
return user?.id === id
|
||||
},
|
||||
|
||||
// Only admins can delete
|
||||
delete: ({ req: { user } }) => user?.roles?.includes('admin'),
|
||||
},
|
||||
fields: [
|
||||
{ name: 'name', type: 'text' },
|
||||
{ name: 'email', type: 'email' },
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
### Restrict Self-Updates
|
||||
|
||||
```ts
|
||||
import type { CollectionConfig, FieldAccess } from 'payload'
|
||||
|
||||
const preventSelfRoleChange: FieldAccess = ({ req: { user }, id }) => {
|
||||
// Admins can change anyone's roles
|
||||
if (user?.roles?.includes('admin')) return true
|
||||
// Users cannot change their own roles
|
||||
if (user?.id === id) return false
|
||||
return false
|
||||
}
|
||||
|
||||
export const Users: CollectionConfig = {
|
||||
slug: 'users',
|
||||
auth: true,
|
||||
fields: [
|
||||
{
|
||||
name: 'roles',
|
||||
type: 'select',
|
||||
hasMany: true,
|
||||
options: ['admin', 'editor', 'user'],
|
||||
access: {
|
||||
update: preventSelfRoleChange,
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
## Cross-Collection Validation
|
||||
|
||||
```ts
|
||||
import type { Access } from 'payload'
|
||||
|
||||
// Check if user is a project member before allowing access
|
||||
export const projectMemberAccess: Access = async ({ req, id }) => {
|
||||
const { user, payload } = req
|
||||
|
||||
if (!user) return false
|
||||
if (user.roles?.includes('admin')) return true
|
||||
|
||||
// Check if document exists and user is member
|
||||
const project = await payload.findByID({
|
||||
collection: 'projects',
|
||||
id: id as string,
|
||||
depth: 0,
|
||||
})
|
||||
|
||||
return project.members?.includes(user.id)
|
||||
}
|
||||
|
||||
// Prevent deletion if document has dependencies
|
||||
export const preventDeleteWithDependencies: Access = async ({ req, id }) => {
|
||||
const { payload } = req
|
||||
|
||||
const dependencyCount = await payload.count({
|
||||
collection: 'related-items',
|
||||
where: {
|
||||
parent: { equals: id },
|
||||
},
|
||||
})
|
||||
|
||||
return dependencyCount === 0
|
||||
}
|
||||
```
|
||||
|
||||
## Access Control Function Arguments
|
||||
|
||||
### Collection Create
|
||||
|
||||
```ts
|
||||
create: ({ req, data }) => boolean | Where
|
||||
|
||||
// req: PayloadRequest
|
||||
// - req.user: Authenticated user (if any)
|
||||
// - req.payload: Payload instance for queries
|
||||
// - req.headers: Request headers
|
||||
// - req.locale: Current locale
|
||||
// data: The data being created
|
||||
```
|
||||
|
||||
### Collection Read
|
||||
|
||||
```ts
|
||||
read: ({ req, id }) => boolean | Where
|
||||
|
||||
// req: PayloadRequest
|
||||
// id: Document ID being read
|
||||
// - undefined during Access Operation (login check)
|
||||
// - string when reading specific document
|
||||
```
|
||||
|
||||
### Collection Update
|
||||
|
||||
```ts
|
||||
update: ({ req, id, data }) => boolean | Where
|
||||
|
||||
// req: PayloadRequest
|
||||
// id: Document ID being updated
|
||||
// data: New values being applied
|
||||
```
|
||||
|
||||
### Collection Delete
|
||||
|
||||
```ts
|
||||
delete: ({ req, id }) => boolean | Where
|
||||
|
||||
// req: PayloadRequest
|
||||
// id: Document ID being deleted
|
||||
```
|
||||
|
||||
### Field Create
|
||||
|
||||
```ts
|
||||
access: {
|
||||
create: ({ req, data, siblingData }) => boolean
|
||||
}
|
||||
|
||||
// req: PayloadRequest
|
||||
// data: Full document data
|
||||
// siblingData: Adjacent field values at same level
|
||||
```
|
||||
|
||||
### Field Read
|
||||
|
||||
```ts
|
||||
access: {
|
||||
read: ({ req, id, doc, siblingData }) => boolean
|
||||
}
|
||||
|
||||
// req: PayloadRequest
|
||||
// id: Document ID
|
||||
// doc: Full document
|
||||
// siblingData: Adjacent field values
|
||||
```
|
||||
|
||||
### Field Update
|
||||
|
||||
```ts
|
||||
access: {
|
||||
update: ({ req, id, data, doc, siblingData }) => boolean
|
||||
}
|
||||
|
||||
// req: PayloadRequest
|
||||
// id: Document ID
|
||||
// data: New values
|
||||
// doc: Current document
|
||||
// siblingData: Adjacent field values
|
||||
```
|
||||
|
||||
## Important Notes
|
||||
|
||||
1. **Local API Default**: Access control is **skipped by default** in Local API (`overrideAccess: true`). When passing a `user` parameter, you almost always want to set `overrideAccess: false` to respect that user's permissions:
|
||||
|
||||
```ts
|
||||
// ❌ WRONG: Passes user but bypasses access control (default behavior)
|
||||
await payload.find({
|
||||
collection: 'posts',
|
||||
user: someUser, // User is ignored for access control!
|
||||
})
|
||||
|
||||
// ✅ CORRECT: Respects the user's permissions
|
||||
await payload.find({
|
||||
collection: 'posts',
|
||||
user: someUser,
|
||||
overrideAccess: false, // Required to enforce access control
|
||||
})
|
||||
```
|
||||
|
||||
**Why this matters**: If you pass `user` without `overrideAccess: false`, the operation runs with admin privileges regardless of the user's actual permissions. This is a common security mistake.
|
||||
|
||||
2. **Field Access Limitations**: Field-level access does NOT support query constraints - only boolean returns.
|
||||
|
||||
3. **Admin Panel Visibility**: The `admin` access control determines if a collection appears in the admin panel for a user.
|
||||
|
||||
4. **Access Before Hooks**: Access control executes BEFORE hooks run, so hooks cannot modify access behavior.
|
||||
|
||||
5. **Query Constraints**: Only collection-level `read` access supports query constraints. All other operations and field-level access require boolean returns.
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Reusable Functions**: Create named access functions for common patterns
|
||||
2. **Fail Secure**: Default to `false` for sensitive operations
|
||||
3. **Cache Checks**: Use `req.context` to cache expensive validation
|
||||
4. **Type Safety**: Type your user object for better IDE support
|
||||
5. **Test Thoroughly**: Write tests for complex access control logic
|
||||
6. **Document Intent**: Add comments explaining access rules
|
||||
7. **Audit Logs**: Track access control decisions for security review
|
||||
8. **Performance**: Avoid N+1 queries in access functions
|
||||
9. **Error Handling**: Access functions should not throw - return `false` instead
|
||||
10. **Tenant Hooks**: Auto-set tenant fields in `beforeChange` hooks
|
||||
|
||||
## Advanced Patterns
|
||||
|
||||
For advanced access control patterns including context-aware access, time-based restrictions, subscription-based access, factory functions, configuration templates, debugging tips, and performance optimization, see [ACCESS-CONTROL-ADVANCED.md](ACCESS-CONTROL-ADVANCED.md).
|
||||
@@ -0,0 +1,326 @@
|
||||
# Payload CMS Adapters Reference
|
||||
|
||||
Complete reference for database, storage, and email adapters.
|
||||
|
||||
## Database Adapters
|
||||
|
||||
### MongoDB
|
||||
|
||||
```ts
|
||||
import { mongooseAdapter } from '@payloadcms/db-mongodb'
|
||||
|
||||
export default buildConfig({
|
||||
db: mongooseAdapter({
|
||||
url: process.env.DATABASE_URL,
|
||||
}),
|
||||
})
|
||||
```
|
||||
|
||||
### Postgres
|
||||
|
||||
```ts
|
||||
import { postgresAdapter } from '@payloadcms/db-postgres'
|
||||
|
||||
export default buildConfig({
|
||||
db: postgresAdapter({
|
||||
pool: {
|
||||
connectionString: process.env.DATABASE_URL,
|
||||
},
|
||||
push: false, // Don't auto-push schema changes
|
||||
migrationDir: './migrations',
|
||||
}),
|
||||
})
|
||||
```
|
||||
|
||||
### SQLite
|
||||
|
||||
```ts
|
||||
import { sqliteAdapter } from '@payloadcms/db-sqlite'
|
||||
|
||||
export default buildConfig({
|
||||
db: sqliteAdapter({
|
||||
client: {
|
||||
url: 'file:./payload.db',
|
||||
},
|
||||
transactionOptions: {}, // Enable transactions (disabled by default)
|
||||
}),
|
||||
})
|
||||
```
|
||||
|
||||
## Transactions
|
||||
|
||||
Payload automatically uses transactions for all-or-nothing database operations. Pass `req` to include operations in the same transaction.
|
||||
|
||||
```ts
|
||||
import type { CollectionAfterChangeHook } from 'payload'
|
||||
|
||||
const afterChange: CollectionAfterChangeHook = async ({ req, doc }) => {
|
||||
// This will be part of the same transaction
|
||||
await req.payload.create({
|
||||
req, // Pass req to use same transaction
|
||||
collection: 'audit-log',
|
||||
data: { action: 'created', docId: doc.id },
|
||||
})
|
||||
}
|
||||
|
||||
// Manual transaction control
|
||||
const transactionID = await payload.db.beginTransaction()
|
||||
try {
|
||||
await payload.create({
|
||||
collection: 'orders',
|
||||
data: orderData,
|
||||
req: { transactionID },
|
||||
})
|
||||
await payload.update({
|
||||
collection: 'inventory',
|
||||
id: itemId,
|
||||
data: { stock: newStock },
|
||||
req: { transactionID },
|
||||
})
|
||||
await payload.db.commitTransaction(transactionID)
|
||||
} catch (error) {
|
||||
await payload.db.rollbackTransaction(transactionID)
|
||||
throw error
|
||||
}
|
||||
```
|
||||
|
||||
**Note**: MongoDB requires replicaset for transactions. SQLite requires `transactionOptions: {}` to enable.
|
||||
|
||||
### Threading req Through Operations
|
||||
|
||||
**Critical**: When performing nested operations in hooks, always pass `req` to maintain transaction context. Failing to do so breaks atomicity and can cause partial updates.
|
||||
|
||||
```ts
|
||||
import type { CollectionAfterChangeHook } from 'payload'
|
||||
|
||||
// ✅ CORRECT: Thread req through nested operations
|
||||
const resaveChildren: CollectionAfterChangeHook = async ({ collection, doc, req }) => {
|
||||
// Find children - pass req
|
||||
const children = await req.payload.find({
|
||||
collection: 'children',
|
||||
where: { parent: { equals: doc.id } },
|
||||
req, // Maintains transaction context
|
||||
})
|
||||
|
||||
// Update each child - pass req
|
||||
for (const child of children.docs) {
|
||||
await req.payload.update({
|
||||
id: child.id,
|
||||
collection: 'children',
|
||||
data: { updatedField: 'value' },
|
||||
req, // Same transaction as parent operation
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ❌ WRONG: Missing req breaks transaction
|
||||
const brokenHook: CollectionAfterChangeHook = async ({ collection, doc, req }) => {
|
||||
const children = await req.payload.find({
|
||||
collection: 'children',
|
||||
where: { parent: { equals: doc.id } },
|
||||
// Missing req - separate transaction or no transaction
|
||||
})
|
||||
|
||||
for (const child of children.docs) {
|
||||
await req.payload.update({
|
||||
id: child.id,
|
||||
collection: 'children',
|
||||
data: { updatedField: 'value' },
|
||||
// Missing req - if parent operation fails, these updates persist
|
||||
})
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Why This Matters:**
|
||||
|
||||
- **MongoDB (with replica sets)**: Creates atomic session across operations
|
||||
- **PostgreSQL**: All operations use same Drizzle transaction
|
||||
- **SQLite (with transactions enabled)**: Ensures rollback on errors
|
||||
- **Without req**: Each operation runs independently, breaking atomicity
|
||||
|
||||
**When req is Required:**
|
||||
|
||||
- All mutating operations in hooks (create, update, delete)
|
||||
- Operations that must succeed/fail together
|
||||
- When using MongoDB replica sets or Postgres
|
||||
- Any operation that relies on `req.context` or `req.user`
|
||||
|
||||
**When req is Optional:**
|
||||
|
||||
- Read-only lookups independent of current transaction
|
||||
- Operations with `disableTransaction: true`
|
||||
- Administrative operations with `overrideAccess: true`
|
||||
|
||||
## Storage Adapters
|
||||
|
||||
Available storage adapters:
|
||||
|
||||
- **@payloadcms/storage-s3** - AWS S3
|
||||
- **@payloadcms/storage-azure** - Azure Blob Storage
|
||||
- **@payloadcms/storage-gcs** - Google Cloud Storage
|
||||
- **@payloadcms/storage-r2** - Cloudflare R2
|
||||
- **@payloadcms/storage-vercel-blob** - Vercel Blob
|
||||
- **@payloadcms/storage-uploadthing** - Uploadthing
|
||||
|
||||
### AWS S3
|
||||
|
||||
```ts
|
||||
import { s3Storage } from '@payloadcms/storage-s3'
|
||||
|
||||
export default buildConfig({
|
||||
plugins: [
|
||||
s3Storage({
|
||||
collections: {
|
||||
media: true,
|
||||
},
|
||||
bucket: process.env.S3_BUCKET,
|
||||
config: {
|
||||
credentials: {
|
||||
accessKeyId: process.env.S3_ACCESS_KEY_ID,
|
||||
secretAccessKey: process.env.S3_SECRET_ACCESS_KEY,
|
||||
},
|
||||
region: process.env.S3_REGION,
|
||||
},
|
||||
}),
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
### Azure Blob Storage
|
||||
|
||||
```ts
|
||||
import { azureStorage } from '@payloadcms/storage-azure'
|
||||
|
||||
export default buildConfig({
|
||||
plugins: [
|
||||
azureStorage({
|
||||
collections: {
|
||||
media: true,
|
||||
},
|
||||
connectionString: process.env.AZURE_STORAGE_CONNECTION_STRING,
|
||||
containerName: process.env.AZURE_STORAGE_CONTAINER_NAME,
|
||||
}),
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
### Google Cloud Storage
|
||||
|
||||
```ts
|
||||
import { gcsStorage } from '@payloadcms/storage-gcs'
|
||||
|
||||
export default buildConfig({
|
||||
plugins: [
|
||||
gcsStorage({
|
||||
collections: {
|
||||
media: true,
|
||||
},
|
||||
bucket: process.env.GCS_BUCKET,
|
||||
options: {
|
||||
projectId: process.env.GCS_PROJECT_ID,
|
||||
credentials: JSON.parse(process.env.GCS_CREDENTIALS),
|
||||
},
|
||||
}),
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
### Cloudflare R2
|
||||
|
||||
```ts
|
||||
import { r2Storage } from '@payloadcms/storage-r2'
|
||||
|
||||
export default buildConfig({
|
||||
plugins: [
|
||||
r2Storage({
|
||||
collections: {
|
||||
media: true,
|
||||
},
|
||||
bucket: process.env.R2_BUCKET,
|
||||
config: {
|
||||
credentials: {
|
||||
accessKeyId: process.env.R2_ACCESS_KEY_ID,
|
||||
secretAccessKey: process.env.R2_SECRET_ACCESS_KEY,
|
||||
},
|
||||
region: 'auto',
|
||||
endpoint: process.env.R2_ENDPOINT,
|
||||
},
|
||||
}),
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
### Vercel Blob
|
||||
|
||||
```ts
|
||||
import { vercelBlobStorage } from '@payloadcms/storage-vercel-blob'
|
||||
|
||||
export default buildConfig({
|
||||
plugins: [
|
||||
vercelBlobStorage({
|
||||
collections: {
|
||||
media: true,
|
||||
},
|
||||
token: process.env.BLOB_READ_WRITE_TOKEN,
|
||||
}),
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
### Uploadthing
|
||||
|
||||
```ts
|
||||
import { uploadthingStorage } from '@payloadcms/storage-uploadthing'
|
||||
|
||||
export default buildConfig({
|
||||
plugins: [
|
||||
uploadthingStorage({
|
||||
collections: {
|
||||
media: true,
|
||||
},
|
||||
options: {
|
||||
token: process.env.UPLOADTHING_TOKEN,
|
||||
acl: 'public-read',
|
||||
},
|
||||
}),
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
## Email Adapters
|
||||
|
||||
### Nodemailer (SMTP)
|
||||
|
||||
```ts
|
||||
import { nodemailerAdapter } from '@payloadcms/email-nodemailer'
|
||||
|
||||
export default buildConfig({
|
||||
email: nodemailerAdapter({
|
||||
defaultFromAddress: 'noreply@example.com',
|
||||
defaultFromName: 'My App',
|
||||
transportOptions: {
|
||||
host: process.env.SMTP_HOST,
|
||||
port: 587,
|
||||
auth: {
|
||||
user: process.env.SMTP_USER,
|
||||
pass: process.env.SMTP_PASS,
|
||||
},
|
||||
},
|
||||
}),
|
||||
})
|
||||
```
|
||||
|
||||
### Resend
|
||||
|
||||
```ts
|
||||
import { resendAdapter } from '@payloadcms/email-resend'
|
||||
|
||||
export default buildConfig({
|
||||
email: resendAdapter({
|
||||
defaultFromAddress: 'noreply@example.com',
|
||||
defaultFromName: 'My App',
|
||||
apiKey: process.env.RESEND_API_KEY,
|
||||
}),
|
||||
})
|
||||
```
|
||||
@@ -0,0 +1,386 @@
|
||||
# Payload CMS Advanced Features
|
||||
|
||||
Complete reference for authentication, jobs, custom endpoints, components, plugins, and localization.
|
||||
|
||||
## Authentication
|
||||
|
||||
### Login
|
||||
|
||||
```ts
|
||||
// REST API
|
||||
const response = await fetch('/api/users/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
email: 'user@example.com',
|
||||
password: 'password',
|
||||
}),
|
||||
})
|
||||
|
||||
// Local API
|
||||
const result = await payload.login({
|
||||
collection: 'users',
|
||||
data: {
|
||||
email: 'user@example.com',
|
||||
password: 'password',
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
### Forgot Password
|
||||
|
||||
```ts
|
||||
await payload.forgotPassword({
|
||||
collection: 'users',
|
||||
data: {
|
||||
email: 'user@example.com',
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
### Custom Strategy
|
||||
|
||||
```ts
|
||||
import type { CollectionConfig, Strategy } from 'payload'
|
||||
|
||||
const customStrategy: Strategy = {
|
||||
name: 'custom',
|
||||
authenticate: async ({ payload, headers }) => {
|
||||
const token = headers.get('authorization')?.split(' ')[1]
|
||||
if (!token) return { user: null }
|
||||
|
||||
const user = await verifyToken(token)
|
||||
return { user }
|
||||
},
|
||||
}
|
||||
|
||||
export const Users: CollectionConfig = {
|
||||
slug: 'users',
|
||||
auth: {
|
||||
strategies: [customStrategy],
|
||||
},
|
||||
fields: [],
|
||||
}
|
||||
```
|
||||
|
||||
### API Keys
|
||||
|
||||
```ts
|
||||
import type { CollectionConfig } from 'payload'
|
||||
|
||||
export const APIKeys: CollectionConfig = {
|
||||
slug: 'api-keys',
|
||||
auth: {
|
||||
disableLocalStrategy: true,
|
||||
useAPIKey: true,
|
||||
},
|
||||
fields: [],
|
||||
}
|
||||
```
|
||||
|
||||
## Jobs Queue
|
||||
|
||||
Offload long-running or scheduled tasks to background workers.
|
||||
|
||||
### Tasks
|
||||
|
||||
```ts
|
||||
import { buildConfig } from 'payload'
|
||||
import type { TaskConfig } from 'payload'
|
||||
|
||||
export default buildConfig({
|
||||
jobs: {
|
||||
tasks: [
|
||||
{
|
||||
slug: 'sendWelcomeEmail',
|
||||
inputSchema: [
|
||||
{ name: 'userEmail', type: 'text', required: true },
|
||||
{ name: 'userName', type: 'text', required: true },
|
||||
],
|
||||
outputSchema: [{ name: 'emailSent', type: 'checkbox', required: true }],
|
||||
retries: 2, // Retry up to 2 times on failure
|
||||
handler: async ({ input, req }) => {
|
||||
await sendEmail({
|
||||
to: input.userEmail,
|
||||
subject: `Welcome ${input.userName}`,
|
||||
})
|
||||
return { output: { emailSent: true } }
|
||||
},
|
||||
} as TaskConfig<'sendWelcomeEmail'>,
|
||||
],
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
### Queueing Jobs
|
||||
|
||||
```ts
|
||||
// In a hook or endpoint
|
||||
await req.payload.jobs.queue({
|
||||
task: 'sendWelcomeEmail',
|
||||
input: {
|
||||
userEmail: 'user@example.com',
|
||||
userName: 'John',
|
||||
},
|
||||
waitUntil: new Date('2024-12-31'), // Optional: schedule for future
|
||||
})
|
||||
```
|
||||
|
||||
### Workflows
|
||||
|
||||
Multi-step jobs that run in sequence:
|
||||
|
||||
```ts
|
||||
{
|
||||
slug: 'onboardUser',
|
||||
inputSchema: [{ name: 'userId', type: 'text' }],
|
||||
handler: async ({ job, req }) => {
|
||||
const results = await job.runInlineTask({
|
||||
task: async ({ input }) => {
|
||||
// Step 1: Send welcome email
|
||||
await sendEmail(input.userId)
|
||||
return { output: { emailSent: true } }
|
||||
},
|
||||
})
|
||||
|
||||
await job.runInlineTask({
|
||||
task: async () => {
|
||||
// Step 2: Create onboarding tasks
|
||||
await createTasks()
|
||||
return { output: { tasksCreated: true } }
|
||||
},
|
||||
})
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
## Custom Endpoints
|
||||
|
||||
Add custom REST API routes to collections, globals, or root config. See [ENDPOINTS.md](ENDPOINTS.md) for detailed patterns, authentication, helpers, and real-world examples.
|
||||
|
||||
### Root Endpoints
|
||||
|
||||
```ts
|
||||
import { buildConfig } from 'payload'
|
||||
import type { Endpoint } from 'payload'
|
||||
|
||||
const helloEndpoint: Endpoint = {
|
||||
path: '/hello',
|
||||
method: 'get',
|
||||
handler: () => {
|
||||
return Response.json({ message: 'Hello!' })
|
||||
},
|
||||
}
|
||||
|
||||
const greetEndpoint: Endpoint = {
|
||||
path: '/greet/:name',
|
||||
method: 'get',
|
||||
handler: (req) => {
|
||||
return Response.json({
|
||||
message: `Hello ${req.routeParams.name}!`,
|
||||
})
|
||||
},
|
||||
}
|
||||
|
||||
export default buildConfig({
|
||||
endpoints: [helloEndpoint, greetEndpoint],
|
||||
collections: [],
|
||||
secret: process.env.PAYLOAD_SECRET || '',
|
||||
})
|
||||
```
|
||||
|
||||
### Collection Endpoints
|
||||
|
||||
```ts
|
||||
import type { CollectionConfig, Endpoint } from 'payload'
|
||||
|
||||
const featuredEndpoint: Endpoint = {
|
||||
path: '/featured',
|
||||
method: 'get',
|
||||
handler: async (req) => {
|
||||
const posts = await req.payload.find({
|
||||
collection: 'posts',
|
||||
where: { featured: { equals: true } },
|
||||
})
|
||||
return Response.json(posts)
|
||||
},
|
||||
}
|
||||
|
||||
export const Posts: CollectionConfig = {
|
||||
slug: 'posts',
|
||||
endpoints: [featuredEndpoint],
|
||||
fields: [
|
||||
{ name: 'title', type: 'text' },
|
||||
{ name: 'featured', type: 'checkbox' },
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
## Custom Components
|
||||
|
||||
### Field Component (Client)
|
||||
|
||||
```tsx
|
||||
'use client'
|
||||
import { useField } from '@payloadcms/ui'
|
||||
import type { TextFieldClientComponent } from 'payload'
|
||||
|
||||
export const CustomField: TextFieldClientComponent = () => {
|
||||
const { value, setValue } = useField()
|
||||
|
||||
return <input value={value || ''} onChange={(e) => setValue(e.target.value)} />
|
||||
}
|
||||
```
|
||||
|
||||
### Custom View
|
||||
|
||||
```tsx
|
||||
'use client'
|
||||
import { DefaultTemplate } from '@payloadcms/next/templates'
|
||||
|
||||
export const CustomView = () => {
|
||||
return (
|
||||
<DefaultTemplate>
|
||||
<h1>Custom Dashboard</h1>
|
||||
{/* Your content */}
|
||||
</DefaultTemplate>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Admin Config
|
||||
|
||||
```ts
|
||||
import { buildConfig } from 'payload'
|
||||
|
||||
export default buildConfig({
|
||||
admin: {
|
||||
components: {
|
||||
beforeDashboard: ['/components/BeforeDashboard'],
|
||||
beforeLogin: ['/components/BeforeLogin'],
|
||||
views: {
|
||||
custom: {
|
||||
Component: '/views/Custom',
|
||||
path: '/custom',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
collections: [],
|
||||
secret: process.env.PAYLOAD_SECRET || '',
|
||||
})
|
||||
```
|
||||
|
||||
## Plugins
|
||||
|
||||
### Available Plugins
|
||||
|
||||
- **@payloadcms/plugin-seo** - SEO fields with meta title/description, Open Graph, preview generation
|
||||
- **@payloadcms/plugin-redirects** - Manage URL redirects (301/302) for Next.js apps
|
||||
- **@payloadcms/plugin-nested-docs** - Hierarchical document structures with breadcrumbs
|
||||
- **@payloadcms/plugin-form-builder** - Dynamic form builder with submissions and validation
|
||||
- **@payloadcms/plugin-search** - Full-text search integration (Algolia support)
|
||||
- **@payloadcms/plugin-stripe** - Stripe payments, subscriptions, webhooks
|
||||
- **@payloadcms/plugin-ecommerce** - Complete ecommerce solution (products, variants, carts, orders)
|
||||
- **@payloadcms/plugin-import-export** - Import/export data via CSV
|
||||
- **@payloadcms/plugin-multi-tenant** - Multi-tenancy with tenant isolation
|
||||
- **@payloadcms/plugin-sentry** - Sentry error tracking integration
|
||||
- **@payloadcms/plugin-mcp** - Model Context Protocol for AI integrations
|
||||
|
||||
### Using Plugins
|
||||
|
||||
```ts
|
||||
import { buildConfig } from 'payload'
|
||||
import { seoPlugin } from '@payloadcms/plugin-seo'
|
||||
import { redirectsPlugin } from '@payloadcms/plugin-redirects'
|
||||
|
||||
export default buildConfig({
|
||||
plugins: [
|
||||
seoPlugin({
|
||||
collections: ['posts', 'pages'],
|
||||
}),
|
||||
redirectsPlugin({
|
||||
collections: ['pages'],
|
||||
}),
|
||||
],
|
||||
collections: [],
|
||||
secret: process.env.PAYLOAD_SECRET || '',
|
||||
})
|
||||
```
|
||||
|
||||
### Creating Plugins
|
||||
|
||||
```ts
|
||||
import type { Config } from 'payload'
|
||||
|
||||
interface PluginOptions {
|
||||
enabled?: boolean
|
||||
}
|
||||
|
||||
export const myPlugin =
|
||||
(options: PluginOptions) =>
|
||||
(config: Config): Config => ({
|
||||
...config,
|
||||
collections: [
|
||||
...(config.collections || []),
|
||||
{
|
||||
slug: 'plugin-collection',
|
||||
fields: [{ name: 'title', type: 'text' }],
|
||||
},
|
||||
],
|
||||
onInit: async (payload) => {
|
||||
if (config.onInit) await config.onInit(payload)
|
||||
// Plugin initialization
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
## Localization
|
||||
|
||||
```ts
|
||||
import { buildConfig } from 'payload'
|
||||
import type { Field, Payload } from 'payload'
|
||||
|
||||
export default buildConfig({
|
||||
localization: {
|
||||
locales: ['en', 'es', 'de'],
|
||||
defaultLocale: 'en',
|
||||
fallback: true,
|
||||
},
|
||||
collections: [],
|
||||
secret: process.env.PAYLOAD_SECRET || '',
|
||||
})
|
||||
|
||||
// Localized field
|
||||
const localizedField: TextField = {
|
||||
name: 'title',
|
||||
type: 'text',
|
||||
localized: true,
|
||||
}
|
||||
|
||||
// Query with locale
|
||||
const posts = await payload.find({
|
||||
collection: 'posts',
|
||||
locale: 'es',
|
||||
})
|
||||
```
|
||||
|
||||
## TypeScript Type References
|
||||
|
||||
For complete TypeScript type definitions and signatures, reference these files from the Payload source:
|
||||
|
||||
### Core Configuration Types
|
||||
|
||||
- **[All Commonly-Used Types](https://github.com/payloadcms/payload/blob/3.x/packages/payload/src/index.ts)** - Check here first for commonly used types and interfaces. All core types are exported from this file.
|
||||
|
||||
### Database & Adapters
|
||||
|
||||
- **[Database Adapter Types](https://github.com/payloadcms/payload/blob/3.x/packages/payload/src/database/types.ts)** - Base adapter interface
|
||||
- **[MongoDB Adapter](https://github.com/payloadcms/payload/blob/3.x/packages/db-mongodb/src/index.ts)** - MongoDB-specific options
|
||||
- **[Postgres Adapter](https://github.com/payloadcms/payload/blob/3.x/packages/db-postgres/src/index.ts)** - Postgres-specific options
|
||||
|
||||
### Rich Text & Plugins
|
||||
|
||||
- **[Lexical Types](https://github.com/payloadcms/payload/blob/3.x/packages/richtext-lexical/src/exports/server/index.ts)** - Lexical editor configuration
|
||||
|
||||
When users need detailed type information, fetch these URLs to provide complete signatures and optional parameters.
|
||||
@@ -0,0 +1,303 @@
|
||||
# Payload CMS Collections Reference
|
||||
|
||||
Complete reference for collection configurations and patterns.
|
||||
|
||||
## Basic Collection
|
||||
|
||||
```ts
|
||||
import type { CollectionConfig } from 'payload'
|
||||
|
||||
export const Posts: CollectionConfig = {
|
||||
slug: 'posts',
|
||||
labels: {
|
||||
singular: 'Post',
|
||||
plural: 'Posts',
|
||||
},
|
||||
admin: {
|
||||
useAsTitle: 'title',
|
||||
defaultColumns: ['title', 'author', 'status', 'createdAt'],
|
||||
group: 'Content', // Organize in admin sidebar
|
||||
description: 'Blog posts and articles',
|
||||
listSearchableFields: ['title', 'slug'],
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
name: 'title',
|
||||
type: 'text',
|
||||
required: true,
|
||||
index: true,
|
||||
},
|
||||
{
|
||||
name: 'slug',
|
||||
type: 'text',
|
||||
unique: true,
|
||||
index: true,
|
||||
admin: { position: 'sidebar' },
|
||||
},
|
||||
{
|
||||
name: 'status',
|
||||
type: 'select',
|
||||
options: ['draft', 'published'],
|
||||
defaultValue: 'draft',
|
||||
},
|
||||
],
|
||||
defaultSort: '-createdAt',
|
||||
timestamps: true,
|
||||
}
|
||||
```
|
||||
|
||||
## Auth Collection
|
||||
|
||||
```ts
|
||||
export const Users: CollectionConfig = {
|
||||
slug: 'users',
|
||||
auth: {
|
||||
tokenExpiration: 7200, // 2 hours
|
||||
verify: true,
|
||||
maxLoginAttempts: 5,
|
||||
lockTime: 600000, // 10 minutes
|
||||
useAPIKey: true,
|
||||
},
|
||||
admin: {
|
||||
useAsTitle: 'email',
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
name: 'roles',
|
||||
type: 'select',
|
||||
hasMany: true,
|
||||
options: ['admin', 'editor', 'user'],
|
||||
required: true,
|
||||
defaultValue: ['user'],
|
||||
saveToJWT: true,
|
||||
},
|
||||
{
|
||||
name: 'name',
|
||||
type: 'text',
|
||||
required: true,
|
||||
},
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
## Upload Collection
|
||||
|
||||
```ts
|
||||
export const Media: CollectionConfig = {
|
||||
slug: 'media',
|
||||
upload: {
|
||||
staticDir: 'media',
|
||||
mimeTypes: ['image/*'],
|
||||
imageSizes: [
|
||||
{
|
||||
name: 'thumbnail',
|
||||
width: 400,
|
||||
height: 300,
|
||||
position: 'centre',
|
||||
},
|
||||
{
|
||||
name: 'card',
|
||||
width: 768,
|
||||
height: 1024,
|
||||
},
|
||||
],
|
||||
adminThumbnail: 'thumbnail',
|
||||
focalPoint: true,
|
||||
crop: true,
|
||||
},
|
||||
access: {
|
||||
read: () => true,
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
name: 'alt',
|
||||
type: 'text',
|
||||
required: true,
|
||||
},
|
||||
{
|
||||
name: 'caption',
|
||||
type: 'text',
|
||||
localized: true,
|
||||
},
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
## Live Preview
|
||||
|
||||
Enable real-time content preview during editing.
|
||||
|
||||
```ts
|
||||
import type { CollectionConfig } from 'payload'
|
||||
|
||||
const generatePreviewPath = ({
|
||||
slug,
|
||||
collection,
|
||||
req,
|
||||
}: {
|
||||
slug: string
|
||||
collection: string
|
||||
req: any
|
||||
}) => {
|
||||
const baseUrl = process.env.NEXT_PUBLIC_SERVER_URL
|
||||
return `${baseUrl}/api/preview?slug=${slug}&collection=${collection}`
|
||||
}
|
||||
|
||||
export const Pages: CollectionConfig = {
|
||||
slug: 'pages',
|
||||
admin: {
|
||||
useAsTitle: 'title',
|
||||
// Live preview during editing
|
||||
livePreview: {
|
||||
url: ({ data, req }) =>
|
||||
generatePreviewPath({
|
||||
slug: data?.slug as string,
|
||||
collection: 'pages',
|
||||
req,
|
||||
}),
|
||||
},
|
||||
// Static preview button
|
||||
preview: (data, { req }) =>
|
||||
generatePreviewPath({
|
||||
slug: data?.slug as string,
|
||||
collection: 'pages',
|
||||
req,
|
||||
}),
|
||||
},
|
||||
fields: [
|
||||
{ name: 'title', type: 'text' },
|
||||
{ name: 'slug', type: 'text' },
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
## Versioning & Drafts
|
||||
|
||||
Payload maintains version history and supports draft/publish workflows.
|
||||
|
||||
```ts
|
||||
import type { CollectionConfig } from 'payload'
|
||||
|
||||
// Basic versioning (audit log only)
|
||||
export const Users: CollectionConfig = {
|
||||
slug: 'users',
|
||||
versions: true, // or { maxPerDoc: 100 }
|
||||
fields: [{ name: 'name', type: 'text' }],
|
||||
}
|
||||
|
||||
// Drafts enabled (draft/publish workflow)
|
||||
export const Posts: CollectionConfig = {
|
||||
slug: 'posts',
|
||||
versions: {
|
||||
drafts: true, // Enables _status field
|
||||
maxPerDoc: 50,
|
||||
},
|
||||
fields: [{ name: 'title', type: 'text' }],
|
||||
}
|
||||
|
||||
// Full configuration with autosave and scheduled publish
|
||||
export const Pages: CollectionConfig = {
|
||||
slug: 'pages',
|
||||
versions: {
|
||||
drafts: {
|
||||
autosave: true, // Auto-save while editing
|
||||
schedulePublish: true, // Schedule future publish/unpublish
|
||||
validate: false, // Don't validate drafts (default)
|
||||
},
|
||||
maxPerDoc: 100, // Keep last 100 versions (0 = unlimited)
|
||||
},
|
||||
fields: [{ name: 'title', type: 'text' }],
|
||||
}
|
||||
```
|
||||
|
||||
### Draft API Usage
|
||||
|
||||
```ts
|
||||
// Create draft
|
||||
await payload.create({
|
||||
collection: 'posts',
|
||||
data: { title: 'Draft Post' },
|
||||
draft: true, // Saves as draft, skips required field validation
|
||||
})
|
||||
|
||||
// Update as draft
|
||||
await payload.update({
|
||||
collection: 'posts',
|
||||
id: '123',
|
||||
data: { title: 'Updated Draft' },
|
||||
draft: true,
|
||||
})
|
||||
|
||||
// Read with drafts (returns newest draft if available)
|
||||
const post = await payload.findByID({
|
||||
collection: 'posts',
|
||||
id: '123',
|
||||
draft: true, // Returns draft version if exists
|
||||
})
|
||||
|
||||
// Query only published (REST API)
|
||||
// GET /api/posts (returns only _status: 'published')
|
||||
|
||||
// Access control for drafts
|
||||
export const Posts: CollectionConfig = {
|
||||
slug: 'posts',
|
||||
versions: { drafts: true },
|
||||
access: {
|
||||
read: ({ req: { user } }) => {
|
||||
// Public can only see published
|
||||
if (!user) return { _status: { equals: 'published' } }
|
||||
// Authenticated can see all
|
||||
return true
|
||||
},
|
||||
},
|
||||
fields: [{ name: 'title', type: 'text' }],
|
||||
}
|
||||
```
|
||||
|
||||
### Document Status
|
||||
|
||||
The `_status` field is auto-injected when drafts are enabled:
|
||||
|
||||
- `draft` - Never published
|
||||
- `published` - Published with no newer drafts
|
||||
- `changed` - Published but has newer unpublished drafts
|
||||
|
||||
## Globals
|
||||
|
||||
Globals are single-instance documents (not collections).
|
||||
|
||||
```ts
|
||||
import type { GlobalConfig } from 'payload'
|
||||
|
||||
export const Header: GlobalConfig = {
|
||||
slug: 'header',
|
||||
label: 'Header',
|
||||
admin: {
|
||||
group: 'Settings',
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
name: 'logo',
|
||||
type: 'upload',
|
||||
relationTo: 'media',
|
||||
required: true,
|
||||
},
|
||||
{
|
||||
name: 'nav',
|
||||
type: 'array',
|
||||
maxRows: 8,
|
||||
fields: [
|
||||
{
|
||||
name: 'link',
|
||||
type: 'relationship',
|
||||
relationTo: 'pages',
|
||||
},
|
||||
{
|
||||
name: 'label',
|
||||
type: 'text',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,634 @@
|
||||
# Payload Custom API Endpoints Reference
|
||||
|
||||
Custom REST API endpoints extend Payload's auto-generated CRUD operations with custom logic, authentication flows, webhooks, and integrations.
|
||||
|
||||
## Quick Reference
|
||||
|
||||
### Endpoint Configuration
|
||||
|
||||
| Property | Type | Description |
|
||||
| --------- | ------------------------------------------------- | --------------------------------------------------------------- |
|
||||
| `path` | `string` | Route path after collection/global slug (e.g., `/:id/tracking`) |
|
||||
| `method` | `'get' \| 'post' \| 'put' \| 'patch' \| 'delete'` | HTTP method (lowercase) |
|
||||
| `handler` | `(req: PayloadRequest) => Promise<Response>` | Async function returning Web API Response |
|
||||
| `custom` | `Record<string, any>` | Extension point for plugins/metadata |
|
||||
|
||||
### Request Context
|
||||
|
||||
| Property | Type | Description |
|
||||
| ----------------- | ----------------------- | ------------------------------------------------------ |
|
||||
| `req.user` | `User \| null` | Authenticated user (null if not authenticated) |
|
||||
| `req.payload` | `Payload` | Payload instance for operations (find, create...) |
|
||||
| `req.routeParams` | `Record<string, any>` | Path parameters (e.g., `:id`) |
|
||||
| `req.url` | `string` | Full request URL |
|
||||
| `req.method` | `string` | HTTP method |
|
||||
| `req.headers` | `Headers` | Request headers |
|
||||
| `req.json()` | `() => Promise<any>` | Parse JSON body |
|
||||
| `req.text()` | `() => Promise<string>` | Read body as text |
|
||||
| `req.data` | `any` | Parsed body (after `addDataAndFileToRequest()`) |
|
||||
| `req.file` | `File` | Uploaded file (after `addDataAndFileToRequest()`) |
|
||||
| `req.locale` | `string` | Request locale (after `addLocalesToRequestFromData()`) |
|
||||
| `req.i18n` | `I18n` | i18n instance |
|
||||
| `req.t` | `TFunction` | Translation function |
|
||||
|
||||
## Common Patterns
|
||||
|
||||
### Authentication Check
|
||||
|
||||
Custom endpoints are **not authenticated by default**. Check `req.user` to enforce authentication.
|
||||
|
||||
```ts
|
||||
import { APIError } from 'payload'
|
||||
|
||||
export const authenticatedEndpoint = {
|
||||
path: '/protected',
|
||||
method: 'get',
|
||||
handler: async (req) => {
|
||||
if (!req.user) {
|
||||
throw new APIError('Unauthorized', 401)
|
||||
}
|
||||
|
||||
// User is authenticated
|
||||
return Response.json({ message: 'Access granted' })
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Using Payload Operations
|
||||
|
||||
Use `req.payload` for database operations with access control and hooks.
|
||||
|
||||
```ts
|
||||
export const getRelatedPosts = {
|
||||
path: '/:id/related',
|
||||
method: 'get',
|
||||
handler: async (req) => {
|
||||
const { id } = req.routeParams
|
||||
|
||||
// Find related posts
|
||||
const posts = await req.payload.find({
|
||||
collection: 'posts',
|
||||
where: {
|
||||
category: {
|
||||
equals: id,
|
||||
},
|
||||
},
|
||||
limit: 5,
|
||||
sort: '-createdAt',
|
||||
})
|
||||
|
||||
return Response.json(posts)
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Route Parameters
|
||||
|
||||
Access path parameters via `req.routeParams`.
|
||||
|
||||
```ts
|
||||
export const getTrackingEndpoint = {
|
||||
path: '/:id/tracking',
|
||||
method: 'get',
|
||||
handler: async (req) => {
|
||||
const orderId = req.routeParams.id
|
||||
|
||||
const tracking = await getTrackingInfo(orderId)
|
||||
|
||||
if (!tracking) {
|
||||
return Response.json({ error: 'not found' }, { status: 404 })
|
||||
}
|
||||
|
||||
return Response.json(tracking)
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Request Body Handling
|
||||
|
||||
**Option 1: Manual JSON parsing**
|
||||
|
||||
```ts
|
||||
export const createEndpoint = {
|
||||
path: '/create',
|
||||
method: 'post',
|
||||
handler: async (req) => {
|
||||
const data = await req.json()
|
||||
|
||||
const result = await req.payload.create({
|
||||
collection: 'posts',
|
||||
data,
|
||||
})
|
||||
|
||||
return Response.json(result)
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
**Option 2: Using helper (handles JSON + files)**
|
||||
|
||||
```ts
|
||||
import { addDataAndFileToRequest } from 'payload'
|
||||
|
||||
export const uploadEndpoint = {
|
||||
path: '/upload',
|
||||
method: 'post',
|
||||
handler: async (req) => {
|
||||
await addDataAndFileToRequest(req)
|
||||
|
||||
// req.data now contains parsed body
|
||||
// req.file contains uploaded file (if multipart)
|
||||
|
||||
const result = await req.payload.create({
|
||||
collection: 'media',
|
||||
data: req.data,
|
||||
file: req.file,
|
||||
})
|
||||
|
||||
return Response.json(result)
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### CORS Headers
|
||||
|
||||
Use `headersWithCors` helper to apply config CORS settings.
|
||||
|
||||
```ts
|
||||
import { headersWithCors } from 'payload'
|
||||
|
||||
export const corsEndpoint = {
|
||||
path: '/public-data',
|
||||
method: 'get',
|
||||
handler: async (req) => {
|
||||
const data = await fetchPublicData()
|
||||
|
||||
return Response.json(data, {
|
||||
headers: headersWithCors({
|
||||
headers: new Headers(),
|
||||
req,
|
||||
}),
|
||||
})
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Error Handling
|
||||
|
||||
Throw `APIError` with status codes for proper error responses.
|
||||
|
||||
```ts
|
||||
import { APIError } from 'payload'
|
||||
|
||||
export const validateEndpoint = {
|
||||
path: '/validate',
|
||||
method: 'post',
|
||||
handler: async (req) => {
|
||||
const data = await req.json()
|
||||
|
||||
if (!data.email) {
|
||||
throw new APIError('Email is required', 400)
|
||||
}
|
||||
|
||||
// Validation passed
|
||||
return Response.json({ valid: true })
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Query Parameters
|
||||
|
||||
Extract query params from URL.
|
||||
|
||||
```ts
|
||||
export const searchEndpoint = {
|
||||
path: '/search',
|
||||
method: 'get',
|
||||
handler: async (req) => {
|
||||
const url = new URL(req.url)
|
||||
const query = url.searchParams.get('q')
|
||||
const limit = parseInt(url.searchParams.get('limit') || '10')
|
||||
|
||||
const results = await req.payload.find({
|
||||
collection: 'posts',
|
||||
where: {
|
||||
title: {
|
||||
contains: query,
|
||||
},
|
||||
},
|
||||
limit,
|
||||
})
|
||||
|
||||
return Response.json(results)
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
## Helper Functions
|
||||
|
||||
### addDataAndFileToRequest
|
||||
|
||||
Parses request body and attaches to `req.data` and `req.file`.
|
||||
|
||||
```ts
|
||||
import { addDataAndFileToRequest } from 'payload'
|
||||
|
||||
export const endpoint = {
|
||||
path: '/process',
|
||||
method: 'post',
|
||||
handler: async (req) => {
|
||||
await addDataAndFileToRequest(req)
|
||||
|
||||
// req.data: parsed JSON or form data
|
||||
// req.file: uploaded file (if multipart)
|
||||
|
||||
console.log(req.data) // { title: 'My Post' }
|
||||
console.log(req.file) // File object or undefined
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
**Handles:**
|
||||
|
||||
- JSON bodies (`Content-Type: application/json`)
|
||||
- Form data (`Content-Type: multipart/form-data`)
|
||||
- File uploads
|
||||
|
||||
### addLocalesToRequestFromData
|
||||
|
||||
Extracts locale from request data and validates against config.
|
||||
|
||||
```ts
|
||||
import { addLocalesToRequestFromData } from 'payload'
|
||||
|
||||
export const endpoint = {
|
||||
path: '/translate',
|
||||
method: 'post',
|
||||
handler: async (req) => {
|
||||
await addLocalesToRequestFromData(req)
|
||||
|
||||
// req.locale: validated locale string
|
||||
// req.fallbackLocale: fallback locale string
|
||||
|
||||
const result = await req.payload.find({
|
||||
collection: 'posts',
|
||||
locale: req.locale,
|
||||
})
|
||||
|
||||
return Response.json(result)
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### headersWithCors
|
||||
|
||||
Applies CORS headers from Payload config.
|
||||
|
||||
```ts
|
||||
import { headersWithCors } from 'payload'
|
||||
|
||||
export const endpoint = {
|
||||
path: '/data',
|
||||
method: 'get',
|
||||
handler: async (req) => {
|
||||
const data = { message: 'Hello' }
|
||||
|
||||
return Response.json(data, {
|
||||
headers: headersWithCors({
|
||||
headers: new Headers({
|
||||
'Cache-Control': 'public, max-age=3600',
|
||||
}),
|
||||
req,
|
||||
}),
|
||||
})
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
## Real-World Examples
|
||||
|
||||
### Multi-Tenant Login Endpoint
|
||||
|
||||
From `examples/multi-tenant`:
|
||||
|
||||
```ts
|
||||
import { APIError, generatePayloadCookie, headersWithCors } from 'payload'
|
||||
|
||||
export const externalUsersLogin = {
|
||||
path: '/login-external',
|
||||
method: 'post',
|
||||
handler: async (req) => {
|
||||
const { email, password, tenant } = await req.json()
|
||||
|
||||
if (!email || !password || !tenant) {
|
||||
throw new APIError('Missing credentials', 400)
|
||||
}
|
||||
|
||||
// Find user with tenant constraint
|
||||
const userQuery = await req.payload.find({
|
||||
collection: 'users',
|
||||
where: {
|
||||
and: [
|
||||
{ email: { equals: email } },
|
||||
{
|
||||
or: [{ tenants: { equals: tenant } }, { 'tenants.tenant': { equals: tenant } }],
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
|
||||
if (!userQuery.docs.length) {
|
||||
throw new APIError('Invalid credentials', 401)
|
||||
}
|
||||
|
||||
// Authenticate user
|
||||
const result = await req.payload.login({
|
||||
collection: 'users',
|
||||
data: { email, password },
|
||||
})
|
||||
|
||||
return Response.json(result, {
|
||||
headers: headersWithCors({
|
||||
headers: new Headers({
|
||||
'Set-Cookie': generatePayloadCookie({
|
||||
collectionAuthConfig: req.payload.config.collections.find((c) => c.slug === 'users')
|
||||
.auth,
|
||||
cookiePrefix: req.payload.config.cookiePrefix,
|
||||
token: result.token,
|
||||
}),
|
||||
}),
|
||||
req,
|
||||
}),
|
||||
})
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Webhook Handler (Stripe)
|
||||
|
||||
From `packages/plugin-ecommerce`:
|
||||
|
||||
```ts
|
||||
export const webhookEndpoint = {
|
||||
path: '/webhooks',
|
||||
method: 'post',
|
||||
handler: async (req) => {
|
||||
const body = await req.text()
|
||||
const signature = req.headers.get('stripe-signature')
|
||||
|
||||
try {
|
||||
const event = stripe.webhooks.constructEvent(body, signature, webhookSecret)
|
||||
|
||||
// Process event
|
||||
switch (event.type) {
|
||||
case 'payment_intent.succeeded':
|
||||
await handlePaymentSuccess(req.payload, event.data.object)
|
||||
break
|
||||
case 'payment_intent.failed':
|
||||
await handlePaymentFailure(req.payload, event.data.object)
|
||||
break
|
||||
}
|
||||
|
||||
return Response.json({ received: true })
|
||||
} catch (err) {
|
||||
req.payload.logger.error(`Webhook error: ${err.message}`)
|
||||
return Response.json({ error: err.message }, { status: 400 })
|
||||
}
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Data Preview Endpoint
|
||||
|
||||
From `packages/plugin-import-export`:
|
||||
|
||||
```ts
|
||||
import { addDataAndFileToRequest } from 'payload'
|
||||
|
||||
export const previewEndpoint = {
|
||||
path: '/preview',
|
||||
method: 'post',
|
||||
handler: async (req) => {
|
||||
if (!req.user) {
|
||||
throw new APIError('Unauthorized', 401)
|
||||
}
|
||||
|
||||
await addDataAndFileToRequest(req)
|
||||
|
||||
const { collection, where, limit = 10 } = req.data
|
||||
|
||||
// Validate collection exists
|
||||
const collectionConfig = req.payload.config.collections.find((c) => c.slug === collection)
|
||||
if (!collectionConfig) {
|
||||
throw new APIError('Collection not found', 404)
|
||||
}
|
||||
|
||||
// Preview data
|
||||
const results = await req.payload.find({
|
||||
collection,
|
||||
where,
|
||||
limit,
|
||||
depth: 0,
|
||||
})
|
||||
|
||||
return Response.json({
|
||||
docs: results.docs,
|
||||
totalDocs: results.totalDocs,
|
||||
fields: collectionConfig.fields,
|
||||
})
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Reindex Action Endpoint
|
||||
|
||||
From `packages/plugin-search`:
|
||||
|
||||
```ts
|
||||
export const reindexEndpoint = (pluginConfig) => ({
|
||||
path: '/reindex',
|
||||
method: 'post',
|
||||
handler: async (req) => {
|
||||
if (!req.user) {
|
||||
throw new APIError('Unauthorized', 401)
|
||||
}
|
||||
|
||||
const { collection } = req.routeParams
|
||||
|
||||
// Reindex collection
|
||||
const result = await reindexCollection(req.payload, collection, pluginConfig)
|
||||
|
||||
return Response.json({
|
||||
message: `Reindexed ${result.count} documents`,
|
||||
count: result.count,
|
||||
})
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
## Endpoint Placement
|
||||
|
||||
### Collection Endpoints
|
||||
|
||||
Mounted at `/api/{collection-slug}/{path}`.
|
||||
|
||||
```ts
|
||||
import type { CollectionConfig } from 'payload'
|
||||
|
||||
export const Orders: CollectionConfig = {
|
||||
slug: 'orders',
|
||||
fields: [
|
||||
/* ... */
|
||||
],
|
||||
endpoints: [
|
||||
{
|
||||
path: '/:id/tracking',
|
||||
method: 'get',
|
||||
handler: async (req) => {
|
||||
// Available at: /api/orders/:id/tracking
|
||||
const orderId = req.routeParams.id
|
||||
return Response.json({ orderId })
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
### Global Endpoints
|
||||
|
||||
Mounted at `/api/globals/{global-slug}/{path}`.
|
||||
|
||||
```ts
|
||||
import type { GlobalConfig } from 'payload'
|
||||
|
||||
export const Settings: GlobalConfig = {
|
||||
slug: 'settings',
|
||||
fields: [
|
||||
/* ... */
|
||||
],
|
||||
endpoints: [
|
||||
{
|
||||
path: '/clear-cache',
|
||||
method: 'post',
|
||||
handler: async (req) => {
|
||||
// Available at: /api/globals/settings/clear-cache
|
||||
await clearCache()
|
||||
return Response.json({ message: 'Cache cleared' })
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
## Advanced Patterns
|
||||
|
||||
### Factory Functions
|
||||
|
||||
Create reusable endpoint factories for plugins.
|
||||
|
||||
```ts
|
||||
export const createWebhookEndpoint = (config) => ({
|
||||
path: '/webhook',
|
||||
method: 'post',
|
||||
handler: async (req) => {
|
||||
const signature = req.headers.get('x-webhook-signature')
|
||||
|
||||
if (!verifySignature(signature, config.secret)) {
|
||||
throw new APIError('Invalid signature', 401)
|
||||
}
|
||||
|
||||
const data = await req.json()
|
||||
await processWebhook(req.payload, data, config)
|
||||
|
||||
return Response.json({ received: true })
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
### Conditional Endpoints
|
||||
|
||||
Add endpoints based on config options.
|
||||
|
||||
```ts
|
||||
export const MyCollection: CollectionConfig = {
|
||||
slug: 'posts',
|
||||
fields: [
|
||||
/* ... */
|
||||
],
|
||||
endpoints: [
|
||||
// Always included
|
||||
{
|
||||
path: '/public',
|
||||
method: 'get',
|
||||
handler: async (req) => Response.json({ data: [] }),
|
||||
},
|
||||
// Conditionally included
|
||||
...(process.env.ENABLE_ANALYTICS
|
||||
? [
|
||||
{
|
||||
path: '/analytics',
|
||||
method: 'get',
|
||||
handler: async (req) => Response.json({ analytics: [] }),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
### OpenAPI Documentation
|
||||
|
||||
Use `custom` property for API documentation metadata.
|
||||
|
||||
```ts
|
||||
export const endpoint = {
|
||||
path: '/search',
|
||||
method: 'get',
|
||||
handler: async (req) => {
|
||||
// Handler implementation
|
||||
},
|
||||
custom: {
|
||||
openapi: {
|
||||
summary: 'Search posts',
|
||||
parameters: [
|
||||
{
|
||||
name: 'q',
|
||||
in: 'query',
|
||||
required: true,
|
||||
schema: { type: 'string' },
|
||||
},
|
||||
],
|
||||
responses: {
|
||||
200: {
|
||||
description: 'Search results',
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: { type: 'array' },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Always check authentication** - Custom endpoints are not authenticated by default
|
||||
2. **Use `req.payload` for operations** - Ensures access control and hooks execute
|
||||
3. **Use helpers for common tasks** - `addDataAndFileToRequest`, `headersWithCors`, etc.
|
||||
4. **Throw `APIError` for errors** - Provides consistent error responses
|
||||
5. **Return Web API `Response`** - Use `Response.json()` for consistent responses
|
||||
6. **Validate input** - Check required fields, validate types
|
||||
7. **Handle CORS** - Use `headersWithCors` for cross-origin requests
|
||||
8. **Log errors** - Use `req.payload.logger` for debugging
|
||||
9. **Document with `custom`** - Add OpenAPI metadata for API docs
|
||||
10. **Factory pattern for reuse** - Create endpoint factories for plugins
|
||||
|
||||
## Resources
|
||||
|
||||
- REST API Overview: <https://payloadcms.com/docs/rest-api/overview>
|
||||
- Custom Endpoints: <https://payloadcms.com/docs/rest-api/overview#custom-endpoints>
|
||||
- Access Control: <https://payloadcms.com/docs/access-control/overview>
|
||||
- Local API: <https://payloadcms.com/docs/local-api/overview>
|
||||
@@ -0,0 +1,553 @@
|
||||
# Payload Field Type Guards Reference
|
||||
|
||||
Complete reference with detailed examples and patterns. See [FIELDS.md](FIELDS.md#field-type-guards) for quick reference table of all guards.
|
||||
|
||||
## Structural Guards
|
||||
|
||||
### fieldHasSubFields
|
||||
|
||||
Checks if field contains nested fields (group, array, row, or collapsible).
|
||||
|
||||
```ts
|
||||
import type { Field } from 'payload'
|
||||
import { fieldHasSubFields } from 'payload'
|
||||
|
||||
function traverseFields(fields: Field[]): void {
|
||||
fields.forEach((field) => {
|
||||
if (fieldHasSubFields(field)) {
|
||||
// Safe to access field.fields
|
||||
traverseFields(field.fields)
|
||||
}
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
**Signature:**
|
||||
|
||||
```ts
|
||||
fieldHasSubFields<TField extends ClientField | Field>(
|
||||
field: TField
|
||||
): field is TField & (FieldWithSubFieldsClient | FieldWithSubFields)
|
||||
```
|
||||
|
||||
**Common Pattern - Exclude Arrays:**
|
||||
|
||||
```ts
|
||||
if (fieldHasSubFields(field) && !fieldIsArrayType(field)) {
|
||||
// Groups, rows, collapsibles only (not arrays)
|
||||
}
|
||||
```
|
||||
|
||||
### fieldIsArrayType
|
||||
|
||||
Checks if field type is `'array'`.
|
||||
|
||||
```ts
|
||||
import { fieldIsArrayType } from 'payload'
|
||||
|
||||
if (fieldIsArrayType(field)) {
|
||||
// field.type === 'array'
|
||||
console.log(`Min rows: ${field.minRows}`)
|
||||
console.log(`Max rows: ${field.maxRows}`)
|
||||
}
|
||||
```
|
||||
|
||||
**Signature:**
|
||||
|
||||
```ts
|
||||
fieldIsArrayType<TField extends ClientField | Field>(
|
||||
field: TField
|
||||
): field is TField & (ArrayFieldClient | ArrayField)
|
||||
```
|
||||
|
||||
### fieldIsBlockType
|
||||
|
||||
Checks if field type is `'blocks'`.
|
||||
|
||||
```ts
|
||||
import { fieldIsBlockType } from 'payload'
|
||||
|
||||
if (fieldIsBlockType(field)) {
|
||||
// field.type === 'blocks'
|
||||
field.blocks.forEach((block) => {
|
||||
console.log(`Block: ${block.slug}`)
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
**Signature:**
|
||||
|
||||
```ts
|
||||
fieldIsBlockType<TField extends ClientField | Field>(
|
||||
field: TField
|
||||
): field is TField & (BlocksFieldClient | BlocksField)
|
||||
```
|
||||
|
||||
**Common Pattern - Distinguish Containers:**
|
||||
|
||||
```ts
|
||||
if (fieldIsArrayType(field)) {
|
||||
// Handle array rows
|
||||
} else if (fieldIsBlockType(field)) {
|
||||
// Handle block types
|
||||
}
|
||||
```
|
||||
|
||||
### fieldIsGroupType
|
||||
|
||||
Checks if field type is `'group'`.
|
||||
|
||||
```ts
|
||||
import { fieldIsGroupType } from 'payload'
|
||||
|
||||
if (fieldIsGroupType(field)) {
|
||||
// field.type === 'group'
|
||||
console.log(`Interface: ${field.interfaceName}`)
|
||||
}
|
||||
```
|
||||
|
||||
**Signature:**
|
||||
|
||||
```ts
|
||||
fieldIsGroupType<TField extends ClientField | Field>(
|
||||
field: TField
|
||||
): field is TField & (GroupFieldClient | GroupField)
|
||||
```
|
||||
|
||||
## Capability Guards
|
||||
|
||||
### fieldSupportsMany
|
||||
|
||||
Checks if field can have multiple values (select, relationship, or upload with `hasMany`).
|
||||
|
||||
```ts
|
||||
import { fieldSupportsMany } from 'payload'
|
||||
|
||||
if (fieldSupportsMany(field)) {
|
||||
// field.type is 'select' | 'relationship' | 'upload'
|
||||
// Safe to check field.hasMany
|
||||
if (field.hasMany) {
|
||||
console.log('Field accepts multiple values')
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Signature:**
|
||||
|
||||
```ts
|
||||
fieldSupportsMany<TField extends ClientField | Field>(
|
||||
field: TField
|
||||
): field is TField & (FieldWithManyClient | FieldWithMany)
|
||||
```
|
||||
|
||||
### fieldHasMaxDepth
|
||||
|
||||
Checks if field is relationship/upload/join with numeric `maxDepth` property.
|
||||
|
||||
```ts
|
||||
import { fieldHasMaxDepth } from 'payload'
|
||||
|
||||
if (fieldHasMaxDepth(field)) {
|
||||
// field.type is 'upload' | 'relationship' | 'join'
|
||||
// AND field.maxDepth is number
|
||||
const remainingDepth = field.maxDepth - currentDepth
|
||||
}
|
||||
```
|
||||
|
||||
**Signature:**
|
||||
|
||||
```ts
|
||||
fieldHasMaxDepth<TField extends ClientField | Field>(
|
||||
field: TField
|
||||
): field is TField & (FieldWithMaxDepthClient | FieldWithMaxDepth)
|
||||
```
|
||||
|
||||
### fieldShouldBeLocalized
|
||||
|
||||
Checks if field needs localization handling (accounts for parent localization).
|
||||
|
||||
```ts
|
||||
import { fieldShouldBeLocalized } from 'payload'
|
||||
|
||||
function processField(field: Field, parentIsLocalized: boolean) {
|
||||
if (fieldShouldBeLocalized({ field, parentIsLocalized })) {
|
||||
// Create locale-specific table or index
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Signature:**
|
||||
|
||||
```ts
|
||||
fieldShouldBeLocalized({
|
||||
field,
|
||||
parentIsLocalized,
|
||||
}: {
|
||||
field: ClientField | ClientTab | Field | Tab
|
||||
parentIsLocalized: boolean
|
||||
}): boolean
|
||||
```
|
||||
|
||||
```ts
|
||||
// Accounts for parent localization
|
||||
if (fieldShouldBeLocalized({ field, parentIsLocalized: false })) {
|
||||
/* ... */
|
||||
}
|
||||
```
|
||||
|
||||
### fieldIsVirtual
|
||||
|
||||
Checks if field is virtual (computed or virtual relationship).
|
||||
|
||||
```ts
|
||||
import { fieldIsVirtual } from 'payload'
|
||||
|
||||
if (fieldIsVirtual(field)) {
|
||||
// field.virtual is truthy
|
||||
if (typeof field.virtual === 'string') {
|
||||
// Virtual relationship path
|
||||
console.log(`Virtual path: ${field.virtual}`)
|
||||
} else {
|
||||
// Computed virtual field (uses hooks)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Signature:**
|
||||
|
||||
```ts
|
||||
fieldIsVirtual(field: Field | Tab): boolean
|
||||
```
|
||||
|
||||
## Data Guards
|
||||
|
||||
### fieldAffectsData
|
||||
|
||||
**Most commonly used guard.** Checks if field stores data (has name and is not UI-only).
|
||||
|
||||
```ts
|
||||
import { fieldAffectsData } from 'payload'
|
||||
|
||||
function generateSchema(fields: Field[]) {
|
||||
fields.forEach((field) => {
|
||||
if (fieldAffectsData(field)) {
|
||||
// Safe to access field.name
|
||||
schema[field.name] = getFieldType(field)
|
||||
}
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
**Signature:**
|
||||
|
||||
```ts
|
||||
fieldAffectsData<TField extends ClientField | Field | TabAsField | TabAsFieldClient>(
|
||||
field: TField
|
||||
): field is TField & (FieldAffectingDataClient | FieldAffectingData)
|
||||
```
|
||||
|
||||
**Pattern - Data Fields Only:**
|
||||
|
||||
```ts
|
||||
const dataFields = fields.filter(fieldAffectsData)
|
||||
```
|
||||
|
||||
### fieldIsPresentationalOnly
|
||||
|
||||
Checks if field is UI-only (type `'ui'`).
|
||||
|
||||
```ts
|
||||
import { fieldIsPresentationalOnly } from 'payload'
|
||||
|
||||
if (fieldIsPresentationalOnly(field)) {
|
||||
// field.type === 'ui'
|
||||
// Skip in data operations, GraphQL schema, etc.
|
||||
return
|
||||
}
|
||||
```
|
||||
|
||||
**Signature:**
|
||||
|
||||
```ts
|
||||
fieldIsPresentationalOnly<TField extends ClientField | Field | TabAsField | TabAsFieldClient>(
|
||||
field: TField
|
||||
): field is TField & (UIFieldClient | UIField)
|
||||
```
|
||||
|
||||
### fieldIsID
|
||||
|
||||
Checks if field name is exactly `'id'`.
|
||||
|
||||
```ts
|
||||
import { fieldIsID } from 'payload'
|
||||
|
||||
if (fieldIsID(field)) {
|
||||
// field.name === 'id'
|
||||
// Special handling for ID field
|
||||
}
|
||||
```
|
||||
|
||||
**Signature:**
|
||||
|
||||
```ts
|
||||
fieldIsID<TField extends ClientField | Field>(
|
||||
field: TField
|
||||
): field is { name: 'id' } & TField
|
||||
```
|
||||
|
||||
### fieldIsHiddenOrDisabled
|
||||
|
||||
Checks if field is hidden or admin-disabled.
|
||||
|
||||
```ts
|
||||
import { fieldIsHiddenOrDisabled } from 'payload'
|
||||
|
||||
const visibleFields = fields.filter((field) => !fieldIsHiddenOrDisabled(field))
|
||||
```
|
||||
|
||||
**Signature:**
|
||||
|
||||
```ts
|
||||
fieldIsHiddenOrDisabled<TField extends ClientField | Field | TabAsField | TabAsFieldClient>(
|
||||
field: TField
|
||||
): field is { admin: { hidden: true } } & TField
|
||||
```
|
||||
|
||||
## Layout Guards
|
||||
|
||||
### fieldIsSidebar
|
||||
|
||||
Checks if field is positioned in sidebar.
|
||||
|
||||
```ts
|
||||
import { fieldIsSidebar } from 'payload'
|
||||
|
||||
const [mainFields, sidebarFields] = fields.reduce(
|
||||
([main, sidebar], field) => {
|
||||
if (fieldIsSidebar(field)) {
|
||||
return [main, [...sidebar, field]]
|
||||
}
|
||||
return [[...main, field], sidebar]
|
||||
},
|
||||
[[], []],
|
||||
)
|
||||
```
|
||||
|
||||
**Signature:**
|
||||
|
||||
```ts
|
||||
fieldIsSidebar<TField extends ClientField | Field | TabAsField | TabAsFieldClient>(
|
||||
field: TField
|
||||
): field is { admin: { position: 'sidebar' } } & TField
|
||||
```
|
||||
|
||||
## Tab & Group Guards
|
||||
|
||||
### tabHasName
|
||||
|
||||
Checks if tab is named (stores data under tab name).
|
||||
|
||||
```ts
|
||||
import { tabHasName } from 'payload'
|
||||
|
||||
tabs.forEach((tab) => {
|
||||
if (tabHasName(tab)) {
|
||||
// tab.name exists
|
||||
dataPath.push(tab.name)
|
||||
}
|
||||
// Process tab.fields
|
||||
})
|
||||
```
|
||||
|
||||
**Signature:**
|
||||
|
||||
```ts
|
||||
tabHasName<TField extends ClientTab | Tab>(
|
||||
tab: TField
|
||||
): tab is NamedTab & TField
|
||||
```
|
||||
|
||||
### groupHasName
|
||||
|
||||
Checks if group is named (stores data under group name).
|
||||
|
||||
```ts
|
||||
import { groupHasName } from 'payload'
|
||||
|
||||
if (groupHasName(group)) {
|
||||
// group.name exists
|
||||
return data[group.name]
|
||||
}
|
||||
```
|
||||
|
||||
**Signature:**
|
||||
|
||||
```ts
|
||||
groupHasName(group: Partial<NamedGroupFieldClient>): group is NamedGroupFieldClient
|
||||
```
|
||||
|
||||
## Option & Value Guards
|
||||
|
||||
### optionIsObject
|
||||
|
||||
Checks if option is object format `{label, value}` vs string.
|
||||
|
||||
```ts
|
||||
import { optionIsObject } from 'payload'
|
||||
|
||||
field.options.forEach((option) => {
|
||||
if (optionIsObject(option)) {
|
||||
console.log(`${option.label}: ${option.value}`)
|
||||
} else {
|
||||
console.log(option) // string value
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
**Signature:**
|
||||
|
||||
```ts
|
||||
optionIsObject(option: Option): option is OptionObject
|
||||
```
|
||||
|
||||
### optionsAreObjects
|
||||
|
||||
Checks if entire options array contains objects.
|
||||
|
||||
```ts
|
||||
import { optionsAreObjects } from 'payload'
|
||||
|
||||
if (optionsAreObjects(field.options)) {
|
||||
// All options are OptionObject[]
|
||||
const labels = field.options.map((opt) => opt.label)
|
||||
}
|
||||
```
|
||||
|
||||
**Signature:**
|
||||
|
||||
```ts
|
||||
optionsAreObjects(options: Option[]): options is OptionObject[]
|
||||
```
|
||||
|
||||
### optionIsValue
|
||||
|
||||
Checks if option is string value (not object).
|
||||
|
||||
```ts
|
||||
import { optionIsValue } from 'payload'
|
||||
|
||||
if (optionIsValue(option)) {
|
||||
// option is string
|
||||
const value = option
|
||||
}
|
||||
```
|
||||
|
||||
**Signature:**
|
||||
|
||||
```ts
|
||||
optionIsValue(option: Option): option is string
|
||||
```
|
||||
|
||||
### valueIsValueWithRelation
|
||||
|
||||
Checks if relationship value is polymorphic format `{relationTo, value}`.
|
||||
|
||||
```ts
|
||||
import { valueIsValueWithRelation } from 'payload'
|
||||
|
||||
if (valueIsValueWithRelation(fieldValue)) {
|
||||
// fieldValue.relationTo exists
|
||||
// fieldValue.value exists
|
||||
console.log(`Related to ${fieldValue.relationTo}: ${fieldValue.value}`)
|
||||
}
|
||||
```
|
||||
|
||||
**Signature:**
|
||||
|
||||
```ts
|
||||
valueIsValueWithRelation(value: unknown): value is ValueWithRelation
|
||||
```
|
||||
|
||||
## Common Patterns
|
||||
|
||||
### Recursive Field Traversal
|
||||
|
||||
```ts
|
||||
import { fieldAffectsData, fieldHasSubFields } from 'payload'
|
||||
|
||||
function traverseFields(fields: Field[], callback: (field: Field) => void) {
|
||||
fields.forEach((field) => {
|
||||
if (fieldAffectsData(field)) {
|
||||
callback(field)
|
||||
}
|
||||
|
||||
if (fieldHasSubFields(field)) {
|
||||
traverseFields(field.fields, callback)
|
||||
}
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
### Filter Data-Bearing Fields
|
||||
|
||||
```ts
|
||||
import { fieldAffectsData, fieldIsPresentationalOnly, fieldIsHiddenOrDisabled } from 'payload'
|
||||
|
||||
const dataFields = fields.filter(
|
||||
(field) =>
|
||||
fieldAffectsData(field) && !fieldIsPresentationalOnly(field) && !fieldIsHiddenOrDisabled(field),
|
||||
)
|
||||
```
|
||||
|
||||
### Container Type Switching
|
||||
|
||||
```ts
|
||||
import { fieldIsArrayType, fieldIsBlockType, fieldHasSubFields } from 'payload'
|
||||
|
||||
if (fieldIsArrayType(field)) {
|
||||
// Handle array-specific logic
|
||||
} else if (fieldIsBlockType(field)) {
|
||||
// Handle blocks-specific logic
|
||||
} else if (fieldHasSubFields(field)) {
|
||||
// Handle group/row/collapsible
|
||||
}
|
||||
```
|
||||
|
||||
### Safe Property Access
|
||||
|
||||
```ts
|
||||
import { fieldSupportsMany, fieldHasMaxDepth } from 'payload'
|
||||
|
||||
// Without guard - TypeScript error
|
||||
// if (field.hasMany) { /* ... */ }
|
||||
|
||||
// With guard - safe access
|
||||
if (fieldSupportsMany(field) && field.hasMany) {
|
||||
console.log('Multiple values supported')
|
||||
}
|
||||
|
||||
if (fieldHasMaxDepth(field)) {
|
||||
const depth = field.maxDepth // TypeScript knows this is number
|
||||
}
|
||||
```
|
||||
|
||||
## Type Preservation
|
||||
|
||||
All guards preserve the original type constraint:
|
||||
|
||||
```ts
|
||||
import type { ClientField, Field } from 'payload'
|
||||
import { fieldHasSubFields } from 'payload'
|
||||
|
||||
function processServerField(field: Field) {
|
||||
if (fieldHasSubFields(field)) {
|
||||
// field is Field & FieldWithSubFields (not ClientField)
|
||||
}
|
||||
}
|
||||
|
||||
function processClientField(field: ClientField) {
|
||||
if (fieldHasSubFields(field)) {
|
||||
// field is ClientField & FieldWithSubFieldsClient
|
||||
}
|
||||
}
|
||||
```
|
||||
+744
@@ -0,0 +1,744 @@
|
||||
# Payload CMS Field Types Reference
|
||||
|
||||
Complete reference for all Payload field types with examples.
|
||||
|
||||
## Text Field
|
||||
|
||||
```ts
|
||||
import type { TextField } from 'payload'
|
||||
|
||||
const textField: TextField = {
|
||||
name: 'title',
|
||||
type: 'text',
|
||||
required: true,
|
||||
unique: true,
|
||||
minLength: 5,
|
||||
maxLength: 100,
|
||||
index: true,
|
||||
localized: true,
|
||||
defaultValue: 'Default Title',
|
||||
validate: (value) => Boolean(value) || 'Required',
|
||||
admin: {
|
||||
placeholder: 'Enter title...',
|
||||
position: 'sidebar',
|
||||
condition: (data) => data.showTitle === true,
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Slug Field Helper
|
||||
|
||||
Built-in helper for auto-generating slugs:
|
||||
|
||||
```ts
|
||||
import { slugField } from 'payload'
|
||||
import type { CollectionConfig } from 'payload'
|
||||
|
||||
export const Pages: CollectionConfig = {
|
||||
slug: 'pages',
|
||||
fields: [
|
||||
{ name: 'title', type: 'text', required: true },
|
||||
slugField({
|
||||
name: 'slug', // defaults to 'slug'
|
||||
useAsSlug: 'title', // defaults to 'title'
|
||||
checkboxName: 'generateSlug', // defaults to 'generateSlug'
|
||||
localized: true,
|
||||
required: true,
|
||||
overrides: (defaultField) => {
|
||||
// Customize the generated fields if needed
|
||||
return defaultField
|
||||
},
|
||||
}),
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
## Rich Text (Lexical)
|
||||
|
||||
```ts
|
||||
import type { RichTextField } from 'payload'
|
||||
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
||||
import { HeadingFeature, LinkFeature } from '@payloadcms/richtext-lexical'
|
||||
|
||||
const richTextField: RichTextField = {
|
||||
name: 'content',
|
||||
type: 'richText',
|
||||
required: true,
|
||||
localized: true,
|
||||
editor: lexicalEditor({
|
||||
features: ({ defaultFeatures }) => [
|
||||
...defaultFeatures,
|
||||
HeadingFeature({
|
||||
enabledHeadingSizes: ['h1', 'h2', 'h3'],
|
||||
}),
|
||||
LinkFeature({
|
||||
enabledCollections: ['posts', 'pages'],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
}
|
||||
```
|
||||
|
||||
### Advanced Lexical Configuration
|
||||
|
||||
```ts
|
||||
import {
|
||||
BoldFeature,
|
||||
EXPERIMENTAL_TableFeature,
|
||||
FixedToolbarFeature,
|
||||
HeadingFeature,
|
||||
IndentFeature,
|
||||
InlineToolbarFeature,
|
||||
ItalicFeature,
|
||||
LinkFeature,
|
||||
OrderedListFeature,
|
||||
UnderlineFeature,
|
||||
UnorderedListFeature,
|
||||
lexicalEditor,
|
||||
} from '@payloadcms/richtext-lexical'
|
||||
|
||||
// Global editor config with full features
|
||||
export default buildConfig({
|
||||
editor: lexicalEditor({
|
||||
features: () => {
|
||||
return [
|
||||
UnderlineFeature(),
|
||||
BoldFeature(),
|
||||
ItalicFeature(),
|
||||
OrderedListFeature(),
|
||||
UnorderedListFeature(),
|
||||
LinkFeature({
|
||||
enabledCollections: ['pages'],
|
||||
fields: ({ defaultFields }) => {
|
||||
const defaultFieldsWithoutUrl = defaultFields.filter((field) => {
|
||||
if ('name' in field && field.name === 'url') return false
|
||||
return true
|
||||
})
|
||||
|
||||
return [
|
||||
...defaultFieldsWithoutUrl,
|
||||
{
|
||||
name: 'url',
|
||||
type: 'text',
|
||||
admin: {
|
||||
condition: ({ linkType }) => linkType !== 'internal',
|
||||
},
|
||||
label: ({ t }) => t('fields:enterURL'),
|
||||
required: true,
|
||||
},
|
||||
]
|
||||
},
|
||||
}),
|
||||
IndentFeature(),
|
||||
EXPERIMENTAL_TableFeature(),
|
||||
]
|
||||
},
|
||||
}),
|
||||
})
|
||||
|
||||
// Field-specific editor with custom toolbar
|
||||
const richTextWithToolbars: RichTextField = {
|
||||
name: 'richText',
|
||||
type: 'richText',
|
||||
editor: lexicalEditor({
|
||||
features: ({ rootFeatures }) => {
|
||||
return [
|
||||
...rootFeatures,
|
||||
HeadingFeature({ enabledHeadingSizes: ['h2', 'h3', 'h4'] }),
|
||||
FixedToolbarFeature(),
|
||||
InlineToolbarFeature(),
|
||||
]
|
||||
},
|
||||
}),
|
||||
label: false,
|
||||
}
|
||||
```
|
||||
|
||||
## Relationship
|
||||
|
||||
```ts
|
||||
import type { RelationshipField } from 'payload'
|
||||
|
||||
// Single relationship
|
||||
const singleRelationship: RelationshipField = {
|
||||
name: 'author',
|
||||
type: 'relationship',
|
||||
relationTo: 'users',
|
||||
required: true,
|
||||
maxDepth: 2,
|
||||
}
|
||||
|
||||
// Multiple relationships (hasMany)
|
||||
const multipleRelationship: RelationshipField = {
|
||||
name: 'categories',
|
||||
type: 'relationship',
|
||||
relationTo: 'categories',
|
||||
hasMany: true,
|
||||
filterOptions: {
|
||||
active: { equals: true },
|
||||
},
|
||||
}
|
||||
|
||||
// Polymorphic relationship
|
||||
const polymorphicRelationship: PolymorphicRelationshipField = {
|
||||
name: 'relatedContent',
|
||||
type: 'relationship',
|
||||
relationTo: ['posts', 'pages'],
|
||||
hasMany: true,
|
||||
}
|
||||
```
|
||||
|
||||
## Array
|
||||
|
||||
```ts
|
||||
import type { ArrayField } from 'payload'
|
||||
|
||||
const arrayField: ArrayField = {
|
||||
name: 'slides',
|
||||
type: 'array',
|
||||
minRows: 2,
|
||||
maxRows: 10,
|
||||
labels: {
|
||||
singular: 'Slide',
|
||||
plural: 'Slides',
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
name: 'title',
|
||||
type: 'text',
|
||||
required: true,
|
||||
},
|
||||
{
|
||||
name: 'image',
|
||||
type: 'upload',
|
||||
relationTo: 'media',
|
||||
},
|
||||
],
|
||||
admin: {
|
||||
initCollapsed: true,
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
## Blocks
|
||||
|
||||
```ts
|
||||
import type { BlocksField, Block } from 'payload'
|
||||
|
||||
const HeroBlock: Block = {
|
||||
slug: 'hero',
|
||||
interfaceName: 'HeroBlock',
|
||||
fields: [
|
||||
{
|
||||
name: 'heading',
|
||||
type: 'text',
|
||||
required: true,
|
||||
},
|
||||
{
|
||||
name: 'background',
|
||||
type: 'upload',
|
||||
relationTo: 'media',
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
const ContentBlock: Block = {
|
||||
slug: 'content',
|
||||
fields: [
|
||||
{
|
||||
name: 'text',
|
||||
type: 'richText',
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
const blocksField: BlocksField = {
|
||||
name: 'layout',
|
||||
type: 'blocks',
|
||||
blocks: [HeroBlock, ContentBlock],
|
||||
}
|
||||
```
|
||||
|
||||
## Select
|
||||
|
||||
```ts
|
||||
import type { SelectField } from 'payload'
|
||||
|
||||
const selectField: SelectField = {
|
||||
name: 'status',
|
||||
type: 'select',
|
||||
options: [
|
||||
{ label: 'Draft', value: 'draft' },
|
||||
{ label: 'Published', value: 'published' },
|
||||
],
|
||||
defaultValue: 'draft',
|
||||
required: true,
|
||||
}
|
||||
|
||||
// Multiple select
|
||||
const multiSelectField: SelectField = {
|
||||
name: 'tags',
|
||||
type: 'select',
|
||||
hasMany: true,
|
||||
options: ['tech', 'news', 'sports'],
|
||||
}
|
||||
```
|
||||
|
||||
## Upload
|
||||
|
||||
```ts
|
||||
import type { UploadField } from 'payload'
|
||||
|
||||
const uploadField: UploadField = {
|
||||
name: 'featuredImage',
|
||||
type: 'upload',
|
||||
relationTo: 'media',
|
||||
required: true,
|
||||
filterOptions: {
|
||||
mimeType: { contains: 'image' },
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
## Point (Geolocation)
|
||||
|
||||
Point fields store geographic coordinates with automatic 2dsphere indexing for geospatial queries.
|
||||
|
||||
```ts
|
||||
import type { PointField } from 'payload'
|
||||
|
||||
const locationField: PointField = {
|
||||
name: 'location',
|
||||
type: 'point',
|
||||
label: 'Location',
|
||||
required: true,
|
||||
}
|
||||
|
||||
// Returns [longitude, latitude]
|
||||
// Example: [-122.4194, 37.7749] for San Francisco
|
||||
```
|
||||
|
||||
### Geospatial Queries
|
||||
|
||||
```ts
|
||||
// Query by distance (sorted by nearest first)
|
||||
const nearbyLocations = await payload.find({
|
||||
collection: 'stores',
|
||||
where: {
|
||||
location: {
|
||||
near: [10, 20], // [longitude, latitude]
|
||||
maxDistance: 5000, // in meters
|
||||
minDistance: 1000,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
// Query within polygon area
|
||||
const polygon: Point[] = [
|
||||
[9.0, 19.0], // bottom-left
|
||||
[9.0, 21.0], // top-left
|
||||
[11.0, 21.0], // top-right
|
||||
[11.0, 19.0], // bottom-right
|
||||
[9.0, 19.0], // closing point
|
||||
]
|
||||
|
||||
const withinArea = await payload.find({
|
||||
collection: 'stores',
|
||||
where: {
|
||||
location: {
|
||||
within: {
|
||||
type: 'Polygon',
|
||||
coordinates: [polygon],
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
// Query intersecting area
|
||||
const intersecting = await payload.find({
|
||||
collection: 'stores',
|
||||
where: {
|
||||
location: {
|
||||
intersects: {
|
||||
type: 'Polygon',
|
||||
coordinates: [polygon],
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
**Note**: Point fields are not supported in SQLite.
|
||||
|
||||
## Join Fields
|
||||
|
||||
Join fields create reverse relationships, allowing you to access related documents from the "other side" of a relationship.
|
||||
|
||||
```ts
|
||||
import type { JoinField } from 'payload'
|
||||
|
||||
// From Users collection - show user's orders
|
||||
const ordersJoinField: JoinField = {
|
||||
name: 'orders',
|
||||
type: 'join',
|
||||
collection: 'orders',
|
||||
on: 'customer', // The field in 'orders' that references this user
|
||||
admin: {
|
||||
allowCreate: false,
|
||||
defaultColumns: ['id', 'createdAt', 'total', 'currency', 'items'],
|
||||
},
|
||||
}
|
||||
|
||||
// From Users collection - show user's cart
|
||||
const cartJoinField: JoinField = {
|
||||
name: 'cart',
|
||||
type: 'join',
|
||||
collection: 'carts',
|
||||
on: 'customer',
|
||||
admin: {
|
||||
allowCreate: false,
|
||||
defaultColumns: ['id', 'createdAt', 'total', 'currency'],
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
## Virtual Fields
|
||||
|
||||
```ts
|
||||
import type { TextField } from 'payload'
|
||||
|
||||
// Computed from siblings
|
||||
const computedVirtualField: TextField = {
|
||||
name: 'fullName',
|
||||
type: 'text',
|
||||
virtual: true,
|
||||
hooks: {
|
||||
afterRead: [({ siblingData }) => `${siblingData.firstName} ${siblingData.lastName}`],
|
||||
},
|
||||
}
|
||||
|
||||
// From relationship path
|
||||
const pathVirtualField: TextField = {
|
||||
name: 'authorName',
|
||||
type: 'text',
|
||||
virtual: 'author.name',
|
||||
}
|
||||
```
|
||||
|
||||
## Conditional Fields
|
||||
|
||||
```ts
|
||||
import type { UploadField, CheckboxField } from 'payload'
|
||||
|
||||
// Simple boolean condition
|
||||
const enableFeatureField: CheckboxField = {
|
||||
name: 'enableFeature',
|
||||
type: 'checkbox',
|
||||
}
|
||||
|
||||
const conditionalField: TextField = {
|
||||
name: 'featureText',
|
||||
type: 'text',
|
||||
admin: {
|
||||
condition: (data) => data.enableFeature === true,
|
||||
},
|
||||
}
|
||||
|
||||
// Sibling data condition (from hero field pattern)
|
||||
const typeField: SelectField = {
|
||||
name: 'type',
|
||||
type: 'select',
|
||||
options: ['none', 'highImpact', 'mediumImpact', 'lowImpact'],
|
||||
defaultValue: 'lowImpact',
|
||||
}
|
||||
|
||||
const mediaField: UploadField = {
|
||||
name: 'media',
|
||||
type: 'upload',
|
||||
relationTo: 'media',
|
||||
admin: {
|
||||
condition: (_, { type } = {}) => ['highImpact', 'mediumImpact'].includes(type),
|
||||
},
|
||||
required: true,
|
||||
}
|
||||
```
|
||||
|
||||
## Radio
|
||||
|
||||
Radio fields present options as radio buttons for single selection.
|
||||
|
||||
```ts
|
||||
import type { RadioField } from 'payload'
|
||||
|
||||
const radioField: RadioField = {
|
||||
name: 'priority',
|
||||
type: 'radio',
|
||||
options: [
|
||||
{ label: 'Low', value: 'low' },
|
||||
{ label: 'Medium', value: 'medium' },
|
||||
{ label: 'High', value: 'high' },
|
||||
],
|
||||
defaultValue: 'medium',
|
||||
admin: {
|
||||
layout: 'horizontal', // or 'vertical'
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
## Row (Layout)
|
||||
|
||||
Row fields arrange fields horizontally in the admin panel (presentational only).
|
||||
|
||||
```ts
|
||||
import type { RowField } from 'payload'
|
||||
|
||||
const rowField: RowField = {
|
||||
type: 'row',
|
||||
fields: [
|
||||
{
|
||||
name: 'firstName',
|
||||
type: 'text',
|
||||
admin: { width: '50%' },
|
||||
},
|
||||
{
|
||||
name: 'lastName',
|
||||
type: 'text',
|
||||
admin: { width: '50%' },
|
||||
},
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
## Collapsible (Layout)
|
||||
|
||||
Collapsible fields group fields in an expandable/collapsible section.
|
||||
|
||||
```ts
|
||||
import type { CollapsibleField } from 'payload'
|
||||
|
||||
const collapsibleField: CollapsibleField = {
|
||||
label: ({ data }) => data?.title || 'Advanced Options',
|
||||
type: 'collapsible',
|
||||
admin: {
|
||||
initCollapsed: true,
|
||||
},
|
||||
fields: [
|
||||
{ name: 'customCSS', type: 'textarea' },
|
||||
{ name: 'customJS', type: 'code' },
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
## UI (Custom Components)
|
||||
|
||||
UI fields allow fully custom React components in the admin (no data stored).
|
||||
|
||||
```ts
|
||||
import type { UIField } from 'payload'
|
||||
|
||||
const uiField: UIField = {
|
||||
name: 'customMessage',
|
||||
type: 'ui',
|
||||
admin: {
|
||||
components: {
|
||||
Field: '/path/to/CustomFieldComponent',
|
||||
Cell: '/path/to/CustomCellComponent', // For list view
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
## Tabs & Groups
|
||||
|
||||
```ts
|
||||
import type { TabsField, GroupField } from 'payload'
|
||||
|
||||
// Tabs
|
||||
const tabsField: TabsField = {
|
||||
type: 'tabs',
|
||||
tabs: [
|
||||
{
|
||||
label: 'Content',
|
||||
fields: [
|
||||
{ name: 'title', type: 'text' },
|
||||
{ name: 'body', type: 'richText' },
|
||||
],
|
||||
},
|
||||
{
|
||||
label: 'SEO',
|
||||
fields: [
|
||||
{ name: 'metaTitle', type: 'text' },
|
||||
{ name: 'metaDescription', type: 'textarea' },
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
// Group (named)
|
||||
const groupField: GroupField = {
|
||||
name: 'meta',
|
||||
type: 'group',
|
||||
fields: [
|
||||
{ name: 'title', type: 'text' },
|
||||
{ name: 'description', type: 'textarea' },
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
## Reusable Field Factories
|
||||
|
||||
Create composable field patterns that can be customized with overrides.
|
||||
|
||||
```ts
|
||||
import type { Field, GroupField } from 'payload'
|
||||
|
||||
// Utility for deep merging
|
||||
const deepMerge = <T>(target: T, source: Partial<T>): T => {
|
||||
// Implementation would deeply merge objects
|
||||
return { ...target, ...source }
|
||||
}
|
||||
|
||||
// Reusable link field factory
|
||||
type LinkType = (options?: {
|
||||
appearances?: ('default' | 'outline')[] | false
|
||||
disableLabel?: boolean
|
||||
overrides?: Record<string, unknown>
|
||||
}) => GroupField
|
||||
|
||||
export const link: LinkType = ({ appearances, disableLabel = false, overrides = {} } = {}) => {
|
||||
const linkField: GroupField = {
|
||||
name: 'link',
|
||||
type: 'group',
|
||||
admin: {
|
||||
hideGutter: true,
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
type: 'row',
|
||||
fields: [
|
||||
{
|
||||
name: 'type',
|
||||
type: 'radio',
|
||||
options: [
|
||||
{ label: 'Internal link', value: 'reference' },
|
||||
{ label: 'Custom URL', value: 'custom' },
|
||||
],
|
||||
defaultValue: 'reference',
|
||||
admin: {
|
||||
layout: 'horizontal',
|
||||
width: '50%',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'newTab',
|
||||
type: 'checkbox',
|
||||
label: 'Open in new tab',
|
||||
admin: {
|
||||
width: '50%',
|
||||
style: {
|
||||
alignSelf: 'flex-end',
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'reference',
|
||||
type: 'relationship',
|
||||
relationTo: ['pages'],
|
||||
required: true,
|
||||
maxDepth: 1,
|
||||
admin: {
|
||||
condition: (_, siblingData) => siblingData?.type === 'reference',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'url',
|
||||
type: 'text',
|
||||
label: 'Custom URL',
|
||||
required: true,
|
||||
admin: {
|
||||
condition: (_, siblingData) => siblingData?.type === 'custom',
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
if (!disableLabel) {
|
||||
linkField.fields.push({
|
||||
name: 'label',
|
||||
type: 'text',
|
||||
required: true,
|
||||
})
|
||||
}
|
||||
|
||||
if (appearances !== false) {
|
||||
linkField.fields.push({
|
||||
name: 'appearance',
|
||||
type: 'select',
|
||||
defaultValue: 'default',
|
||||
options: [
|
||||
{ label: 'Default', value: 'default' },
|
||||
{ label: 'Outline', value: 'outline' },
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
return deepMerge(linkField, overrides) as GroupField
|
||||
}
|
||||
|
||||
// Usage
|
||||
const navItem = link({ appearances: false })
|
||||
const ctaButton = link({
|
||||
overrides: {
|
||||
name: 'cta',
|
||||
admin: {
|
||||
description: 'Call to action button',
|
||||
},
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
## Field Type Guards
|
||||
|
||||
Type guards for runtime field type checking and safe type narrowing.
|
||||
|
||||
| Type Guard | Checks For | Use When |
|
||||
| --------------------------- | ----------------------------------------------------------- | ---------------------------------------- |
|
||||
| `fieldAffectsData` | Field stores data (has name, not UI-only) | Need to access field data or name |
|
||||
| `fieldHasSubFields` | Field contains nested fields (group/array/row/collapsible) | Need to recursively traverse fields |
|
||||
| `fieldIsArrayType` | Field is array type | Distinguish arrays from other containers |
|
||||
| `fieldIsBlockType` | Field is blocks type | Handle blocks-specific logic |
|
||||
| `fieldIsGroupType` | Field is group type | Handle group-specific logic |
|
||||
| `fieldSupportsMany` | Field can have multiple values (select/relationship/upload) | Check for `hasMany` support |
|
||||
| `fieldHasMaxDepth` | Field supports population depth control | Control relationship/upload/join depth |
|
||||
| `fieldIsPresentationalOnly` | Field is UI-only (no data storage) | Exclude from data operations |
|
||||
| `fieldIsSidebar` | Field positioned in sidebar | Separate sidebar rendering |
|
||||
| `fieldIsID` | Field name is 'id' | Special ID field handling |
|
||||
| `fieldIsHiddenOrDisabled` | Field is hidden or disabled | Filter from UI operations |
|
||||
| `fieldShouldBeLocalized` | Field needs localization handling | Proper locale table checks |
|
||||
| `fieldIsVirtual` | Field is virtual (computed/no DB column) | Skip in database transforms |
|
||||
| `tabHasName` | Tab is named (stores data) | Distinguish named vs unnamed tabs |
|
||||
| `groupHasName` | Group is named (stores data) | Distinguish named vs unnamed groups |
|
||||
| `optionIsObject` | Option is `{label, value}` format | Access option properties safely |
|
||||
| `optionsAreObjects` | All options are objects | Batch option processing |
|
||||
| `optionIsValue` | Option is string value | Handle string options |
|
||||
| `valueIsValueWithRelation` | Value is polymorphic relationship | Handle polymorphic relationships |
|
||||
|
||||
```ts
|
||||
import { fieldAffectsData, fieldHasSubFields, fieldIsArrayType } from 'payload'
|
||||
|
||||
function processField(field: Field) {
|
||||
if (fieldAffectsData(field)) {
|
||||
// Safe to access field.name
|
||||
console.log(field.name)
|
||||
}
|
||||
|
||||
if (fieldHasSubFields(field)) {
|
||||
// Safe to access field.fields
|
||||
field.fields.forEach(processField)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
See [FIELD-TYPE-GUARDS.md](FIELD-TYPE-GUARDS.md) for detailed usage patterns.
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
# Payload CMS Hooks Reference
|
||||
|
||||
Complete reference for collection hooks, field hooks, and hook context patterns.
|
||||
|
||||
## Collection Hooks
|
||||
|
||||
```ts
|
||||
export const Posts: CollectionConfig = {
|
||||
slug: 'posts',
|
||||
hooks: {
|
||||
// Before validation
|
||||
beforeValidate: [
|
||||
async ({ data, operation }) => {
|
||||
if (operation === 'create') {
|
||||
data.slug = slugify(data.title)
|
||||
}
|
||||
return data
|
||||
},
|
||||
],
|
||||
|
||||
// Before save
|
||||
beforeChange: [
|
||||
async ({ data, req, operation, originalDoc }) => {
|
||||
if (operation === 'update' && data.status === 'published') {
|
||||
data.publishedAt = new Date()
|
||||
}
|
||||
return data
|
||||
},
|
||||
],
|
||||
|
||||
// After save
|
||||
afterChange: [
|
||||
async ({ doc, req, operation, previousDoc }) => {
|
||||
if (operation === 'create') {
|
||||
await sendNotification(doc)
|
||||
}
|
||||
return doc
|
||||
},
|
||||
],
|
||||
|
||||
// After read
|
||||
afterRead: [
|
||||
async ({ doc, req }) => {
|
||||
doc.viewCount = await getViewCount(doc.id)
|
||||
return doc
|
||||
},
|
||||
],
|
||||
|
||||
// Before delete
|
||||
beforeDelete: [
|
||||
async ({ req, id }) => {
|
||||
await cleanupRelatedData(id)
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
## Field Hooks
|
||||
|
||||
```ts
|
||||
import type { EmailField, FieldHook } from 'payload'
|
||||
|
||||
const beforeValidateHook: FieldHook = ({ value }) => {
|
||||
return value.trim().toLowerCase()
|
||||
}
|
||||
|
||||
const afterReadHook: FieldHook = ({ value, req }) => {
|
||||
// Hide email from non-admins
|
||||
if (!req.user?.roles?.includes('admin')) {
|
||||
return value.replace(/(.{2})(.*)(@.*)/, '$1***$3')
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
const emailField: EmailField = {
|
||||
name: 'email',
|
||||
type: 'email',
|
||||
hooks: {
|
||||
beforeValidate: [beforeValidateHook],
|
||||
afterRead: [afterReadHook],
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
## Hook Context
|
||||
|
||||
Share data between hooks or control hook behavior using request context:
|
||||
|
||||
```ts
|
||||
import type { CollectionConfig } from 'payload'
|
||||
|
||||
export const Posts: CollectionConfig = {
|
||||
slug: 'posts',
|
||||
hooks: {
|
||||
beforeChange: [
|
||||
async ({ context }) => {
|
||||
context.expensiveData = await fetchExpensiveData()
|
||||
},
|
||||
],
|
||||
afterChange: [
|
||||
async ({ context, doc }) => {
|
||||
// Reuse from previous hook
|
||||
await processData(doc, context.expensiveData)
|
||||
},
|
||||
],
|
||||
},
|
||||
fields: [{ name: 'title', type: 'text' }],
|
||||
}
|
||||
```
|
||||
|
||||
## Next.js Revalidation with Context Control
|
||||
|
||||
```ts
|
||||
import type { CollectionAfterChangeHook, CollectionAfterDeleteHook } from 'payload'
|
||||
import { revalidatePath } from 'next/cache'
|
||||
import type { Page } from '../payload-types'
|
||||
|
||||
export const revalidatePage: CollectionAfterChangeHook<Page> = ({
|
||||
doc,
|
||||
previousDoc,
|
||||
req: { payload, context },
|
||||
}) => {
|
||||
if (!context.disableRevalidate) {
|
||||
if (doc._status === 'published') {
|
||||
const path = doc.slug === 'home' ? '/' : `/${doc.slug}`
|
||||
payload.logger.info(`Revalidating page at path: ${path}`)
|
||||
revalidatePath(path)
|
||||
}
|
||||
|
||||
// Revalidate old path if unpublished
|
||||
if (previousDoc?._status === 'published' && doc._status !== 'published') {
|
||||
const oldPath = previousDoc.slug === 'home' ? '/' : `/${previousDoc.slug}`
|
||||
payload.logger.info(`Revalidating old page at path: ${oldPath}`)
|
||||
revalidatePath(oldPath)
|
||||
}
|
||||
}
|
||||
return doc
|
||||
}
|
||||
|
||||
export const revalidateDelete: CollectionAfterDeleteHook<Page> = ({ doc, req: { context } }) => {
|
||||
if (!context.disableRevalidate) {
|
||||
const path = doc?.slug === 'home' ? '/' : `/${doc?.slug}`
|
||||
revalidatePath(path)
|
||||
}
|
||||
return doc
|
||||
}
|
||||
```
|
||||
|
||||
## Date Field Auto-Set
|
||||
|
||||
Automatically set date when document is published:
|
||||
|
||||
```ts
|
||||
import type { DateField } from 'payload'
|
||||
|
||||
const publishedOnField: DateField = {
|
||||
name: 'publishedOn',
|
||||
type: 'date',
|
||||
admin: {
|
||||
date: {
|
||||
pickerAppearance: 'dayAndTime',
|
||||
},
|
||||
position: 'sidebar',
|
||||
},
|
||||
hooks: {
|
||||
beforeChange: [
|
||||
({ siblingData, value }) => {
|
||||
if (siblingData._status === 'published' && !value) {
|
||||
return new Date()
|
||||
}
|
||||
return value
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
## Hook Patterns Best Practices
|
||||
|
||||
- Use `beforeValidate` for data formatting
|
||||
- Use `beforeChange` for business logic
|
||||
- Use `afterChange` for side effects
|
||||
- Use `afterRead` for computed fields
|
||||
- Store expensive operations in `context`
|
||||
- Pass `req` to nested operations for transaction safety (see [ADAPTERS.md#threading-req-through-operations](ADAPTERS.md#threading-req-through-operations))
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,274 @@
|
||||
# Payload CMS Querying Reference
|
||||
|
||||
Complete reference for querying data across Local API, REST, and GraphQL.
|
||||
|
||||
## Query Operators
|
||||
|
||||
```ts
|
||||
import type { Where } from 'payload'
|
||||
|
||||
// Equals
|
||||
const equalsQuery: Where = { color: { equals: 'blue' } }
|
||||
|
||||
// Not equals
|
||||
const notEqualsQuery: Where = { status: { not_equals: 'draft' } }
|
||||
|
||||
// Greater/less than
|
||||
const greaterThanQuery: Where = { price: { greater_than: 100 } }
|
||||
const lessThanEqualQuery: Where = { age: { less_than_equal: 65 } }
|
||||
|
||||
// Contains (case-insensitive)
|
||||
const containsQuery: Where = { title: { contains: 'payload' } }
|
||||
|
||||
// Like (all words present)
|
||||
const likeQuery: Where = { description: { like: 'cms headless' } }
|
||||
|
||||
// In/not in
|
||||
const inQuery: Where = { category: { in: ['tech', 'news'] } }
|
||||
|
||||
// Exists
|
||||
const existsQuery: Where = { image: { exists: true } }
|
||||
|
||||
// Near (point fields)
|
||||
const nearQuery: Where = { location: { near: '-122.4194,37.7749,10000' } }
|
||||
```
|
||||
|
||||
## AND/OR Logic
|
||||
|
||||
```ts
|
||||
import type { Where } from 'payload'
|
||||
|
||||
const complexQuery: Where = {
|
||||
or: [
|
||||
{ color: { equals: 'mint' } },
|
||||
{
|
||||
and: [{ color: { equals: 'white' } }, { featured: { equals: false } }],
|
||||
},
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
## Nested Properties
|
||||
|
||||
```ts
|
||||
import type { Where } from 'payload'
|
||||
|
||||
const nestedQuery: Where = {
|
||||
'author.role': { equals: 'editor' },
|
||||
'meta.featured': { exists: true },
|
||||
}
|
||||
```
|
||||
|
||||
## Local API
|
||||
|
||||
```ts
|
||||
// Find documents
|
||||
const posts = await payload.find({
|
||||
collection: 'posts',
|
||||
where: {
|
||||
status: { equals: 'published' },
|
||||
'author.name': { contains: 'john' },
|
||||
},
|
||||
depth: 2,
|
||||
limit: 10,
|
||||
page: 1,
|
||||
sort: '-createdAt',
|
||||
locale: 'en',
|
||||
select: {
|
||||
title: true,
|
||||
author: true,
|
||||
},
|
||||
})
|
||||
|
||||
// Find by ID
|
||||
const post = await payload.findByID({
|
||||
collection: 'posts',
|
||||
id: '123',
|
||||
depth: 2,
|
||||
})
|
||||
|
||||
// Create
|
||||
const post = await payload.create({
|
||||
collection: 'posts',
|
||||
data: {
|
||||
title: 'New Post',
|
||||
status: 'draft',
|
||||
},
|
||||
})
|
||||
|
||||
// Update
|
||||
await payload.update({
|
||||
collection: 'posts',
|
||||
id: '123',
|
||||
data: {
|
||||
status: 'published',
|
||||
},
|
||||
})
|
||||
|
||||
// Delete
|
||||
await payload.delete({
|
||||
collection: 'posts',
|
||||
id: '123',
|
||||
})
|
||||
|
||||
// Count
|
||||
const count = await payload.count({
|
||||
collection: 'posts',
|
||||
where: {
|
||||
status: { equals: 'published' },
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
### Threading req Parameter
|
||||
|
||||
When performing operations in hooks or nested operations, pass the `req` parameter to maintain transaction context:
|
||||
|
||||
```ts
|
||||
// ✅ CORRECT: Pass req for transaction safety
|
||||
const afterChange: CollectionAfterChangeHook = async ({ doc, req }) => {
|
||||
await req.payload.create({
|
||||
collection: 'audit-log',
|
||||
data: { action: 'created', docId: doc.id },
|
||||
req, // Maintains transaction atomicity
|
||||
})
|
||||
}
|
||||
|
||||
// ❌ WRONG: Missing req breaks transaction
|
||||
const afterChange: CollectionAfterChangeHook = async ({ doc, req }) => {
|
||||
await req.payload.create({
|
||||
collection: 'audit-log',
|
||||
data: { action: 'created', docId: doc.id },
|
||||
// Missing req - runs in separate transaction
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
This is critical for MongoDB replica sets and Postgres. See [ADAPTERS.md#threading-req-through-operations](ADAPTERS.md#threading-req-through-operations) for details.
|
||||
|
||||
### Access Control in Local API
|
||||
|
||||
**Important**: Local API bypasses access control by default (`overrideAccess: true`). When passing a `user` parameter, you must explicitly set `overrideAccess: false` to respect that user's permissions.
|
||||
|
||||
```ts
|
||||
// ❌ WRONG: User is passed but access control is bypassed
|
||||
const posts = await payload.find({
|
||||
collection: 'posts',
|
||||
user: currentUser,
|
||||
// Missing: overrideAccess: false
|
||||
// Result: Operation runs with ADMIN privileges, ignoring user's permissions
|
||||
})
|
||||
|
||||
// ✅ CORRECT: Respects user's access control permissions
|
||||
const posts = await payload.find({
|
||||
collection: 'posts',
|
||||
user: currentUser,
|
||||
overrideAccess: false, // Required to enforce access control
|
||||
// Result: User only sees posts they have permission to read
|
||||
})
|
||||
|
||||
// Administrative operation (intentionally bypass access control)
|
||||
const allPosts = await payload.find({
|
||||
collection: 'posts',
|
||||
// No user parameter
|
||||
// overrideAccess defaults to true
|
||||
// Result: Returns all posts regardless of access control
|
||||
})
|
||||
```
|
||||
|
||||
**When to use `overrideAccess: false`:**
|
||||
|
||||
- Performing operations on behalf of a user
|
||||
- Testing access control logic
|
||||
- API routes that should respect user permissions
|
||||
- Any operation where `user` parameter is provided
|
||||
|
||||
**When `overrideAccess: true` is appropriate:**
|
||||
|
||||
- Administrative operations (migrations, seeds, cron jobs)
|
||||
- Internal system operations
|
||||
- Operations explicitly intended to bypass access control
|
||||
|
||||
See [ACCESS-CONTROL.md#important-notes](ACCESS-CONTROL.md#important-notes) for more details.
|
||||
|
||||
## REST API
|
||||
|
||||
```ts
|
||||
import { stringify } from 'qs-esm'
|
||||
|
||||
const query = {
|
||||
status: { equals: 'published' },
|
||||
}
|
||||
|
||||
const queryString = stringify(
|
||||
{
|
||||
where: query,
|
||||
depth: 2,
|
||||
limit: 10,
|
||||
},
|
||||
{ addQueryPrefix: true },
|
||||
)
|
||||
|
||||
const response = await fetch(`https://api.example.com/api/posts${queryString}`)
|
||||
const data = await response.json()
|
||||
```
|
||||
|
||||
### REST Endpoints
|
||||
|
||||
```txt
|
||||
GET /api/{collection} - Find documents
|
||||
GET /api/{collection}/{id} - Find by ID
|
||||
POST /api/{collection} - Create
|
||||
PATCH /api/{collection}/{id} - Update
|
||||
DELETE /api/{collection}/{id} - Delete
|
||||
GET /api/{collection}/count - Count documents
|
||||
|
||||
GET /api/globals/{slug} - Get global
|
||||
POST /api/globals/{slug} - Update global
|
||||
```
|
||||
|
||||
## GraphQL
|
||||
|
||||
```graphql
|
||||
query {
|
||||
Posts(where: { status: { equals: published } }, limit: 10, sort: "-createdAt") {
|
||||
docs {
|
||||
id
|
||||
title
|
||||
author {
|
||||
name
|
||||
}
|
||||
}
|
||||
totalDocs
|
||||
hasNextPage
|
||||
}
|
||||
}
|
||||
|
||||
mutation {
|
||||
createPost(data: { title: "New Post", status: draft }) {
|
||||
id
|
||||
title
|
||||
}
|
||||
}
|
||||
|
||||
mutation {
|
||||
updatePost(id: "123", data: { status: published }) {
|
||||
id
|
||||
status
|
||||
}
|
||||
}
|
||||
|
||||
mutation {
|
||||
deletePost(id: "123") {
|
||||
id
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Performance Best Practices
|
||||
|
||||
- Set `maxDepth` on relationships to prevent over-fetching
|
||||
- Use `select` to limit returned fields
|
||||
- Index frequently queried fields
|
||||
- Use `virtual` fields for computed data
|
||||
- Cache expensive operations in hook `context`
|
||||
+3810
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,17 @@
|
||||
MIT License
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
|
||||
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
|
||||
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of
|
||||
the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
|
||||
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
||||
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
The upstream repository (https://github.com/vercel-labs/agent-skills) declares the MIT licence in its README and in
|
||||
the SKILL.md frontmatter; it ships no LICENSE file with a copyright line. Copyright: Vercel.
|
||||
@@ -0,0 +1,123 @@
|
||||
# React Best Practices
|
||||
|
||||
A structured repository for creating and maintaining React Best Practices optimized for agents and LLMs.
|
||||
|
||||
## Structure
|
||||
|
||||
- `rules/` - Individual rule files (one per rule)
|
||||
- `_sections.md` - Section metadata (titles, impacts, descriptions)
|
||||
- `_template.md` - Template for creating new rules
|
||||
- `area-description.md` - Individual rule files
|
||||
- `src/` - Build scripts and utilities
|
||||
- `metadata.json` - Document metadata (version, organization, abstract)
|
||||
- __`AGENTS.md`__ - Compiled output (generated)
|
||||
- __`test-cases.json`__ - Test cases for LLM evaluation (generated)
|
||||
|
||||
## Getting Started
|
||||
|
||||
1. Install dependencies:
|
||||
```bash
|
||||
pnpm install
|
||||
```
|
||||
|
||||
2. Build AGENTS.md from rules:
|
||||
```bash
|
||||
pnpm build
|
||||
```
|
||||
|
||||
3. Validate rule files:
|
||||
```bash
|
||||
pnpm validate
|
||||
```
|
||||
|
||||
4. Extract test cases:
|
||||
```bash
|
||||
pnpm extract-tests
|
||||
```
|
||||
|
||||
## Creating a New Rule
|
||||
|
||||
1. Copy `rules/_template.md` to `rules/area-description.md`
|
||||
2. Choose the appropriate area prefix:
|
||||
- `async-` for Eliminating Waterfalls (Section 1)
|
||||
- `bundle-` for Bundle Size Optimization (Section 2)
|
||||
- `server-` for Server-Side Performance (Section 3)
|
||||
- `client-` for Client-Side Data Fetching (Section 4)
|
||||
- `rerender-` for Re-render Optimization (Section 5)
|
||||
- `rendering-` for Rendering Performance (Section 6)
|
||||
- `js-` for JavaScript Performance (Section 7)
|
||||
- `advanced-` for Advanced Patterns (Section 8)
|
||||
3. Fill in the frontmatter and content
|
||||
4. Ensure you have clear examples with explanations
|
||||
5. Run `pnpm build` to regenerate AGENTS.md and test-cases.json
|
||||
|
||||
## Rule File Structure
|
||||
|
||||
Each rule file should follow this structure:
|
||||
|
||||
```markdown
|
||||
---
|
||||
title: Rule Title Here
|
||||
impact: MEDIUM
|
||||
impactDescription: Optional description
|
||||
tags: tag1, tag2, tag3
|
||||
---
|
||||
|
||||
## Rule Title Here
|
||||
|
||||
Brief explanation of the rule and why it matters.
|
||||
|
||||
**Incorrect (description of what's wrong):**
|
||||
|
||||
```typescript
|
||||
// Bad code example
|
||||
```
|
||||
|
||||
**Correct (description of what's right):**
|
||||
|
||||
```typescript
|
||||
// Good code example
|
||||
```
|
||||
|
||||
Optional explanatory text after examples.
|
||||
|
||||
Reference: [Link](https://example.com)
|
||||
|
||||
## File Naming Convention
|
||||
|
||||
- Files starting with `_` are special (excluded from build)
|
||||
- Rule files: `area-description.md` (e.g., `async-parallel.md`)
|
||||
- Section is automatically inferred from filename prefix
|
||||
- Rules are sorted alphabetically by title within each section
|
||||
- IDs (e.g., 1.1, 1.2) are auto-generated during build
|
||||
|
||||
## Impact Levels
|
||||
|
||||
- `CRITICAL` - Highest priority, major performance gains
|
||||
- `HIGH` - Significant performance improvements
|
||||
- `MEDIUM-HIGH` - Moderate-high gains
|
||||
- `MEDIUM` - Moderate performance improvements
|
||||
- `LOW-MEDIUM` - Low-medium gains
|
||||
- `LOW` - Incremental improvements
|
||||
|
||||
## Scripts
|
||||
|
||||
- `pnpm build` - Compile rules into AGENTS.md
|
||||
- `pnpm validate` - Validate all rule files
|
||||
- `pnpm extract-tests` - Extract test cases for LLM evaluation
|
||||
- `pnpm dev` - Build and validate
|
||||
|
||||
## Contributing
|
||||
|
||||
When adding or modifying rules:
|
||||
|
||||
1. Use the correct filename prefix for your section
|
||||
2. Follow the `_template.md` structure
|
||||
3. Include clear bad/good examples with explanations
|
||||
4. Add appropriate tags
|
||||
5. Run `pnpm build` to regenerate AGENTS.md and test-cases.json
|
||||
6. Rules are automatically sorted by title - no need to manage numbers!
|
||||
|
||||
## Acknowledgments
|
||||
|
||||
Originally created by [@shuding](https://x.com/shuding) at [Vercel](https://vercel.com).
|
||||
@@ -0,0 +1,159 @@
|
||||
---
|
||||
name: ext-react-best-practices
|
||||
description: React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React/Next.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.
|
||||
license: MIT
|
||||
metadata:
|
||||
author: vercel
|
||||
version: "1.0.0"
|
||||
---
|
||||
|
||||
> **Project rules win.** Vendored by @intecion/ipal-kit as guidance. When this skill conflicts with
|
||||
> `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md`, the project's `AGENTS.md` or `DESIGN.md`, those win:
|
||||
> ipal-kit features first (the `ipal-reference` skill), Payload 3 + Next 16 App Router, data from Server Components
|
||||
> through Payload / `@/lib/content`, every visible text from the CMS, design values from `DESIGN.md` tokens.
|
||||
> Never add a dependency this skill suggests without the owner's decision.
|
||||
>
|
||||
> **Data fetching:** ignore `client-swr-dedup` and any advice to add `swr`, `better-all`, `lru-cache` or another
|
||||
> client-fetch library. Fetch in Server Components with the Payload Local API / `@/lib/content` helpers (React `cache()`).
|
||||
|
||||
|
||||
# Vercel React Best Practices
|
||||
|
||||
Comprehensive performance optimization guide for React and Next.js applications, maintained by Vercel. Contains 70 rules across 8 categories, prioritized by impact to guide automated refactoring and code generation.
|
||||
|
||||
## When to Apply
|
||||
|
||||
Reference these guidelines when:
|
||||
- Writing new React components or Next.js pages
|
||||
- Implementing data fetching (client or server-side)
|
||||
- Reviewing code for performance issues
|
||||
- Refactoring existing React/Next.js code
|
||||
- Optimizing bundle size or load times
|
||||
|
||||
## Rule Categories by Priority
|
||||
|
||||
| Priority | Category | Impact | Prefix |
|
||||
|----------|----------|--------|--------|
|
||||
| 1 | Eliminating Waterfalls | CRITICAL | `async-` |
|
||||
| 2 | Bundle Size Optimization | CRITICAL | `bundle-` |
|
||||
| 3 | Server-Side Performance | HIGH | `server-` |
|
||||
| 4 | Client-Side Data Fetching | MEDIUM-HIGH | `client-` |
|
||||
| 5 | Re-render Optimization | MEDIUM | `rerender-` |
|
||||
| 6 | Rendering Performance | MEDIUM | `rendering-` |
|
||||
| 7 | JavaScript Performance | LOW-MEDIUM | `js-` |
|
||||
| 8 | Advanced Patterns | LOW | `advanced-` |
|
||||
|
||||
## Quick Reference
|
||||
|
||||
### 1. Eliminating Waterfalls (CRITICAL)
|
||||
|
||||
- `async-cheap-condition-before-await` - Check cheap sync conditions before awaiting flags or remote values
|
||||
- `async-defer-await` - Move await into branches where actually used
|
||||
- `async-parallel` - Use Promise.all() for independent operations
|
||||
- `async-dependencies` - Use better-all for partial dependencies
|
||||
- `async-api-routes` - Start promises early, await late in API routes
|
||||
- `async-suspense-boundaries` - Use Suspense to stream content
|
||||
|
||||
### 2. Bundle Size Optimization (CRITICAL)
|
||||
|
||||
- `bundle-barrel-imports` - Import directly, avoid barrel files
|
||||
- `bundle-analyzable-paths` - Prefer statically analyzable import and file-system paths to avoid broad bundles and traces
|
||||
- `bundle-dynamic-imports` - Use next/dynamic for heavy components
|
||||
- `bundle-defer-third-party` - Load analytics/logging after hydration
|
||||
- `bundle-conditional` - Load modules only when feature is activated
|
||||
- `bundle-preload` - Preload on hover/focus for perceived speed
|
||||
|
||||
### 3. Server-Side Performance (HIGH)
|
||||
|
||||
- `server-auth-actions` - Authenticate server actions like API routes
|
||||
- `server-cache-react` - Use React.cache() for per-request deduplication
|
||||
- `server-cache-lru` - Use LRU cache for cross-request caching
|
||||
- `server-dedup-props` - Avoid duplicate serialization in RSC props
|
||||
- `server-hoist-static-io` - Hoist static I/O (fonts, logos) to module level
|
||||
- `server-no-shared-module-state` - Avoid module-level mutable request state in RSC/SSR
|
||||
- `server-serialization` - Minimize data passed to client components
|
||||
- `server-parallel-fetching` - Restructure components to parallelize fetches
|
||||
- `server-parallel-nested-fetching` - Chain nested fetches per item in Promise.all
|
||||
- `server-after-nonblocking` - Use after() for non-blocking operations
|
||||
|
||||
### 4. Client-Side Data Fetching (MEDIUM-HIGH)
|
||||
|
||||
- `client-swr-dedup` - Use SWR for automatic request deduplication
|
||||
- `client-event-listeners` - Deduplicate global event listeners
|
||||
- `client-passive-event-listeners` - Use passive listeners for scroll
|
||||
- `client-localstorage-schema` - Version and minimize localStorage data
|
||||
|
||||
### 5. Re-render Optimization (MEDIUM)
|
||||
|
||||
- `rerender-defer-reads` - Don't subscribe to state only used in callbacks
|
||||
- `rerender-memo` - Extract expensive work into memoized components
|
||||
- `rerender-memo-with-default-value` - Hoist default non-primitive props
|
||||
- `rerender-dependencies` - Use primitive dependencies in effects
|
||||
- `rerender-derived-state` - Subscribe to derived booleans, not raw values
|
||||
- `rerender-derived-state-no-effect` - Derive state during render, not effects
|
||||
- `rerender-functional-setstate` - Use functional setState for stable callbacks
|
||||
- `rerender-lazy-state-init` - Pass function to useState for expensive values
|
||||
- `rerender-simple-expression-in-memo` - Avoid memo for simple primitives
|
||||
- `rerender-split-combined-hooks` - Split hooks with independent dependencies
|
||||
- `rerender-move-effect-to-event` - Put interaction logic in event handlers
|
||||
- `rerender-transitions` - Use startTransition for non-urgent updates
|
||||
- `rerender-use-deferred-value` - Defer expensive renders to keep input responsive
|
||||
- `rerender-use-ref-transient-values` - Use refs for transient frequent values
|
||||
- `rerender-no-inline-components` - Don't define components inside components
|
||||
|
||||
### 6. Rendering Performance (MEDIUM)
|
||||
|
||||
- `rendering-animate-svg-wrapper` - Animate div wrapper, not SVG element
|
||||
- `rendering-content-visibility` - Use content-visibility for long lists
|
||||
- `rendering-hoist-jsx` - Extract static JSX outside components
|
||||
- `rendering-svg-precision` - Reduce SVG coordinate precision
|
||||
- `rendering-hydration-no-flicker` - Use inline script for client-only data
|
||||
- `rendering-hydration-suppress-warning` - Suppress expected mismatches
|
||||
- `rendering-activity` - Use Activity component for show/hide
|
||||
- `rendering-conditional-render` - Use ternary, not && for conditionals
|
||||
- `rendering-usetransition-loading` - Prefer useTransition for loading state
|
||||
- `rendering-resource-hints` - Use React DOM resource hints for preloading
|
||||
- `rendering-script-defer-async` - Use defer or async on script tags
|
||||
|
||||
### 7. JavaScript Performance (LOW-MEDIUM)
|
||||
|
||||
- `js-batch-dom-css` - Group CSS changes via classes or cssText
|
||||
- `js-index-maps` - Build Map for repeated lookups
|
||||
- `js-cache-property-access` - Cache object properties in loops
|
||||
- `js-cache-function-results` - Cache function results in module-level Map
|
||||
- `js-cache-storage` - Cache localStorage/sessionStorage reads
|
||||
- `js-combine-iterations` - Combine multiple filter/map into one loop
|
||||
- `js-length-check-first` - Check array length before expensive comparison
|
||||
- `js-early-exit` - Return early from functions
|
||||
- `js-hoist-regexp` - Hoist RegExp creation outside loops
|
||||
- `js-min-max-loop` - Use loop for min/max instead of sort
|
||||
- `js-set-map-lookups` - Use Set/Map for O(1) lookups
|
||||
- `js-tosorted-immutable` - Use toSorted() for immutability
|
||||
- `js-flatmap-filter` - Use flatMap to map and filter in one pass
|
||||
- `js-request-idle-callback` - Defer non-critical work to browser idle time
|
||||
|
||||
### 8. Advanced Patterns (LOW)
|
||||
|
||||
- `advanced-effect-event-deps` - Don't put `useEffectEvent` results in effect deps
|
||||
- `advanced-event-handler-refs` - Store event handlers in refs
|
||||
- `advanced-init-once` - Initialize app once per app load
|
||||
- `advanced-use-latest` - useLatest for stable callback refs
|
||||
|
||||
## How to Use
|
||||
|
||||
Read individual rule files for detailed explanations and code examples:
|
||||
|
||||
```
|
||||
rules/async-parallel.md
|
||||
rules/bundle-barrel-imports.md
|
||||
```
|
||||
|
||||
Each rule file contains:
|
||||
- Brief explanation of why it matters
|
||||
- Incorrect code example with explanation
|
||||
- Correct code example with explanation
|
||||
- Additional context and references
|
||||
|
||||
## Full Compiled Document
|
||||
|
||||
For the complete guide with all rules expanded: `AGENTS.md`
|
||||
@@ -0,0 +1,14 @@
|
||||
# ext-react-best-practices
|
||||
|
||||
Vendored by @intecion/ipal-kit (`ipal-skills --external`). Do not edit — regenerate with
|
||||
`scripts/vendor-external-skills.mjs` in the ipal-kit repository.
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Publisher | Vercel |
|
||||
| Source | https://github.com/vercel-labs/agent-skills/tree/1a2c79d4e6c4a2283dc2c614b6538cbe1ed5ca62/skills/react-best-practices |
|
||||
| Commit | `1a2c79d4e6c4a2283dc2c614b6538cbe1ed5ca62` |
|
||||
| Licence | MIT (see the LICENSE file in this folder) |
|
||||
|
||||
Changes from the upstream text: the `name` in the SKILL.md frontmatter is `ext-react-best-practices`, and an
|
||||
override note (project rules win) is inserted after the frontmatter. Nothing else is changed.
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"version": "1.0.0",
|
||||
"organization": "Vercel Engineering",
|
||||
"date": "January 2026",
|
||||
"abstract": "Comprehensive performance optimization guide for React and Next.js applications, designed for AI agents and LLMs. Contains 40+ rules across 8 categories, prioritized by impact from critical (eliminating waterfalls, reducing bundle size) to incremental (advanced patterns). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics to guide automated refactoring and code generation.",
|
||||
"references": [
|
||||
"https://react.dev",
|
||||
"https://nextjs.org",
|
||||
"https://swr.vercel.app",
|
||||
"https://github.com/shuding/better-all",
|
||||
"https://github.com/isaacs/node-lru-cache",
|
||||
"https://vercel.com/blog/how-we-optimized-package-imports-in-next-js",
|
||||
"https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
# Sections
|
||||
|
||||
This file defines all sections, their ordering, impact levels, and descriptions.
|
||||
The section ID (in parentheses) is the filename prefix used to group rules.
|
||||
|
||||
---
|
||||
|
||||
## 1. Eliminating Waterfalls (async)
|
||||
|
||||
**Impact:** CRITICAL
|
||||
**Description:** Waterfalls are the #1 performance killer. Each sequential await adds full network latency. Eliminating them yields the largest gains.
|
||||
|
||||
## 2. Bundle Size Optimization (bundle)
|
||||
|
||||
**Impact:** CRITICAL
|
||||
**Description:** Reducing initial bundle size improves Time to Interactive and Largest Contentful Paint.
|
||||
|
||||
## 3. Server-Side Performance (server)
|
||||
|
||||
**Impact:** HIGH
|
||||
**Description:** Optimizing server-side rendering and data fetching eliminates server-side waterfalls and reduces response times.
|
||||
|
||||
## 4. Client-Side Data Fetching (client)
|
||||
|
||||
**Impact:** MEDIUM-HIGH
|
||||
**Description:** Automatic deduplication and efficient data fetching patterns reduce redundant network requests.
|
||||
|
||||
## 5. Re-render Optimization (rerender)
|
||||
|
||||
**Impact:** MEDIUM
|
||||
**Description:** Reducing unnecessary re-renders minimizes wasted computation and improves UI responsiveness.
|
||||
|
||||
## 6. Rendering Performance (rendering)
|
||||
|
||||
**Impact:** MEDIUM
|
||||
**Description:** Optimizing the rendering process reduces the work the browser needs to do.
|
||||
|
||||
## 7. JavaScript Performance (js)
|
||||
|
||||
**Impact:** LOW-MEDIUM
|
||||
**Description:** Micro-optimizations for hot paths can add up to meaningful improvements.
|
||||
|
||||
## 8. Advanced Patterns (advanced)
|
||||
|
||||
**Impact:** LOW
|
||||
**Description:** Advanced patterns for specific cases that require careful implementation.
|
||||
@@ -0,0 +1,28 @@
|
||||
---
|
||||
title: Rule Title Here
|
||||
impact: MEDIUM
|
||||
impactDescription: Optional description of impact (e.g., "20-50% improvement")
|
||||
tags: tag1, tag2
|
||||
---
|
||||
|
||||
## Rule Title Here
|
||||
|
||||
**Impact: MEDIUM (optional impact description)**
|
||||
|
||||
Brief explanation of the rule and why it matters. This should be clear and concise, explaining the performance implications.
|
||||
|
||||
**Incorrect (description of what's wrong):**
|
||||
|
||||
```typescript
|
||||
// Bad code example here
|
||||
const bad = example()
|
||||
```
|
||||
|
||||
**Correct (description of what's right):**
|
||||
|
||||
```typescript
|
||||
// Good code example here
|
||||
const good = example()
|
||||
```
|
||||
|
||||
Reference: [Link to documentation or resource](https://example.com)
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
---
|
||||
title: Do Not Put Effect Events in Dependency Arrays
|
||||
impact: LOW
|
||||
impactDescription: avoids unnecessary effect re-runs and lint errors
|
||||
tags: advanced, hooks, useEffectEvent, dependencies, effects
|
||||
---
|
||||
|
||||
## Do Not Put Effect Events in Dependency Arrays
|
||||
|
||||
Effect Event functions do not have a stable identity. Their identity intentionally changes on every render. Do not include the function returned by `useEffectEvent` in a `useEffect` dependency array. Keep the actual reactive values as dependencies and call the Effect Event from inside the effect body or subscriptions created by that effect.
|
||||
|
||||
**Incorrect (Effect Event added as a dependency):**
|
||||
|
||||
```tsx
|
||||
import { useEffect, useEffectEvent } from 'react'
|
||||
|
||||
function ChatRoom({ roomId, onConnected }: {
|
||||
roomId: string
|
||||
onConnected: () => void
|
||||
}) {
|
||||
const handleConnected = useEffectEvent(onConnected)
|
||||
|
||||
useEffect(() => {
|
||||
const connection = createConnection(roomId)
|
||||
connection.on('connected', handleConnected)
|
||||
connection.connect()
|
||||
|
||||
return () => connection.disconnect()
|
||||
}, [roomId, handleConnected])
|
||||
}
|
||||
```
|
||||
|
||||
Including the Effect Event in dependencies makes the effect re-run every render and triggers the React Hooks lint rule.
|
||||
|
||||
**Correct (depend on reactive values, not the Effect Event):**
|
||||
|
||||
```tsx
|
||||
import { useEffect, useEffectEvent } from 'react'
|
||||
|
||||
function ChatRoom({ roomId, onConnected }: {
|
||||
roomId: string
|
||||
onConnected: () => void
|
||||
}) {
|
||||
const handleConnected = useEffectEvent(onConnected)
|
||||
|
||||
useEffect(() => {
|
||||
const connection = createConnection(roomId)
|
||||
connection.on('connected', handleConnected)
|
||||
connection.connect()
|
||||
|
||||
return () => connection.disconnect()
|
||||
}, [roomId])
|
||||
}
|
||||
```
|
||||
|
||||
Reference: [React useEffectEvent: Effect Event in deps](https://react.dev/reference/react/useEffectEvent#effect-event-in-deps)
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
---
|
||||
title: Store Event Handlers in Refs
|
||||
impact: LOW
|
||||
impactDescription: stable subscriptions
|
||||
tags: advanced, hooks, refs, event-handlers, optimization
|
||||
---
|
||||
|
||||
## Store Event Handlers in Refs
|
||||
|
||||
Store callbacks in refs when used in effects that shouldn't re-subscribe on callback changes.
|
||||
|
||||
**Incorrect (re-subscribes on every render):**
|
||||
|
||||
```tsx
|
||||
function useWindowEvent(event: string, handler: (e) => void) {
|
||||
useEffect(() => {
|
||||
window.addEventListener(event, handler)
|
||||
return () => window.removeEventListener(event, handler)
|
||||
}, [event, handler])
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (stable subscription):**
|
||||
|
||||
```tsx
|
||||
function useWindowEvent(event: string, handler: (e) => void) {
|
||||
const handlerRef = useRef(handler)
|
||||
useEffect(() => {
|
||||
handlerRef.current = handler
|
||||
}, [handler])
|
||||
|
||||
useEffect(() => {
|
||||
const listener = (e) => handlerRef.current(e)
|
||||
window.addEventListener(event, listener)
|
||||
return () => window.removeEventListener(event, listener)
|
||||
}, [event])
|
||||
}
|
||||
```
|
||||
|
||||
**Alternative: use `useEffectEvent` if you're on latest React:**
|
||||
|
||||
```tsx
|
||||
import { useEffectEvent } from 'react'
|
||||
|
||||
function useWindowEvent(event: string, handler: (e) => void) {
|
||||
const onEvent = useEffectEvent(handler)
|
||||
|
||||
useEffect(() => {
|
||||
window.addEventListener(event, onEvent)
|
||||
return () => window.removeEventListener(event, onEvent)
|
||||
}, [event])
|
||||
}
|
||||
```
|
||||
|
||||
`useEffectEvent` provides a cleaner API for the same pattern: it creates a stable function reference that always calls the latest version of the handler.
|
||||
@@ -0,0 +1,42 @@
|
||||
---
|
||||
title: Initialize App Once, Not Per Mount
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: avoids duplicate init in development
|
||||
tags: initialization, useEffect, app-startup, side-effects
|
||||
---
|
||||
|
||||
## Initialize App Once, Not Per Mount
|
||||
|
||||
Do not put app-wide initialization that must run once per app load inside `useEffect([])` of a component. Components can remount and effects will re-run. Use a module-level guard or top-level init in the entry module instead.
|
||||
|
||||
**Incorrect (runs twice in dev, re-runs on remount):**
|
||||
|
||||
```tsx
|
||||
function Comp() {
|
||||
useEffect(() => {
|
||||
loadFromStorage()
|
||||
checkAuthToken()
|
||||
}, [])
|
||||
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (once per app load):**
|
||||
|
||||
```tsx
|
||||
let didInit = false
|
||||
|
||||
function Comp() {
|
||||
useEffect(() => {
|
||||
if (didInit) return
|
||||
didInit = true
|
||||
loadFromStorage()
|
||||
checkAuthToken()
|
||||
}, [])
|
||||
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
Reference: [Initializing the application](https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application)
|
||||
@@ -0,0 +1,39 @@
|
||||
---
|
||||
title: useEffectEvent for Stable Callback Refs
|
||||
impact: LOW
|
||||
impactDescription: prevents effect re-runs
|
||||
tags: advanced, hooks, useEffectEvent, refs, optimization
|
||||
---
|
||||
|
||||
## useEffectEvent for Stable Callback Refs
|
||||
|
||||
Access latest values in callbacks without adding them to dependency arrays. Prevents effect re-runs while avoiding stale closures.
|
||||
|
||||
**Incorrect (effect re-runs on every callback change):**
|
||||
|
||||
```tsx
|
||||
function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
|
||||
const [query, setQuery] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
const timeout = setTimeout(() => onSearch(query), 300)
|
||||
return () => clearTimeout(timeout)
|
||||
}, [query, onSearch])
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (using React's useEffectEvent):**
|
||||
|
||||
```tsx
|
||||
import { useEffectEvent } from 'react';
|
||||
|
||||
function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
|
||||
const [query, setQuery] = useState('')
|
||||
const onSearchEvent = useEffectEvent(onSearch)
|
||||
|
||||
useEffect(() => {
|
||||
const timeout = setTimeout(() => onSearchEvent(query), 300)
|
||||
return () => clearTimeout(timeout)
|
||||
}, [query])
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,38 @@
|
||||
---
|
||||
title: Prevent Waterfall Chains in API Routes
|
||||
impact: CRITICAL
|
||||
impactDescription: 2-10× improvement
|
||||
tags: api-routes, server-actions, waterfalls, parallelization
|
||||
---
|
||||
|
||||
## Prevent Waterfall Chains in API Routes
|
||||
|
||||
In API routes and Server Actions, start independent operations immediately, even if you don't await them yet.
|
||||
|
||||
**Incorrect (config waits for auth, data waits for both):**
|
||||
|
||||
```typescript
|
||||
export async function GET(request: Request) {
|
||||
const session = await auth()
|
||||
const config = await fetchConfig()
|
||||
const data = await fetchData(session.user.id)
|
||||
return Response.json({ data, config })
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (auth and config start immediately):**
|
||||
|
||||
```typescript
|
||||
export async function GET(request: Request) {
|
||||
const sessionPromise = auth()
|
||||
const configPromise = fetchConfig()
|
||||
const session = await sessionPromise
|
||||
const [config, data] = await Promise.all([
|
||||
configPromise,
|
||||
fetchData(session.user.id)
|
||||
])
|
||||
return Response.json({ data, config })
|
||||
}
|
||||
```
|
||||
|
||||
For operations with more complex dependency chains, use `better-all` to automatically maximize parallelism (see Dependency-Based Parallelization).
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
---
|
||||
title: Check Cheap Conditions Before Async Flags
|
||||
impact: HIGH
|
||||
impactDescription: avoids unnecessary async work when a synchronous guard already fails
|
||||
tags: async, await, feature-flags, short-circuit, conditional
|
||||
---
|
||||
|
||||
## Check Cheap Conditions Before Async Flags
|
||||
|
||||
When a branch uses `await` for a flag or remote value and also requires a **cheap synchronous** condition (local props, request metadata, already-loaded state), evaluate the cheap condition **first**. Otherwise you pay for the async call even when the compound condition can never be true.
|
||||
|
||||
This is a specialization of [Defer Await Until Needed](./async-defer-await.md) for `flag && cheapCondition` style checks.
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```typescript
|
||||
const someFlag = await getFlag()
|
||||
|
||||
if (someFlag && someCondition) {
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```typescript
|
||||
if (someCondition) {
|
||||
const someFlag = await getFlag()
|
||||
if (someFlag) {
|
||||
// ...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This matters when `getFlag` hits the network, a feature-flag service, or `React.cache` / DB work: skipping it when `someCondition` is false removes that cost on the cold path.
|
||||
|
||||
Keep the original order if `someCondition` is expensive, depends on the flag, or you must run side effects in a fixed order.
|
||||
@@ -0,0 +1,82 @@
|
||||
---
|
||||
title: Defer Await Until Needed
|
||||
impact: HIGH
|
||||
impactDescription: avoids blocking unused code paths
|
||||
tags: async, await, conditional, optimization
|
||||
---
|
||||
|
||||
## Defer Await Until Needed
|
||||
|
||||
Move `await` operations into the branches where they're actually used to avoid blocking code paths that don't need them.
|
||||
|
||||
**Incorrect (blocks both branches):**
|
||||
|
||||
```typescript
|
||||
async function handleRequest(userId: string, skipProcessing: boolean) {
|
||||
const userData = await fetchUserData(userId)
|
||||
|
||||
if (skipProcessing) {
|
||||
// Returns immediately but still waited for userData
|
||||
return { skipped: true }
|
||||
}
|
||||
|
||||
// Only this branch uses userData
|
||||
return processUserData(userData)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (only blocks when needed):**
|
||||
|
||||
```typescript
|
||||
async function handleRequest(userId: string, skipProcessing: boolean) {
|
||||
if (skipProcessing) {
|
||||
// Returns immediately without waiting
|
||||
return { skipped: true }
|
||||
}
|
||||
|
||||
// Fetch only when needed
|
||||
const userData = await fetchUserData(userId)
|
||||
return processUserData(userData)
|
||||
}
|
||||
```
|
||||
|
||||
**Another example (early return optimization):**
|
||||
|
||||
```typescript
|
||||
// Incorrect: always fetches permissions
|
||||
async function updateResource(resourceId: string, userId: string) {
|
||||
const permissions = await fetchPermissions(userId)
|
||||
const resource = await getResource(resourceId)
|
||||
|
||||
if (!resource) {
|
||||
return { error: 'Not found' }
|
||||
}
|
||||
|
||||
if (!permissions.canEdit) {
|
||||
return { error: 'Forbidden' }
|
||||
}
|
||||
|
||||
return await updateResourceData(resource, permissions)
|
||||
}
|
||||
|
||||
// Correct: fetches only when needed
|
||||
async function updateResource(resourceId: string, userId: string) {
|
||||
const resource = await getResource(resourceId)
|
||||
|
||||
if (!resource) {
|
||||
return { error: 'Not found' }
|
||||
}
|
||||
|
||||
const permissions = await fetchPermissions(userId)
|
||||
|
||||
if (!permissions.canEdit) {
|
||||
return { error: 'Forbidden' }
|
||||
}
|
||||
|
||||
return await updateResourceData(resource, permissions)
|
||||
}
|
||||
```
|
||||
|
||||
This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive.
|
||||
|
||||
For `await getFlag()` combined with a cheap synchronous guard (`flag && someCondition`), see [Check Cheap Conditions Before Async Flags](./async-cheap-condition-before-await.md).
|
||||
@@ -0,0 +1,51 @@
|
||||
---
|
||||
title: Dependency-Based Parallelization
|
||||
impact: CRITICAL
|
||||
impactDescription: 2-10× improvement
|
||||
tags: async, parallelization, dependencies, better-all
|
||||
---
|
||||
|
||||
## Dependency-Based Parallelization
|
||||
|
||||
For operations with partial dependencies, use `better-all` to maximize parallelism. It automatically starts each task at the earliest possible moment.
|
||||
|
||||
**Incorrect (profile waits for config unnecessarily):**
|
||||
|
||||
```typescript
|
||||
const [user, config] = await Promise.all([
|
||||
fetchUser(),
|
||||
fetchConfig()
|
||||
])
|
||||
const profile = await fetchProfile(user.id)
|
||||
```
|
||||
|
||||
**Correct (config and profile run in parallel):**
|
||||
|
||||
```typescript
|
||||
import { all } from 'better-all'
|
||||
|
||||
const { user, config, profile } = await all({
|
||||
async user() { return fetchUser() },
|
||||
async config() { return fetchConfig() },
|
||||
async profile() {
|
||||
return fetchProfile((await this.$.user).id)
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
**Alternative without extra dependencies:**
|
||||
|
||||
We can also create all the promises first, and do `Promise.all()` at the end.
|
||||
|
||||
```typescript
|
||||
const userPromise = fetchUser()
|
||||
const profilePromise = userPromise.then(user => fetchProfile(user.id))
|
||||
|
||||
const [user, config, profile] = await Promise.all([
|
||||
userPromise,
|
||||
fetchConfig(),
|
||||
profilePromise
|
||||
])
|
||||
```
|
||||
|
||||
Reference: [https://github.com/shuding/better-all](https://github.com/shuding/better-all)
|
||||
@@ -0,0 +1,28 @@
|
||||
---
|
||||
title: Promise.all() for Independent Operations
|
||||
impact: CRITICAL
|
||||
impactDescription: 2-10× improvement
|
||||
tags: async, parallelization, promises, waterfalls
|
||||
---
|
||||
|
||||
## Promise.all() for Independent Operations
|
||||
|
||||
When async operations have no interdependencies, execute them concurrently using `Promise.all()`.
|
||||
|
||||
**Incorrect (sequential execution, 3 round trips):**
|
||||
|
||||
```typescript
|
||||
const user = await fetchUser()
|
||||
const posts = await fetchPosts()
|
||||
const comments = await fetchComments()
|
||||
```
|
||||
|
||||
**Correct (parallel execution, 1 round trip):**
|
||||
|
||||
```typescript
|
||||
const [user, posts, comments] = await Promise.all([
|
||||
fetchUser(),
|
||||
fetchPosts(),
|
||||
fetchComments()
|
||||
])
|
||||
```
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
---
|
||||
title: Strategic Suspense Boundaries
|
||||
impact: HIGH
|
||||
impactDescription: faster initial paint
|
||||
tags: async, suspense, streaming, layout-shift
|
||||
---
|
||||
|
||||
## Strategic Suspense Boundaries
|
||||
|
||||
Instead of awaiting data in async components before returning JSX, use Suspense boundaries to show the wrapper UI faster while data loads.
|
||||
|
||||
**Incorrect (wrapper blocked by data fetching):**
|
||||
|
||||
```tsx
|
||||
async function Page() {
|
||||
const data = await fetchData() // Blocks entire page
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div>Sidebar</div>
|
||||
<div>Header</div>
|
||||
<div>
|
||||
<DataDisplay data={data} />
|
||||
</div>
|
||||
<div>Footer</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
The entire layout waits for data even though only the middle section needs it.
|
||||
|
||||
**Correct (wrapper shows immediately, data streams in):**
|
||||
|
||||
```tsx
|
||||
function Page() {
|
||||
return (
|
||||
<div>
|
||||
<div>Sidebar</div>
|
||||
<div>Header</div>
|
||||
<div>
|
||||
<Suspense fallback={<Skeleton />}>
|
||||
<DataDisplay />
|
||||
</Suspense>
|
||||
</div>
|
||||
<div>Footer</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
async function DataDisplay() {
|
||||
const data = await fetchData() // Only blocks this component
|
||||
return <div>{data.content}</div>
|
||||
}
|
||||
```
|
||||
|
||||
Sidebar, Header, and Footer render immediately. Only DataDisplay waits for data.
|
||||
|
||||
**Alternative (share promise across components):**
|
||||
|
||||
```tsx
|
||||
function Page() {
|
||||
// Start fetch immediately, but don't await
|
||||
const dataPromise = fetchData()
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div>Sidebar</div>
|
||||
<div>Header</div>
|
||||
<Suspense fallback={<Skeleton />}>
|
||||
<DataDisplay dataPromise={dataPromise} />
|
||||
<DataSummary dataPromise={dataPromise} />
|
||||
</Suspense>
|
||||
<div>Footer</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function DataDisplay({ dataPromise }: { dataPromise: Promise<Data> }) {
|
||||
const data = use(dataPromise) // Unwraps the promise
|
||||
return <div>{data.content}</div>
|
||||
}
|
||||
|
||||
function DataSummary({ dataPromise }: { dataPromise: Promise<Data> }) {
|
||||
const data = use(dataPromise) // Reuses the same promise
|
||||
return <div>{data.summary}</div>
|
||||
}
|
||||
```
|
||||
|
||||
Both components share the same promise, so only one fetch occurs. Layout renders immediately while both components wait together.
|
||||
|
||||
**When NOT to use this pattern:**
|
||||
|
||||
- Critical data needed for layout decisions (affects positioning)
|
||||
- SEO-critical content above the fold
|
||||
- Small, fast queries where suspense overhead isn't worth it
|
||||
- When you want to avoid layout shift (loading → content jump)
|
||||
|
||||
**Trade-off:** Faster initial paint vs potential layout shift. Choose based on your UX priorities.
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
---
|
||||
title: Prefer Statically Analyzable Paths
|
||||
impact: HIGH
|
||||
impactDescription: avoids accidental broad bundles and file traces
|
||||
tags: bundle, nextjs, vite, webpack, rollup, esbuild, path
|
||||
---
|
||||
|
||||
## Prefer Statically Analyzable Paths
|
||||
|
||||
Build tools work best when import and file-system paths are obvious at build time. If you hide the real path inside a variable or compose it too dynamically, the tool either has to include a broad set of possible files, warn that it cannot analyze the import, or widen file tracing to stay safe.
|
||||
|
||||
Prefer explicit maps or literal paths so the set of reachable files stays narrow and predictable. This is the same rule whether you are choosing modules with `import()` or reading files in server/build code.
|
||||
|
||||
When analysis becomes too broad, the cost is real:
|
||||
- Larger server bundles
|
||||
- Slower builds
|
||||
- Worse cold starts
|
||||
- More memory use
|
||||
|
||||
### Import Paths
|
||||
|
||||
**Incorrect (the bundler cannot tell what may be imported):**
|
||||
|
||||
```ts
|
||||
const PAGE_MODULES = {
|
||||
home: './pages/home',
|
||||
settings: './pages/settings',
|
||||
} as const
|
||||
|
||||
const Page = await import(PAGE_MODULES[pageName])
|
||||
```
|
||||
|
||||
**Correct (use an explicit map of allowed modules):**
|
||||
|
||||
```ts
|
||||
const PAGE_MODULES = {
|
||||
home: () => import('./pages/home'),
|
||||
settings: () => import('./pages/settings'),
|
||||
} as const
|
||||
|
||||
const Page = await PAGE_MODULES[pageName]()
|
||||
```
|
||||
|
||||
### File-System Paths
|
||||
|
||||
**Incorrect (a 2-value enum still hides the final path from static analysis):**
|
||||
|
||||
```ts
|
||||
const baseDir = path.join(process.cwd(), 'content/' + contentKind)
|
||||
```
|
||||
|
||||
**Correct (make each final path literal at the callsite):**
|
||||
|
||||
```ts
|
||||
const baseDir =
|
||||
kind === ContentKind.Blog
|
||||
? path.join(process.cwd(), 'content/blog')
|
||||
: path.join(process.cwd(), 'content/docs')
|
||||
```
|
||||
|
||||
In Next.js server code, this matters for output file tracing too. `path.join(process.cwd(), someVar)` can widen the traced file set because Next.js statically analyze `import`, `require`, and `fs` usage.
|
||||
|
||||
Reference: [Next.js output](https://nextjs.org/docs/app/api-reference/config/next-config-js/output), [Next.js dynamic imports](https://nextjs.org/learn/seo/dynamic-imports), [Vite features](https://vite.dev/guide/features.html), [esbuild API](https://esbuild.github.io/api/), [Rollup dynamic import vars](https://www.npmjs.com/package/@rollup/plugin-dynamic-import-vars), [Webpack dependency management](https://webpack.js.org/guides/dependency-management/)
|
||||
@@ -0,0 +1,60 @@
|
||||
---
|
||||
title: Avoid Barrel File Imports
|
||||
impact: CRITICAL
|
||||
impactDescription: 200-800ms import cost, slow builds
|
||||
tags: bundle, imports, tree-shaking, barrel-files, performance
|
||||
---
|
||||
|
||||
## Avoid Barrel File Imports
|
||||
|
||||
Import directly from source files instead of barrel files to avoid loading thousands of unused modules. **Barrel files** are entry points that re-export multiple modules (e.g., `index.js` that does `export * from './module'`).
|
||||
|
||||
Popular icon and component libraries can have **up to 10,000 re-exports** in their entry file. For many React packages, **it takes 200-800ms just to import them**, affecting both development speed and production cold starts.
|
||||
|
||||
**Why tree-shaking doesn't help:** When a library is marked as external (not bundled), the bundler can't optimize it. If you bundle it to enable tree-shaking, builds become substantially slower analyzing the entire module graph.
|
||||
|
||||
**Incorrect (imports entire library):**
|
||||
|
||||
```tsx
|
||||
import { Check, X, Menu } from 'lucide-react'
|
||||
// Loads 1,583 modules, takes ~2.8s extra in dev
|
||||
// Runtime cost: 200-800ms on every cold start
|
||||
|
||||
import { Button, TextField } from '@mui/material'
|
||||
// Loads 2,225 modules, takes ~4.2s extra in dev
|
||||
```
|
||||
|
||||
**Correct - Next.js 13.5+ (recommended):**
|
||||
|
||||
```js
|
||||
// next.config.js - automatically optimizes barrel imports at build time
|
||||
module.exports = {
|
||||
experimental: {
|
||||
optimizePackageImports: ['lucide-react', '@mui/material']
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```tsx
|
||||
// Keep the standard imports - Next.js transforms them to direct imports
|
||||
import { Check, X, Menu } from 'lucide-react'
|
||||
// Full TypeScript support, no manual path wrangling
|
||||
```
|
||||
|
||||
This is the recommended approach because it preserves TypeScript type safety and editor autocompletion while still eliminating the barrel import cost.
|
||||
|
||||
**Correct - Direct imports (non-Next.js projects):**
|
||||
|
||||
```tsx
|
||||
import Button from '@mui/material/Button'
|
||||
import TextField from '@mui/material/TextField'
|
||||
// Loads only what you use
|
||||
```
|
||||
|
||||
> **TypeScript warning:** Some libraries (notably `lucide-react`) don't ship `.d.ts` files for their deep import paths. Importing from `lucide-react/dist/esm/icons/check` resolves to an implicit `any` type, causing errors under `strict` or `noImplicitAny`. Prefer `optimizePackageImports` when available, or verify the library exports types for its subpaths before using direct imports.
|
||||
|
||||
These optimizations provide 15-70% faster dev boot, 28% faster builds, 40% faster cold starts, and significantly faster HMR.
|
||||
|
||||
Libraries commonly affected: `lucide-react`, `@mui/material`, `@mui/icons-material`, `@tabler/icons-react`, `react-icons`, `@headlessui/react`, `@radix-ui/react-*`, `lodash`, `ramda`, `date-fns`, `rxjs`, `react-use`.
|
||||
|
||||
Reference: [How we optimized package imports in Next.js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js)
|
||||
@@ -0,0 +1,31 @@
|
||||
---
|
||||
title: Conditional Module Loading
|
||||
impact: HIGH
|
||||
impactDescription: loads large data only when needed
|
||||
tags: bundle, conditional-loading, lazy-loading
|
||||
---
|
||||
|
||||
## Conditional Module Loading
|
||||
|
||||
Load large data or modules only when a feature is activated.
|
||||
|
||||
**Example (lazy-load animation frames):**
|
||||
|
||||
```tsx
|
||||
function AnimationPlayer({ enabled, setEnabled }: { enabled: boolean; setEnabled: React.Dispatch<React.SetStateAction<boolean>> }) {
|
||||
const [frames, setFrames] = useState<Frame[] | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (enabled && !frames && typeof window !== 'undefined') {
|
||||
import('./animation-frames.js')
|
||||
.then(mod => setFrames(mod.frames))
|
||||
.catch(() => setEnabled(false))
|
||||
}
|
||||
}, [enabled, frames, setEnabled])
|
||||
|
||||
if (!frames) return <Skeleton />
|
||||
return <Canvas frames={frames} />
|
||||
}
|
||||
```
|
||||
|
||||
The `typeof window !== 'undefined'` check prevents bundling this module for SSR, optimizing server bundle size and build speed.
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
---
|
||||
title: Defer Non-Critical Third-Party Libraries
|
||||
impact: MEDIUM
|
||||
impactDescription: loads after hydration
|
||||
tags: bundle, third-party, analytics, defer
|
||||
---
|
||||
|
||||
## Defer Non-Critical Third-Party Libraries
|
||||
|
||||
Analytics, logging, and error tracking don't block user interaction. Load them after hydration.
|
||||
|
||||
**Incorrect (blocks initial bundle):**
|
||||
|
||||
```tsx
|
||||
import { Analytics } from '@vercel/analytics/react'
|
||||
|
||||
export default function RootLayout({ children }) {
|
||||
return (
|
||||
<html>
|
||||
<body>
|
||||
{children}
|
||||
<Analytics />
|
||||
</body>
|
||||
</html>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (loads after hydration):**
|
||||
|
||||
```tsx
|
||||
import dynamic from 'next/dynamic'
|
||||
|
||||
const Analytics = dynamic(
|
||||
() => import('@vercel/analytics/react').then(m => m.Analytics),
|
||||
{ ssr: false }
|
||||
)
|
||||
|
||||
export default function RootLayout({ children }) {
|
||||
return (
|
||||
<html>
|
||||
<body>
|
||||
{children}
|
||||
<Analytics />
|
||||
</body>
|
||||
</html>
|
||||
)
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,35 @@
|
||||
---
|
||||
title: Dynamic Imports for Heavy Components
|
||||
impact: CRITICAL
|
||||
impactDescription: directly affects TTI and LCP
|
||||
tags: bundle, dynamic-import, code-splitting, next-dynamic
|
||||
---
|
||||
|
||||
## Dynamic Imports for Heavy Components
|
||||
|
||||
Use `next/dynamic` to lazy-load large components not needed on initial render.
|
||||
|
||||
**Incorrect (Monaco bundles with main chunk ~300KB):**
|
||||
|
||||
```tsx
|
||||
import { MonacoEditor } from './monaco-editor'
|
||||
|
||||
function CodePanel({ code }: { code: string }) {
|
||||
return <MonacoEditor value={code} />
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (Monaco loads on demand):**
|
||||
|
||||
```tsx
|
||||
import dynamic from 'next/dynamic'
|
||||
|
||||
const MonacoEditor = dynamic(
|
||||
() => import('./monaco-editor').then(m => m.MonacoEditor),
|
||||
{ ssr: false }
|
||||
)
|
||||
|
||||
function CodePanel({ code }: { code: string }) {
|
||||
return <MonacoEditor value={code} />
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,50 @@
|
||||
---
|
||||
title: Preload Based on User Intent
|
||||
impact: MEDIUM
|
||||
impactDescription: reduces perceived latency
|
||||
tags: bundle, preload, user-intent, hover
|
||||
---
|
||||
|
||||
## Preload Based on User Intent
|
||||
|
||||
Preload heavy bundles before they're needed to reduce perceived latency.
|
||||
|
||||
**Example (preload on hover/focus):**
|
||||
|
||||
```tsx
|
||||
function EditorButton({ onClick }: { onClick: () => void }) {
|
||||
const preload = () => {
|
||||
if (typeof window !== 'undefined') {
|
||||
void import('./monaco-editor')
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<button
|
||||
onMouseEnter={preload}
|
||||
onFocus={preload}
|
||||
onClick={onClick}
|
||||
>
|
||||
Open Editor
|
||||
</button>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Example (preload when feature flag is enabled):**
|
||||
|
||||
```tsx
|
||||
function FlagsProvider({ children, flags }: Props) {
|
||||
useEffect(() => {
|
||||
if (flags.editorEnabled && typeof window !== 'undefined') {
|
||||
void import('./monaco-editor').then(mod => mod.init())
|
||||
}
|
||||
}, [flags.editorEnabled])
|
||||
|
||||
return <FlagsContext.Provider value={flags}>
|
||||
{children}
|
||||
</FlagsContext.Provider>
|
||||
}
|
||||
```
|
||||
|
||||
The `typeof window !== 'undefined'` check prevents bundling preloaded modules for SSR, optimizing server bundle size and build speed.
|
||||
@@ -0,0 +1,74 @@
|
||||
---
|
||||
title: Deduplicate Global Event Listeners
|
||||
impact: LOW
|
||||
impactDescription: single listener for N components
|
||||
tags: client, swr, event-listeners, subscription
|
||||
---
|
||||
|
||||
## Deduplicate Global Event Listeners
|
||||
|
||||
Use `useSWRSubscription()` to share global event listeners across component instances.
|
||||
|
||||
**Incorrect (N instances = N listeners):**
|
||||
|
||||
```tsx
|
||||
function useKeyboardShortcut(key: string, callback: () => void) {
|
||||
useEffect(() => {
|
||||
const handler = (e: KeyboardEvent) => {
|
||||
if (e.metaKey && e.key === key) {
|
||||
callback()
|
||||
}
|
||||
}
|
||||
window.addEventListener('keydown', handler)
|
||||
return () => window.removeEventListener('keydown', handler)
|
||||
}, [key, callback])
|
||||
}
|
||||
```
|
||||
|
||||
When using the `useKeyboardShortcut` hook multiple times, each instance will register a new listener.
|
||||
|
||||
**Correct (N instances = 1 listener):**
|
||||
|
||||
```tsx
|
||||
import useSWRSubscription from 'swr/subscription'
|
||||
|
||||
// Module-level Map to track callbacks per key
|
||||
const keyCallbacks = new Map<string, Set<() => void>>()
|
||||
|
||||
function useKeyboardShortcut(key: string, callback: () => void) {
|
||||
// Register this callback in the Map
|
||||
useEffect(() => {
|
||||
if (!keyCallbacks.has(key)) {
|
||||
keyCallbacks.set(key, new Set())
|
||||
}
|
||||
keyCallbacks.get(key)!.add(callback)
|
||||
|
||||
return () => {
|
||||
const set = keyCallbacks.get(key)
|
||||
if (set) {
|
||||
set.delete(callback)
|
||||
if (set.size === 0) {
|
||||
keyCallbacks.delete(key)
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [key, callback])
|
||||
|
||||
useSWRSubscription('global-keydown', () => {
|
||||
const handler = (e: KeyboardEvent) => {
|
||||
if (e.metaKey && keyCallbacks.has(e.key)) {
|
||||
keyCallbacks.get(e.key)!.forEach(cb => cb())
|
||||
}
|
||||
}
|
||||
window.addEventListener('keydown', handler)
|
||||
return () => window.removeEventListener('keydown', handler)
|
||||
})
|
||||
}
|
||||
|
||||
function Profile() {
|
||||
// Multiple shortcuts will share the same listener
|
||||
useKeyboardShortcut('p', () => { /* ... */ })
|
||||
useKeyboardShortcut('k', () => { /* ... */ })
|
||||
// ...
|
||||
}
|
||||
```
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
---
|
||||
title: Version and Minimize localStorage Data
|
||||
impact: MEDIUM
|
||||
impactDescription: prevents schema conflicts, reduces storage size
|
||||
tags: client, localStorage, storage, versioning, data-minimization
|
||||
---
|
||||
|
||||
## Version and Minimize localStorage Data
|
||||
|
||||
Add version prefix to keys and store only needed fields. Prevents schema conflicts and accidental storage of sensitive data.
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```typescript
|
||||
// No version, stores everything, no error handling
|
||||
localStorage.setItem('userConfig', JSON.stringify(fullUserObject))
|
||||
const data = localStorage.getItem('userConfig')
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```typescript
|
||||
const VERSION = 'v2'
|
||||
|
||||
function saveConfig(config: { theme: string; language: string }) {
|
||||
try {
|
||||
localStorage.setItem(`userConfig:${VERSION}`, JSON.stringify(config))
|
||||
} catch {
|
||||
// Throws in incognito/private browsing, quota exceeded, or disabled
|
||||
}
|
||||
}
|
||||
|
||||
function loadConfig() {
|
||||
try {
|
||||
const data = localStorage.getItem(`userConfig:${VERSION}`)
|
||||
return data ? JSON.parse(data) : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// Migration from v1 to v2
|
||||
function migrate() {
|
||||
try {
|
||||
const v1 = localStorage.getItem('userConfig:v1')
|
||||
if (v1) {
|
||||
const old = JSON.parse(v1)
|
||||
saveConfig({ theme: old.darkMode ? 'dark' : 'light', language: old.lang })
|
||||
localStorage.removeItem('userConfig:v1')
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
```
|
||||
|
||||
**Store minimal fields from server responses:**
|
||||
|
||||
```typescript
|
||||
// User object has 20+ fields, only store what UI needs
|
||||
function cachePrefs(user: FullUser) {
|
||||
try {
|
||||
localStorage.setItem('prefs:v1', JSON.stringify({
|
||||
theme: user.preferences.theme,
|
||||
notifications: user.preferences.notifications
|
||||
}))
|
||||
} catch {}
|
||||
}
|
||||
```
|
||||
|
||||
**Always wrap in try-catch:** `getItem()` and `setItem()` throw in incognito/private browsing (Safari, Firefox), when quota exceeded, or when disabled.
|
||||
|
||||
**Benefits:** Schema evolution via versioning, reduced storage size, prevents storing tokens/PII/internal flags.
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
---
|
||||
title: Use Passive Event Listeners for Scrolling Performance
|
||||
impact: MEDIUM
|
||||
impactDescription: eliminates scroll delay caused by event listeners
|
||||
tags: client, event-listeners, scrolling, performance, touch, wheel
|
||||
---
|
||||
|
||||
## Use Passive Event Listeners for Scrolling Performance
|
||||
|
||||
Add `{ passive: true }` to touch and wheel event listeners to enable immediate scrolling. Browsers normally wait for listeners to finish to check if `preventDefault()` is called, causing scroll delay.
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```typescript
|
||||
useEffect(() => {
|
||||
const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)
|
||||
const handleWheel = (e: WheelEvent) => console.log(e.deltaY)
|
||||
|
||||
document.addEventListener('touchstart', handleTouch)
|
||||
document.addEventListener('wheel', handleWheel)
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('touchstart', handleTouch)
|
||||
document.removeEventListener('wheel', handleWheel)
|
||||
}
|
||||
}, [])
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```typescript
|
||||
useEffect(() => {
|
||||
const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)
|
||||
const handleWheel = (e: WheelEvent) => console.log(e.deltaY)
|
||||
|
||||
document.addEventListener('touchstart', handleTouch, { passive: true })
|
||||
document.addEventListener('wheel', handleWheel, { passive: true })
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('touchstart', handleTouch)
|
||||
document.removeEventListener('wheel', handleWheel)
|
||||
}
|
||||
}, [])
|
||||
```
|
||||
|
||||
**Use passive when:** tracking/analytics, logging, any listener that doesn't call `preventDefault()`.
|
||||
|
||||
**Don't use passive when:** implementing custom swipe gestures, custom zoom controls, or any listener that needs `preventDefault()`.
|
||||
@@ -0,0 +1,56 @@
|
||||
---
|
||||
title: Use SWR for Automatic Deduplication
|
||||
impact: MEDIUM-HIGH
|
||||
impactDescription: automatic deduplication
|
||||
tags: client, swr, deduplication, data-fetching
|
||||
---
|
||||
|
||||
## Use SWR for Automatic Deduplication
|
||||
|
||||
SWR enables request deduplication, caching, and revalidation across component instances.
|
||||
|
||||
**Incorrect (no deduplication, each instance fetches):**
|
||||
|
||||
```tsx
|
||||
function UserList() {
|
||||
const [users, setUsers] = useState([])
|
||||
useEffect(() => {
|
||||
fetch('/api/users')
|
||||
.then(r => r.json())
|
||||
.then(setUsers)
|
||||
}, [])
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (multiple instances share one request):**
|
||||
|
||||
```tsx
|
||||
import useSWR from 'swr'
|
||||
|
||||
function UserList() {
|
||||
const { data: users } = useSWR('/api/users', fetcher)
|
||||
}
|
||||
```
|
||||
|
||||
**For immutable data:**
|
||||
|
||||
```tsx
|
||||
import { useImmutableSWR } from '@/lib/swr'
|
||||
|
||||
function StaticContent() {
|
||||
const { data } = useImmutableSWR('/api/config', fetcher)
|
||||
}
|
||||
```
|
||||
|
||||
**For mutations:**
|
||||
|
||||
```tsx
|
||||
import { useSWRMutation } from 'swr/mutation'
|
||||
|
||||
function UpdateButton() {
|
||||
const { trigger } = useSWRMutation('/api/user', updateUser)
|
||||
return <button onClick={() => trigger()}>Update</button>
|
||||
}
|
||||
```
|
||||
|
||||
Reference: [https://swr.vercel.app](https://swr.vercel.app)
|
||||
@@ -0,0 +1,107 @@
|
||||
---
|
||||
title: Avoid Layout Thrashing
|
||||
impact: MEDIUM
|
||||
impactDescription: prevents forced synchronous layouts and reduces performance bottlenecks
|
||||
tags: javascript, dom, css, performance, reflow, layout-thrashing
|
||||
---
|
||||
|
||||
## Avoid Layout Thrashing
|
||||
|
||||
Avoid interleaving style writes with layout reads. When you read a layout property (like `offsetWidth`, `getBoundingClientRect()`, or `getComputedStyle()`) between style changes, the browser is forced to trigger a synchronous reflow.
|
||||
|
||||
**This is OK (browser batches style changes):**
|
||||
```typescript
|
||||
function updateElementStyles(element: HTMLElement) {
|
||||
// Each line invalidates style, but browser batches the recalculation
|
||||
element.style.width = '100px'
|
||||
element.style.height = '200px'
|
||||
element.style.backgroundColor = 'blue'
|
||||
element.style.border = '1px solid black'
|
||||
}
|
||||
```
|
||||
|
||||
**Incorrect (interleaved reads and writes force reflows):**
|
||||
```typescript
|
||||
function layoutThrashing(element: HTMLElement) {
|
||||
element.style.width = '100px'
|
||||
const width = element.offsetWidth // Forces reflow
|
||||
element.style.height = '200px'
|
||||
const height = element.offsetHeight // Forces another reflow
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (batch writes, then read once):**
|
||||
```typescript
|
||||
function updateElementStyles(element: HTMLElement) {
|
||||
// Batch all writes together
|
||||
element.style.width = '100px'
|
||||
element.style.height = '200px'
|
||||
element.style.backgroundColor = 'blue'
|
||||
element.style.border = '1px solid black'
|
||||
|
||||
// Read after all writes are done (single reflow)
|
||||
const { width, height } = element.getBoundingClientRect()
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (batch reads, then writes):**
|
||||
```typescript
|
||||
function avoidThrashing(element: HTMLElement) {
|
||||
// Read phase - all layout queries first
|
||||
const rect1 = element.getBoundingClientRect()
|
||||
const offsetWidth = element.offsetWidth
|
||||
const offsetHeight = element.offsetHeight
|
||||
|
||||
// Write phase - all style changes after
|
||||
element.style.width = '100px'
|
||||
element.style.height = '200px'
|
||||
}
|
||||
```
|
||||
|
||||
**Better: use CSS classes**
|
||||
```css
|
||||
.highlighted-box {
|
||||
width: 100px;
|
||||
height: 200px;
|
||||
background-color: blue;
|
||||
border: 1px solid black;
|
||||
}
|
||||
```
|
||||
```typescript
|
||||
function updateElementStyles(element: HTMLElement) {
|
||||
element.classList.add('highlighted-box')
|
||||
|
||||
const { width, height } = element.getBoundingClientRect()
|
||||
}
|
||||
```
|
||||
|
||||
**React example:**
|
||||
```tsx
|
||||
// Incorrect: interleaving style changes with layout queries
|
||||
function Box({ isHighlighted }: { isHighlighted: boolean }) {
|
||||
const ref = useRef<HTMLDivElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (ref.current && isHighlighted) {
|
||||
ref.current.style.width = '100px'
|
||||
const width = ref.current.offsetWidth // Forces layout
|
||||
ref.current.style.height = '200px'
|
||||
}
|
||||
}, [isHighlighted])
|
||||
|
||||
return <div ref={ref}>Content</div>
|
||||
}
|
||||
|
||||
// Correct: toggle class
|
||||
function Box({ isHighlighted }: { isHighlighted: boolean }) {
|
||||
return (
|
||||
<div className={isHighlighted ? 'highlighted-box' : ''}>
|
||||
Content
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
Prefer CSS classes over inline styles when possible. CSS files are cached by the browser, and classes provide better separation of concerns and are easier to maintain.
|
||||
|
||||
See [this gist](https://gist.github.com/paulirish/5d52fb081b3570c81e3a) and [CSS Triggers](https://csstriggers.com/) for more information on layout-forcing operations.
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
---
|
||||
title: Cache Repeated Function Calls
|
||||
impact: MEDIUM
|
||||
impactDescription: avoid redundant computation
|
||||
tags: javascript, cache, memoization, performance
|
||||
---
|
||||
|
||||
## Cache Repeated Function Calls
|
||||
|
||||
Use a module-level Map to cache function results when the same function is called repeatedly with the same inputs during render.
|
||||
|
||||
**Incorrect (redundant computation):**
|
||||
|
||||
```typescript
|
||||
function ProjectList({ projects }: { projects: Project[] }) {
|
||||
return (
|
||||
<div>
|
||||
{projects.map(project => {
|
||||
// slugify() called 100+ times for same project names
|
||||
const slug = slugify(project.name)
|
||||
|
||||
return <ProjectCard key={project.id} slug={slug} />
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (cached results):**
|
||||
|
||||
```typescript
|
||||
// Module-level cache
|
||||
const slugifyCache = new Map<string, string>()
|
||||
|
||||
function cachedSlugify(text: string): string {
|
||||
if (slugifyCache.has(text)) {
|
||||
return slugifyCache.get(text)!
|
||||
}
|
||||
const result = slugify(text)
|
||||
slugifyCache.set(text, result)
|
||||
return result
|
||||
}
|
||||
|
||||
function ProjectList({ projects }: { projects: Project[] }) {
|
||||
return (
|
||||
<div>
|
||||
{projects.map(project => {
|
||||
// Computed only once per unique project name
|
||||
const slug = cachedSlugify(project.name)
|
||||
|
||||
return <ProjectCard key={project.id} slug={slug} />
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Simpler pattern for single-value functions:**
|
||||
|
||||
```typescript
|
||||
let isLoggedInCache: boolean | null = null
|
||||
|
||||
function isLoggedIn(): boolean {
|
||||
if (isLoggedInCache !== null) {
|
||||
return isLoggedInCache
|
||||
}
|
||||
|
||||
isLoggedInCache = document.cookie.includes('auth=')
|
||||
return isLoggedInCache
|
||||
}
|
||||
|
||||
// Clear cache when auth changes
|
||||
function onAuthChange() {
|
||||
isLoggedInCache = null
|
||||
}
|
||||
```
|
||||
|
||||
Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
|
||||
|
||||
Reference: [How we made the Vercel Dashboard twice as fast](https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast)
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
---
|
||||
title: Cache Property Access in Loops
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: reduces lookups
|
||||
tags: javascript, loops, optimization, caching
|
||||
---
|
||||
|
||||
## Cache Property Access in Loops
|
||||
|
||||
Cache object property lookups in hot paths.
|
||||
|
||||
**Incorrect (3 lookups × N iterations):**
|
||||
|
||||
```typescript
|
||||
for (let i = 0; i < arr.length; i++) {
|
||||
process(obj.config.settings.value)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (1 lookup total):**
|
||||
|
||||
```typescript
|
||||
const value = obj.config.settings.value
|
||||
const len = arr.length
|
||||
for (let i = 0; i < len; i++) {
|
||||
process(value)
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,70 @@
|
||||
---
|
||||
title: Cache Storage API Calls
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: reduces expensive I/O
|
||||
tags: javascript, localStorage, storage, caching, performance
|
||||
---
|
||||
|
||||
## Cache Storage API Calls
|
||||
|
||||
`localStorage`, `sessionStorage`, and `document.cookie` are synchronous and expensive. Cache reads in memory.
|
||||
|
||||
**Incorrect (reads storage on every call):**
|
||||
|
||||
```typescript
|
||||
function getTheme() {
|
||||
return localStorage.getItem('theme') ?? 'light'
|
||||
}
|
||||
// Called 10 times = 10 storage reads
|
||||
```
|
||||
|
||||
**Correct (Map cache):**
|
||||
|
||||
```typescript
|
||||
const storageCache = new Map<string, string | null>()
|
||||
|
||||
function getLocalStorage(key: string) {
|
||||
if (!storageCache.has(key)) {
|
||||
storageCache.set(key, localStorage.getItem(key))
|
||||
}
|
||||
return storageCache.get(key)
|
||||
}
|
||||
|
||||
function setLocalStorage(key: string, value: string) {
|
||||
localStorage.setItem(key, value)
|
||||
storageCache.set(key, value) // keep cache in sync
|
||||
}
|
||||
```
|
||||
|
||||
Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
|
||||
|
||||
**Cookie caching:**
|
||||
|
||||
```typescript
|
||||
let cookieCache: Record<string, string> | null = null
|
||||
|
||||
function getCookie(name: string) {
|
||||
if (!cookieCache) {
|
||||
cookieCache = Object.fromEntries(
|
||||
document.cookie.split('; ').map(c => c.split('='))
|
||||
)
|
||||
}
|
||||
return cookieCache[name]
|
||||
}
|
||||
```
|
||||
|
||||
**Important (invalidate on external changes):**
|
||||
|
||||
If storage can change externally (another tab, server-set cookies), invalidate cache:
|
||||
|
||||
```typescript
|
||||
window.addEventListener('storage', (e) => {
|
||||
if (e.key) storageCache.delete(e.key)
|
||||
})
|
||||
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
if (document.visibilityState === 'visible') {
|
||||
storageCache.clear()
|
||||
}
|
||||
})
|
||||
```
|
||||
@@ -0,0 +1,32 @@
|
||||
---
|
||||
title: Combine Multiple Array Iterations
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: reduces iterations
|
||||
tags: javascript, arrays, loops, performance
|
||||
---
|
||||
|
||||
## Combine Multiple Array Iterations
|
||||
|
||||
Multiple `.filter()` or `.map()` calls iterate the array multiple times. Combine into one loop.
|
||||
|
||||
**Incorrect (3 iterations):**
|
||||
|
||||
```typescript
|
||||
const admins = users.filter(u => u.isAdmin)
|
||||
const testers = users.filter(u => u.isTester)
|
||||
const inactive = users.filter(u => !u.isActive)
|
||||
```
|
||||
|
||||
**Correct (1 iteration):**
|
||||
|
||||
```typescript
|
||||
const admins: User[] = []
|
||||
const testers: User[] = []
|
||||
const inactive: User[] = []
|
||||
|
||||
for (const user of users) {
|
||||
if (user.isAdmin) admins.push(user)
|
||||
if (user.isTester) testers.push(user)
|
||||
if (!user.isActive) inactive.push(user)
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,50 @@
|
||||
---
|
||||
title: Early Return from Functions
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: avoids unnecessary computation
|
||||
tags: javascript, functions, optimization, early-return
|
||||
---
|
||||
|
||||
## Early Return from Functions
|
||||
|
||||
Return early when result is determined to skip unnecessary processing.
|
||||
|
||||
**Incorrect (processes all items even after finding answer):**
|
||||
|
||||
```typescript
|
||||
function validateUsers(users: User[]) {
|
||||
let hasError = false
|
||||
let errorMessage = ''
|
||||
|
||||
for (const user of users) {
|
||||
if (!user.email) {
|
||||
hasError = true
|
||||
errorMessage = 'Email required'
|
||||
}
|
||||
if (!user.name) {
|
||||
hasError = true
|
||||
errorMessage = 'Name required'
|
||||
}
|
||||
// Continues checking all users even after error found
|
||||
}
|
||||
|
||||
return hasError ? { valid: false, error: errorMessage } : { valid: true }
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (returns immediately on first error):**
|
||||
|
||||
```typescript
|
||||
function validateUsers(users: User[]) {
|
||||
for (const user of users) {
|
||||
if (!user.email) {
|
||||
return { valid: false, error: 'Email required' }
|
||||
}
|
||||
if (!user.name) {
|
||||
return { valid: false, error: 'Name required' }
|
||||
}
|
||||
}
|
||||
|
||||
return { valid: true }
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,60 @@
|
||||
---
|
||||
title: Use flatMap to Map and Filter in One Pass
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: eliminates intermediate array
|
||||
tags: javascript, arrays, flatMap, filter, performance
|
||||
---
|
||||
|
||||
## Use flatMap to Map and Filter in One Pass
|
||||
|
||||
**Impact: LOW-MEDIUM (eliminates intermediate array)**
|
||||
|
||||
Chaining `.map().filter(Boolean)` creates an intermediate array and iterates twice. Use `.flatMap()` to transform and filter in a single pass.
|
||||
|
||||
**Incorrect (2 iterations, intermediate array):**
|
||||
|
||||
```typescript
|
||||
const userNames = users
|
||||
.map(user => user.isActive ? user.name : null)
|
||||
.filter(Boolean)
|
||||
```
|
||||
|
||||
**Correct (1 iteration, no intermediate array):**
|
||||
|
||||
```typescript
|
||||
const userNames = users.flatMap(user =>
|
||||
user.isActive ? [user.name] : []
|
||||
)
|
||||
```
|
||||
|
||||
**More examples:**
|
||||
|
||||
```typescript
|
||||
// Extract valid emails from responses
|
||||
// Before
|
||||
const emails = responses
|
||||
.map(r => r.success ? r.data.email : null)
|
||||
.filter(Boolean)
|
||||
|
||||
// After
|
||||
const emails = responses.flatMap(r =>
|
||||
r.success ? [r.data.email] : []
|
||||
)
|
||||
|
||||
// Parse and filter valid numbers
|
||||
// Before
|
||||
const numbers = strings
|
||||
.map(s => parseInt(s, 10))
|
||||
.filter(n => !isNaN(n))
|
||||
|
||||
// After
|
||||
const numbers = strings.flatMap(s => {
|
||||
const n = parseInt(s, 10)
|
||||
return isNaN(n) ? [] : [n]
|
||||
})
|
||||
```
|
||||
|
||||
**When to use:**
|
||||
- Transforming items while filtering some out
|
||||
- Conditional mapping where some inputs produce no output
|
||||
- Parsing/validating where invalid inputs should be skipped
|
||||
@@ -0,0 +1,45 @@
|
||||
---
|
||||
title: Hoist RegExp Creation
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: avoids recreation
|
||||
tags: javascript, regexp, optimization, memoization
|
||||
---
|
||||
|
||||
## Hoist RegExp Creation
|
||||
|
||||
Don't create RegExp inside render. Hoist to module scope or memoize with `useMemo()`.
|
||||
|
||||
**Incorrect (new RegExp every render):**
|
||||
|
||||
```tsx
|
||||
function Highlighter({ text, query }: Props) {
|
||||
const regex = new RegExp(`(${query})`, 'gi')
|
||||
const parts = text.split(regex)
|
||||
return <>{parts.map((part, i) => ...)}</>
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (memoize or hoist):**
|
||||
|
||||
```tsx
|
||||
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
||||
|
||||
function Highlighter({ text, query }: Props) {
|
||||
const regex = useMemo(
|
||||
() => new RegExp(`(${escapeRegex(query)})`, 'gi'),
|
||||
[query]
|
||||
)
|
||||
const parts = text.split(regex)
|
||||
return <>{parts.map((part, i) => ...)}</>
|
||||
}
|
||||
```
|
||||
|
||||
**Warning (global regex has mutable state):**
|
||||
|
||||
Global regex (`/g`) has mutable `lastIndex` state:
|
||||
|
||||
```typescript
|
||||
const regex = /foo/g
|
||||
regex.test('foo') // true, lastIndex = 3
|
||||
regex.test('foo') // false, lastIndex = 0
|
||||
```
|
||||
@@ -0,0 +1,37 @@
|
||||
---
|
||||
title: Build Index Maps for Repeated Lookups
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: 1M ops to 2K ops
|
||||
tags: javascript, map, indexing, optimization, performance
|
||||
---
|
||||
|
||||
## Build Index Maps for Repeated Lookups
|
||||
|
||||
Multiple `.find()` calls by the same key should use a Map.
|
||||
|
||||
**Incorrect (O(n) per lookup):**
|
||||
|
||||
```typescript
|
||||
function processOrders(orders: Order[], users: User[]) {
|
||||
return orders.map(order => ({
|
||||
...order,
|
||||
user: users.find(u => u.id === order.userId)
|
||||
}))
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (O(1) per lookup):**
|
||||
|
||||
```typescript
|
||||
function processOrders(orders: Order[], users: User[]) {
|
||||
const userById = new Map(users.map(u => [u.id, u]))
|
||||
|
||||
return orders.map(order => ({
|
||||
...order,
|
||||
user: userById.get(order.userId)
|
||||
}))
|
||||
}
|
||||
```
|
||||
|
||||
Build map once (O(n)), then all lookups are O(1).
|
||||
For 1000 orders × 1000 users: 1M ops → 2K ops.
|
||||
@@ -0,0 +1,49 @@
|
||||
---
|
||||
title: Early Length Check for Array Comparisons
|
||||
impact: MEDIUM-HIGH
|
||||
impactDescription: avoids expensive operations when lengths differ
|
||||
tags: javascript, arrays, performance, optimization, comparison
|
||||
---
|
||||
|
||||
## Early Length Check for Array Comparisons
|
||||
|
||||
When comparing arrays with expensive operations (sorting, deep equality, serialization), check lengths first. If lengths differ, the arrays cannot be equal.
|
||||
|
||||
In real-world applications, this optimization is especially valuable when the comparison runs in hot paths (event handlers, render loops).
|
||||
|
||||
**Incorrect (always runs expensive comparison):**
|
||||
|
||||
```typescript
|
||||
function hasChanges(current: string[], original: string[]) {
|
||||
// Always sorts and joins, even when lengths differ
|
||||
return current.sort().join() !== original.sort().join()
|
||||
}
|
||||
```
|
||||
|
||||
Two O(n log n) sorts run even when `current.length` is 5 and `original.length` is 100. There is also overhead of joining the arrays and comparing the strings.
|
||||
|
||||
**Correct (O(1) length check first):**
|
||||
|
||||
```typescript
|
||||
function hasChanges(current: string[], original: string[]) {
|
||||
// Early return if lengths differ
|
||||
if (current.length !== original.length) {
|
||||
return true
|
||||
}
|
||||
// Only sort when lengths match
|
||||
const currentSorted = current.toSorted()
|
||||
const originalSorted = original.toSorted()
|
||||
for (let i = 0; i < currentSorted.length; i++) {
|
||||
if (currentSorted[i] !== originalSorted[i]) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
```
|
||||
|
||||
This new approach is more efficient because:
|
||||
- It avoids the overhead of sorting and joining the arrays when lengths differ
|
||||
- It avoids consuming memory for the joined strings (especially important for large arrays)
|
||||
- It avoids mutating the original arrays
|
||||
- It returns early when a difference is found
|
||||
@@ -0,0 +1,82 @@
|
||||
---
|
||||
title: Use Loop for Min/Max Instead of Sort
|
||||
impact: LOW
|
||||
impactDescription: O(n) instead of O(n log n)
|
||||
tags: javascript, arrays, performance, sorting, algorithms
|
||||
---
|
||||
|
||||
## Use Loop for Min/Max Instead of Sort
|
||||
|
||||
Finding the smallest or largest element only requires a single pass through the array. Sorting is wasteful and slower.
|
||||
|
||||
**Incorrect (O(n log n) - sort to find latest):**
|
||||
|
||||
```typescript
|
||||
interface Project {
|
||||
id: string
|
||||
name: string
|
||||
updatedAt: number
|
||||
}
|
||||
|
||||
function getLatestProject(projects: Project[]) {
|
||||
const sorted = [...projects].sort((a, b) => b.updatedAt - a.updatedAt)
|
||||
return sorted[0]
|
||||
}
|
||||
```
|
||||
|
||||
Sorts the entire array just to find the maximum value.
|
||||
|
||||
**Incorrect (O(n log n) - sort for oldest and newest):**
|
||||
|
||||
```typescript
|
||||
function getOldestAndNewest(projects: Project[]) {
|
||||
const sorted = [...projects].sort((a, b) => a.updatedAt - b.updatedAt)
|
||||
return { oldest: sorted[0], newest: sorted[sorted.length - 1] }
|
||||
}
|
||||
```
|
||||
|
||||
Still sorts unnecessarily when only min/max are needed.
|
||||
|
||||
**Correct (O(n) - single loop):**
|
||||
|
||||
```typescript
|
||||
function getLatestProject(projects: Project[]) {
|
||||
if (projects.length === 0) return null
|
||||
|
||||
let latest = projects[0]
|
||||
|
||||
for (let i = 1; i < projects.length; i++) {
|
||||
if (projects[i].updatedAt > latest.updatedAt) {
|
||||
latest = projects[i]
|
||||
}
|
||||
}
|
||||
|
||||
return latest
|
||||
}
|
||||
|
||||
function getOldestAndNewest(projects: Project[]) {
|
||||
if (projects.length === 0) return { oldest: null, newest: null }
|
||||
|
||||
let oldest = projects[0]
|
||||
let newest = projects[0]
|
||||
|
||||
for (let i = 1; i < projects.length; i++) {
|
||||
if (projects[i].updatedAt < oldest.updatedAt) oldest = projects[i]
|
||||
if (projects[i].updatedAt > newest.updatedAt) newest = projects[i]
|
||||
}
|
||||
|
||||
return { oldest, newest }
|
||||
}
|
||||
```
|
||||
|
||||
Single pass through the array, no copying, no sorting.
|
||||
|
||||
**Alternative (Math.min/Math.max for small arrays):**
|
||||
|
||||
```typescript
|
||||
const numbers = [5, 2, 8, 1, 9]
|
||||
const min = Math.min(...numbers)
|
||||
const max = Math.max(...numbers)
|
||||
```
|
||||
|
||||
This works for small arrays, but can be slower or just throw an error for very large arrays due to spread operator limitations. Maximal array length is approximately 124000 in Chrome 143 and 638000 in Safari 18; exact numbers may vary - see [the fiddle](https://jsfiddle.net/qw1jabsx/4/). Use the loop approach for reliability.
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
---
|
||||
title: Defer Non-Critical Work with requestIdleCallback
|
||||
impact: MEDIUM
|
||||
impactDescription: keeps UI responsive during background tasks
|
||||
tags: javascript, performance, idle, scheduling, analytics
|
||||
---
|
||||
|
||||
## Defer Non-Critical Work with requestIdleCallback
|
||||
|
||||
**Impact: MEDIUM (keeps UI responsive during background tasks)**
|
||||
|
||||
Use `requestIdleCallback()` to schedule non-critical work during browser idle periods. This keeps the main thread free for user interactions and animations, reducing jank and improving perceived performance.
|
||||
|
||||
**Incorrect (blocks main thread during user interaction):**
|
||||
|
||||
```typescript
|
||||
function handleSearch(query: string) {
|
||||
const results = searchItems(query)
|
||||
setResults(results)
|
||||
|
||||
// These block the main thread immediately
|
||||
analytics.track('search', { query })
|
||||
saveToRecentSearches(query)
|
||||
prefetchTopResults(results.slice(0, 3))
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (defers non-critical work to idle time):**
|
||||
|
||||
```typescript
|
||||
function handleSearch(query: string) {
|
||||
const results = searchItems(query)
|
||||
setResults(results)
|
||||
|
||||
// Defer non-critical work to idle periods
|
||||
requestIdleCallback(() => {
|
||||
analytics.track('search', { query })
|
||||
})
|
||||
|
||||
requestIdleCallback(() => {
|
||||
saveToRecentSearches(query)
|
||||
})
|
||||
|
||||
requestIdleCallback(() => {
|
||||
prefetchTopResults(results.slice(0, 3))
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
**With timeout for required work:**
|
||||
|
||||
```typescript
|
||||
// Ensure analytics fires within 2 seconds even if browser stays busy
|
||||
requestIdleCallback(
|
||||
() => analytics.track('page_view', { path: location.pathname }),
|
||||
{ timeout: 2000 }
|
||||
)
|
||||
```
|
||||
|
||||
**Chunking large tasks:**
|
||||
|
||||
```typescript
|
||||
function processLargeDataset(items: Item[]) {
|
||||
let index = 0
|
||||
|
||||
function processChunk(deadline: IdleDeadline) {
|
||||
// Process items while we have idle time (aim for <50ms chunks)
|
||||
while (index < items.length && deadline.timeRemaining() > 0) {
|
||||
processItem(items[index])
|
||||
index++
|
||||
}
|
||||
|
||||
// Schedule next chunk if more items remain
|
||||
if (index < items.length) {
|
||||
requestIdleCallback(processChunk)
|
||||
}
|
||||
}
|
||||
|
||||
requestIdleCallback(processChunk)
|
||||
}
|
||||
```
|
||||
|
||||
**With fallback for unsupported browsers:**
|
||||
|
||||
```typescript
|
||||
const scheduleIdleWork = window.requestIdleCallback ?? ((cb: () => void) => setTimeout(cb, 1))
|
||||
|
||||
scheduleIdleWork(() => {
|
||||
// Non-critical work
|
||||
})
|
||||
```
|
||||
|
||||
**When to use:**
|
||||
|
||||
- Analytics and telemetry
|
||||
- Saving state to localStorage/IndexedDB
|
||||
- Prefetching resources for likely next actions
|
||||
- Processing non-urgent data transformations
|
||||
- Lazy initialization of non-critical features
|
||||
|
||||
**When NOT to use:**
|
||||
|
||||
- User-initiated actions that need immediate feedback
|
||||
- Rendering updates the user is waiting for
|
||||
- Time-sensitive operations
|
||||
@@ -0,0 +1,24 @@
|
||||
---
|
||||
title: Use Set/Map for O(1) Lookups
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: O(n) to O(1)
|
||||
tags: javascript, set, map, data-structures, performance
|
||||
---
|
||||
|
||||
## Use Set/Map for O(1) Lookups
|
||||
|
||||
Convert arrays to Set/Map for repeated membership checks.
|
||||
|
||||
**Incorrect (O(n) per check):**
|
||||
|
||||
```typescript
|
||||
const allowedIds = ['a', 'b', 'c', ...]
|
||||
items.filter(item => allowedIds.includes(item.id))
|
||||
```
|
||||
|
||||
**Correct (O(1) per check):**
|
||||
|
||||
```typescript
|
||||
const allowedIds = new Set(['a', 'b', 'c', ...])
|
||||
items.filter(item => allowedIds.has(item.id))
|
||||
```
|
||||
@@ -0,0 +1,57 @@
|
||||
---
|
||||
title: Use toSorted() Instead of sort() for Immutability
|
||||
impact: MEDIUM-HIGH
|
||||
impactDescription: prevents mutation bugs in React state
|
||||
tags: javascript, arrays, immutability, react, state, mutation
|
||||
---
|
||||
|
||||
## Use toSorted() Instead of sort() for Immutability
|
||||
|
||||
`.sort()` mutates the array in place, which can cause bugs with React state and props. Use `.toSorted()` to create a new sorted array without mutation.
|
||||
|
||||
**Incorrect (mutates original array):**
|
||||
|
||||
```typescript
|
||||
function UserList({ users }: { users: User[] }) {
|
||||
// Mutates the users prop array!
|
||||
const sorted = useMemo(
|
||||
() => users.sort((a, b) => a.name.localeCompare(b.name)),
|
||||
[users]
|
||||
)
|
||||
return <div>{sorted.map(renderUser)}</div>
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (creates new array):**
|
||||
|
||||
```typescript
|
||||
function UserList({ users }: { users: User[] }) {
|
||||
// Creates new sorted array, original unchanged
|
||||
const sorted = useMemo(
|
||||
() => users.toSorted((a, b) => a.name.localeCompare(b.name)),
|
||||
[users]
|
||||
)
|
||||
return <div>{sorted.map(renderUser)}</div>
|
||||
}
|
||||
```
|
||||
|
||||
**Why this matters in React:**
|
||||
|
||||
1. Props/state mutations break React's immutability model - React expects props and state to be treated as read-only
|
||||
2. Causes stale closure bugs - Mutating arrays inside closures (callbacks, effects) can lead to unexpected behavior
|
||||
|
||||
**Browser support (fallback for older browsers):**
|
||||
|
||||
`.toSorted()` is available in all modern browsers (Chrome 110+, Safari 16+, Firefox 115+, Node.js 20+). For older environments, use spread operator:
|
||||
|
||||
```typescript
|
||||
// Fallback for older browsers
|
||||
const sorted = [...items].sort((a, b) => a.value - b.value)
|
||||
```
|
||||
|
||||
**Other immutable array methods:**
|
||||
|
||||
- `.toSorted()` - immutable sort
|
||||
- `.toReversed()` - immutable reverse
|
||||
- `.toSpliced()` - immutable splice
|
||||
- `.with()` - immutable element replacement
|
||||
@@ -0,0 +1,26 @@
|
||||
---
|
||||
title: Use Activity Component for Show/Hide
|
||||
impact: MEDIUM
|
||||
impactDescription: preserves state/DOM
|
||||
tags: rendering, activity, visibility, state-preservation
|
||||
---
|
||||
|
||||
## Use Activity Component for Show/Hide
|
||||
|
||||
Use React's `<Activity>` to preserve state/DOM for expensive components that frequently toggle visibility.
|
||||
|
||||
**Usage:**
|
||||
|
||||
```tsx
|
||||
import { Activity } from 'react'
|
||||
|
||||
function Dropdown({ isOpen }: Props) {
|
||||
return (
|
||||
<Activity mode={isOpen ? 'visible' : 'hidden'}>
|
||||
<ExpensiveMenu />
|
||||
</Activity>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
Avoids expensive re-renders and state loss.
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
---
|
||||
title: Animate SVG Wrapper Instead of SVG Element
|
||||
impact: LOW
|
||||
impactDescription: enables hardware acceleration
|
||||
tags: rendering, svg, css, animation, performance
|
||||
---
|
||||
|
||||
## Animate SVG Wrapper Instead of SVG Element
|
||||
|
||||
Many browsers don't have hardware acceleration for CSS3 animations on SVG elements. Wrap SVG in a `<div>` and animate the wrapper instead.
|
||||
|
||||
**Incorrect (animating SVG directly - no hardware acceleration):**
|
||||
|
||||
```tsx
|
||||
function LoadingSpinner() {
|
||||
return (
|
||||
<svg
|
||||
className="animate-spin"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<circle cx="12" cy="12" r="10" stroke="currentColor" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (animating wrapper div - hardware accelerated):**
|
||||
|
||||
```tsx
|
||||
function LoadingSpinner() {
|
||||
return (
|
||||
<div className="animate-spin">
|
||||
<svg
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<circle cx="12" cy="12" r="10" stroke="currentColor" />
|
||||
</svg>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
This applies to all CSS transforms and transitions (`transform`, `opacity`, `translate`, `scale`, `rotate`). The wrapper div allows browsers to use GPU acceleration for smoother animations.
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
---
|
||||
title: Use Explicit Conditional Rendering
|
||||
impact: LOW
|
||||
impactDescription: prevents rendering 0 or NaN
|
||||
tags: rendering, conditional, jsx, falsy-values
|
||||
---
|
||||
|
||||
## Use Explicit Conditional Rendering
|
||||
|
||||
Use explicit ternary operators (`? :`) instead of `&&` for conditional rendering when the condition can be `0`, `NaN`, or other falsy values that render.
|
||||
|
||||
**Incorrect (renders "0" when count is 0):**
|
||||
|
||||
```tsx
|
||||
function Badge({ count }: { count: number }) {
|
||||
return (
|
||||
<div>
|
||||
{count && <span className="badge">{count}</span>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// When count = 0, renders: <div>0</div>
|
||||
// When count = 5, renders: <div><span class="badge">5</span></div>
|
||||
```
|
||||
|
||||
**Correct (renders nothing when count is 0):**
|
||||
|
||||
```tsx
|
||||
function Badge({ count }: { count: number }) {
|
||||
return (
|
||||
<div>
|
||||
{count > 0 ? <span className="badge">{count}</span> : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// When count = 0, renders: <div></div>
|
||||
// When count = 5, renders: <div><span class="badge">5</span></div>
|
||||
```
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
---
|
||||
title: CSS content-visibility for Long Lists
|
||||
impact: HIGH
|
||||
impactDescription: faster initial render
|
||||
tags: rendering, css, content-visibility, long-lists
|
||||
---
|
||||
|
||||
## CSS content-visibility for Long Lists
|
||||
|
||||
Apply `content-visibility: auto` to defer off-screen rendering.
|
||||
|
||||
**CSS:**
|
||||
|
||||
```css
|
||||
.message-item {
|
||||
content-visibility: auto;
|
||||
contain-intrinsic-size: 0 80px;
|
||||
}
|
||||
```
|
||||
|
||||
**Example:**
|
||||
|
||||
```tsx
|
||||
function MessageList({ messages }: { messages: Message[] }) {
|
||||
return (
|
||||
<div className="overflow-y-auto h-screen">
|
||||
{messages.map(msg => (
|
||||
<div key={msg.id} className="message-item">
|
||||
<Avatar user={msg.author} />
|
||||
<div>{msg.content}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
For 1000 messages, browser skips layout/paint for ~990 off-screen items (10× faster initial render).
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user