Skip to content

Commit 2f6cd7e

Browse files
jherrclaude
andcommitted
feat(compat-wp): WP-shaped features — comments, forms, taxonomy, redirects
Extends @tanstack/cms-compat-wp with the interactive WordPress features core leaves to userland, each off by default and added via config (createCompatWpDefinition({ comments, forms, taxonomy })): - Public comments: a wp_comments collection + compatWpSubmitComment (public, lands pending) + compatWpModerateComment (settings.manage: approve/unapprove/ spam/trash). Moderation runs through the content list's status field. - Form submissions: a wp_form_submissions collection (CF7 + Flamingo pattern) + compatWpSubmitForm (public). The entries inbox is the content list. - Taxonomy: a hierarchical wp_terms collection (categories/tags + usage count). - Apply redirects: compatWpApplyRedirects (settings.manage) compiles a source's old-permalink redirects and writes them into the redirects collection. The ops write through the core store (commitDocument/getAs); the plugin attaches comment/form ops only when their collection is enabled. Relative imports carry explicit .ts extensions (repo convention) so the definition stays resolvable at Vite config-load time. Verified live in the wp-vs-tanstack example: comment submit→moderate(approve) and form submit round-trips all succeed. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent 083147b commit 2f6cd7e

15 files changed

Lines changed: 545 additions & 43 deletions

File tree

‎examples/wp-vs-tanstack/src/cms.definition.ts‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,15 @@ import {
1212
} from '@tanstack/cms-core/definition'
1313
import { createCompatWpDefinition } from '@tanstack/cms-compat-wp/definition'
1414

15-
// WordPress-compatibility: adds the "WP Import" wizard under /cms. Fitting,
16-
// since this app is the WordPress-vs-TanStack comparison. The runtime op is
17-
// attached in cms.config.ts from this same object (defineCms requires it).
18-
export const wpDefinition = createCompatWpDefinition()
15+
// WordPress-compatibility: the "WP Import" wizard plus WP-shaped collections
16+
// (public comments with moderation, a form-submissions inbox, and taxonomy
17+
// terms). Fitting, since this app is the WordPress-vs-TanStack comparison. The
18+
// runtime ops are attached in cms.config.ts from this same object.
19+
export const wpDefinition = createCompatWpDefinition({
20+
comments: true,
21+
forms: true,
22+
taxonomy: true,
23+
})
1924

2025
export const definition = defineCmsDefinition({
2126
// Admin surface lives under /cms so it never collides with the public

‎packages/cms-compat-wp/README.md‎

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,12 @@ the `/definition` subpath so it stays load-safe in the Vite config:
2323
import { defineCmsDefinition } from '@tanstack/cms-core'
2424
import { createCompatWpDefinition } from '@tanstack/cms-compat-wp/definition'
2525

26-
export const wp = createCompatWpDefinition()
26+
// Enable the WP-shaped collections you want alongside the import wizard.
27+
export const wp = createCompatWpDefinition({
28+
comments: true,
29+
forms: true,
30+
taxonomy: true,
31+
})
2732

2833
export const definition = defineCmsDefinition({
2934
collections: [/* … */],
@@ -47,12 +52,21 @@ export const cms = defineCms(definition, { plugins: [createCompatWpPlugin(wp)] }
4752
live WordPress site URL, and preview what the import would produce — the
4853
inferred collections, the document count per collection, the redirects
4954
generated from old permalinks, and the WordPress plugins detected on the
50-
source. The preview is a dry run over the migration engine; it writes nothing.
51-
52-
The wizard and its op are gated on `settings.manage`.
53-
54-
## Roadmap
55+
source. A dry run over the migration engine; it writes nothing. Gated on
56+
`settings.manage`.
57+
- **Public comments** (`comments: true`): a `wp_comments` collection and two
58+
ops — `compatWpSubmitComment` (public; a visitor comment lands `pending`) and
59+
`compatWpModerateComment` (`settings.manage`; approve / unapprove / spam /
60+
trash). Moderate from the content list or the op.
61+
- **Form submissions** (`forms: true`): a `wp_form_submissions` collection (the
62+
Contact Form 7 + Flamingo pattern) and `compatWpSubmitForm` (public). The
63+
entries inbox is the content list, filtered to the collection.
64+
- **Taxonomy terms** (`taxonomy: true`): a hierarchical `wp_terms` collection
65+
(categories/tags with a usage `count`).
66+
- **Apply redirects**: `compatWpApplyRedirects` (`settings.manage`) compiles a
67+
source's old-permalink redirects and writes them into the redirects
68+
collection (pairs with core's `redirectsCollection()`).
5569

56-
Built on the same seams (`collections`, `adminNav`, `adminRoutes`, `ops`,
57-
`eventHandlers`), still to come: a forms + entries inbox, public comments with
58-
moderation, and a taxonomy manager.
70+
Each feature is off by default; enable the ones you need. Every submit/moderate
71+
op writes through the core store, so entries are normal documents with a
72+
`status` field — moderation needs no special screen.
Lines changed: 25 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,45 @@
11
/**
2-
* The one-call factory: `createCompatWpPlugin(config)` returns a core
3-
* `CmsPlugin` that adds WordPress-compatibility features for teams migrating
4-
* off WordPress. It composes the existing `@tanstack/cms-migrate-wp` engine
5-
* rather than reimplementing it — no core changes.
2+
* The one-call factory: `createCompatWpPlugin(definition)` wraps a WP-compat
3+
* **definition** into the full runtime `CmsPlugin`, attaching the server ops
4+
* that match the enabled features. It composes the existing
5+
* `@tanstack/cms-migrate-wp` engine and core store rather than reimplementing
6+
* them — no core changes.
67
*
7-
* It bundles the import-wizard **definition** (admin nav + route, from
8-
* `./definition`) with the server-side **runtime** (the preview op). Later
9-
* features (forms + entries inbox, public comments, taxonomy manager) hang off
10-
* the same seams.
8+
* `defineCms` requires the runtime plugin to carry the *same* definition object
9+
* registered in `defineCmsDefinition({ plugins })`, so pass that object in.
1110
*/
1211
import { definePlugin } from '@tanstack/cms-core'
13-
import { wpImportPreviewOp } from './ops'
14-
import type { CmsPlugin, CmsPluginDefinition } from '@tanstack/cms-core'
12+
import { wpImportPreviewOp } from './ops.ts'
13+
import { commentOps } from './features/comment-ops.ts'
14+
import { DEFAULT_COMMENTS_COLLECTION } from './features/comments.ts'
15+
import { formOps } from './features/form-ops.ts'
16+
import { DEFAULT_FORMS_COLLECTION } from './features/forms.ts'
17+
import { redirectOps } from './features/redirect-ops.ts'
18+
import type { CmsOpDefinition, CmsPlugin, CmsPluginDefinition } from '@tanstack/cms-core'
1519

16-
export { createCompatWpDefinition, DEFAULT_IMPORT_ROUTE } from './definition'
20+
export { createCompatWpDefinition, DEFAULT_IMPORT_ROUTE } from './definition.ts'
1721

1822
/**
19-
* Wrap a WordPress-compat **definition** into the full runtime `CmsPlugin`,
20-
* attaching the server-side preview op. `defineCms` requires the runtime
21-
* plugin to carry the *same* definition object registered in
22-
* `defineCmsDefinition({ plugins })`, so pass that object in:
23+
* Wrap a WP-compat definition into the full runtime plugin:
2324
*
2425
* ```ts
2526
* // cms.definition.ts
26-
* export const wp = createCompatWpDefinition()
27+
* export const wp = createCompatWpDefinition({ comments: true, forms: true })
2728
* export const definition = defineCmsDefinition({ …, plugins: [wp] })
2829
* // cms.config.ts
2930
* export const cms = defineCms(definition, { plugins: [createCompatWpPlugin(wp)] })
3031
* ```
3132
*
32-
* For a single-config app, `defineCms(createCompatWpPlugin(createCompatWpDefinition()))`.
33+
* The import-preview and apply-redirects ops are always attached; the comment
34+
* and form ops are attached only when their collections are in the definition
35+
* (so a submit op never targets a collection the app didn't add).
3336
*/
3437
export function createCompatWpPlugin(
3538
definition: CmsPluginDefinition,
3639
): CmsPlugin {
37-
return definePlugin({
38-
definition,
39-
runtime: { ops: [wpImportPreviewOp] },
40-
})
40+
const names = new Set((definition.collections ?? []).map((c) => c.name))
41+
const ops: Array<CmsOpDefinition> = [wpImportPreviewOp, ...redirectOps]
42+
if (names.has(DEFAULT_COMMENTS_COLLECTION)) ops.push(...commentOps)
43+
if (names.has(DEFAULT_FORMS_COLLECTION)) ops.push(...formOps)
44+
return definePlugin({ definition, runtime: { ops } })
4145
}

‎packages/cms-compat-wp/src/definition.ts‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,11 @@
1111
// where Vite bundles subpath workspace imports but externalizes root ones.
1212
import { definePluginDefinition } from '@tanstack/cms-core/definition'
1313
import { route } from '@tanstack/virtual-file-routes'
14-
import type { CmsPluginDefinition } from '@tanstack/cms-core/definition'
15-
import type { CompatWpPluginConfig } from './types'
14+
import { commentsCollection } from './features/comments.ts'
15+
import { formSubmissionsCollection } from './features/forms.ts'
16+
import { taxonomyCollection } from './features/taxonomy.ts'
17+
import type { Collection, CmsPluginDefinition } from '@tanstack/cms-core/definition'
18+
import type { CompatWpPluginConfig } from './types.ts'
1619

1720
/** Default admin route (under the admin base) for the import wizard. */
1821
export const DEFAULT_IMPORT_ROUTE = '/wp-import'
@@ -32,8 +35,16 @@ export function createCompatWpDefinition(
3235
const wizardFile = decodeURIComponent(
3336
new URL('./admin/wp-import.tsx', import.meta.url).pathname,
3437
)
38+
// WP-shaped collections, added on demand. Their inboxes and moderation run
39+
// through the standard content list (each has a `status` field).
40+
const collections: Array<Collection> = []
41+
if (config.comments) collections.push(commentsCollection())
42+
if (config.forms) collections.push(formSubmissionsCollection())
43+
if (config.taxonomy) collections.push(taxonomyCollection())
44+
3545
return definePluginDefinition({
3646
name: config.name ?? 'compat-wp',
47+
...(collections.length ? { collections } : {}),
3748
adminNav: [
3849
{
3950
label: config.importLabel ?? 'WP Import',
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
/**
2+
* Server ops behind the public-comments feature: a `public` submit op (a
3+
* visitor posts a comment, which lands as `pending`) and a `settings.manage`
4+
* moderation op (approve / spam / trash / unapprove). Runtime-only — safe to
5+
* import `@tanstack/cms-core/server` here.
6+
*/
7+
import { z } from 'zod'
8+
import { defineOp } from '@tanstack/cms-core'
9+
import { commitDocument, getAs, systemContext } from '@tanstack/cms-core/server'
10+
import {
11+
COMMENT_STATUSES,
12+
DEFAULT_COMMENTS_COLLECTION,
13+
moderatedStatus,
14+
} from './comments.ts'
15+
16+
/** Op names (stable; the public site and the moderation screen call these). */
17+
export const SUBMIT_COMMENT_OP = 'compatWpSubmitComment'
18+
export const MODERATE_COMMENT_OP = 'compatWpModerateComment'
19+
20+
/** A short unique comment id. */
21+
function commentId(): string {
22+
return `wpc-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`
23+
}
24+
25+
const submitInput = z.object({
26+
author: z.string().min(1).max(120),
27+
body: z.string().min(1).max(10000),
28+
email: z.string().email().optional(),
29+
targetCollection: z.string().max(120).optional(),
30+
targetId: z.string().max(200).optional(),
31+
targetPath: z.string().max(400).optional(),
32+
})
33+
34+
/** Public: accept a visitor comment. It is stored `pending` for moderation. */
35+
export const submitCommentOp = defineOp({
36+
name: SUBMIT_COMMENT_OP,
37+
method: 'POST',
38+
access: 'public',
39+
description: 'Submit a public comment. Stored as pending until moderated.',
40+
input: submitInput,
41+
run: async (input) => {
42+
const id = commentId()
43+
await commitDocument(DEFAULT_COMMENTS_COLLECTION, id, {
44+
author: input.author,
45+
body: input.body,
46+
email: input.email ?? '',
47+
targetCollection: input.targetCollection ?? '',
48+
targetId: input.targetId ?? '',
49+
targetPath: input.targetPath ?? '',
50+
status: 'pending',
51+
submittedAt: new Date().toISOString(),
52+
})
53+
return { ok: true, id, status: 'pending' as const }
54+
},
55+
})
56+
57+
const moderateInput = z.object({
58+
id: z.string().min(1),
59+
action: z.enum(['approve', 'unapprove', 'spam', 'trash']),
60+
})
61+
62+
/** Moderator: move a comment to a new status (approve / spam / trash). */
63+
export const moderateCommentOp = defineOp({
64+
name: MODERATE_COMMENT_OP,
65+
method: 'POST',
66+
access: 'settings.manage',
67+
description: 'Moderate a comment: approve, unapprove, mark spam, or trash.',
68+
input: moderateInput,
69+
run: async (input) => {
70+
const status = moderatedStatus(input.action)
71+
if (!status || !COMMENT_STATUSES.includes(status)) {
72+
throw new Error(`Unknown moderation action: ${input.action}`)
73+
}
74+
const existing = (
75+
await getAs(systemContext('wp comment moderation'), {
76+
collection: DEFAULT_COMMENTS_COLLECTION,
77+
id: input.id,
78+
staged: false,
79+
populate: false,
80+
})
81+
)?.doc
82+
if (!existing) throw new Error(`Comment not found: ${input.id}`)
83+
await commitDocument(DEFAULT_COMMENTS_COLLECTION, input.id, {
84+
...existing,
85+
status,
86+
})
87+
return { ok: true, id: input.id, status }
88+
},
89+
})
90+
91+
/** Both comment ops, for the plugin runtime. */
92+
export const commentOps = [submitCommentOp, moderateCommentOp]
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/**
2+
* Public comments — the WordPress comment model that core's *editorial*
3+
* comments (reviewer notes on a document) don't cover. A visitor-submitted
4+
* comment lands as `pending` and a moderator approves, marks spam, or trashes
5+
* it. The collection is plain CMS data, so it also shows up in the content list.
6+
*
7+
* Imported by the plugin definition (Vite-config-load safe): uses only the
8+
* `@tanstack/cms-core/definition` subpath.
9+
*/
10+
import { defineCollection } from '@tanstack/cms-core/definition'
11+
12+
/** The moderation states a comment moves through. */
13+
export const COMMENT_STATUSES = ['pending', 'approved', 'spam', 'trash'] as const
14+
export type CommentStatus = (typeof COMMENT_STATUSES)[number]
15+
16+
/** Default collection name for public comments. */
17+
export const DEFAULT_COMMENTS_COLLECTION = 'wp_comments'
18+
19+
/** Moderation action → the status it produces. Pure, so it is unit-testable. */
20+
const TRANSITIONS: Record<string, CommentStatus> = {
21+
approve: 'approved',
22+
unapprove: 'pending',
23+
spam: 'spam',
24+
trash: 'trash',
25+
}
26+
27+
/** The status a moderation action yields, or null for an unknown action. */
28+
export function moderatedStatus(action: string): CommentStatus | null {
29+
return TRANSITIONS[action] ?? null
30+
}
31+
32+
/** Build the public-comments collection (status field drives moderation). */
33+
export function commentsCollection(config: { name?: string; label?: string } = {}) {
34+
return defineCollection({
35+
name: config.name ?? DEFAULT_COMMENTS_COLLECTION,
36+
label: config.label ?? 'Comments',
37+
titleField: 'author',
38+
admin: { columns: ['author', 'status', 'targetPath'] },
39+
fields: [
40+
{ name: 'author', label: 'Author', type: 'text', required: true },
41+
{ name: 'email', label: 'Email', type: 'email' },
42+
{ name: 'body', label: 'Comment', type: 'textarea', required: true },
43+
{
44+
name: 'targetCollection',
45+
label: 'On Collection',
46+
type: 'text',
47+
defaultValue: '',
48+
},
49+
{ name: 'targetId', label: 'On Document', type: 'text', defaultValue: '' },
50+
{ name: 'targetPath', label: 'On Path', type: 'text', defaultValue: '' },
51+
{
52+
name: 'status',
53+
label: 'Status',
54+
type: 'select',
55+
options: [...COMMENT_STATUSES],
56+
defaultValue: 'pending',
57+
},
58+
{ name: 'submittedAt', label: 'Submitted', type: 'datetime' },
59+
],
60+
})
61+
}
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* The public form-submit op: a visitor posts a form and it becomes a `new`
3+
* entry in the submissions collection. Runtime-only.
4+
*/
5+
import { z } from 'zod'
6+
import { defineOp } from '@tanstack/cms-core'
7+
import { commitDocument } from '@tanstack/cms-core/server'
8+
import { DEFAULT_FORMS_COLLECTION } from './forms.ts'
9+
10+
export const SUBMIT_FORM_OP = 'compatWpSubmitForm'
11+
12+
const submitFormInput = z.object({
13+
formSlug: z.string().max(120).optional(),
14+
name: z.string().max(200).optional(),
15+
email: z.string().email().optional(),
16+
message: z.string().max(10000).optional(),
17+
fields: z.record(z.string(), z.unknown()).optional(),
18+
})
19+
20+
/** A one-line summary for the entry title (name and/or email). */
21+
export function submissionTitle(name?: string, email?: string): string {
22+
if (name && email) return `${name} <${email}>`
23+
return name || email || 'Form submission'
24+
}
25+
26+
/** Public: accept a form submission into the inbox collection. */
27+
export const submitFormOp = defineOp({
28+
name: SUBMIT_FORM_OP,
29+
method: 'POST',
30+
access: 'public',
31+
description: 'Submit a form. Stored as a new entry for the inbox.',
32+
input: submitFormInput,
33+
run: async (input) => {
34+
const id = `wpf-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`
35+
await commitDocument(DEFAULT_FORMS_COLLECTION, id, {
36+
title: submissionTitle(input.name, input.email),
37+
formSlug: input.formSlug ?? 'contact-us',
38+
senderName: input.name ?? '',
39+
senderEmail: input.email ?? '',
40+
message: input.message ?? '',
41+
fields: input.fields ?? {},
42+
status: 'new',
43+
submittedAt: new Date().toISOString(),
44+
})
45+
return { ok: true, id }
46+
},
47+
})
48+
49+
export const formOps = [submitFormOp]

0 commit comments

Comments
 (0)