Skip to content

feat: relations, and reference fields as entry pickers - #1928

Merged
ascorbic merged 102 commits into
emdash-cms:mainfrom
MA2153:feat/reference-field-admin-ui
Sep 25, 2026
Merged

ascorbic merged 102 commits into
emdash-cms:mainfrom
MA2153:feat/reference-field-admin-ui

Conversation

@MA2153

@MA2153 MA2153 commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Adds relations as first-class schema objects, and turns reference fields into entry pickers that link through them — core storage, the site query API, generated types, seeds and export, two migrations, and the admin surface for all of it.

A relation joins two collections under a site-unique slug, with a label for each side and an optional limit on how many entries each side may link. A reference field binds to a relation and views its links from one end, so one relation can back a field on either collection. Links live in _emdash_content_references keyed by translation group, not in a column on the collection table, so a selection is shared across an entry's translations.

Feature Discussion: #386

Closes #2403

Core (emdash)

Schema. _emdash_relations becomes one row per relation keyed by a unique slug (migration 083_relations_structural, replacing the per-locale rows migration 043 created), and _emdash_content_references.relation_group becomes relation_id. Relation IDs are preserved, so existing links stay valid. A relation carries a label and an optional singular form for each role, plus a per-side limit. Deleting a reference field no longer deletes its relation unless the caller passes deleteRelation=true; deleting a collection removes every relation it is an end of, along with the fields on the far collection that view them. Reading a relation reports what deleting it would take: the fields bound to it and how many links it holds.

Storage. A bound reference field adds no column. SchemaRegistry skips the DDL for it, createContentTable applies the same guard for seeded fields, and a selection is written as edges in the same transaction as the entry. relations joins the reserved collection slugs, since the admin serves its screen at that path.

Writes. Entry create and update bodies carry references, keyed by field slug. Required and selection-limit constraints are enforced on both ends of the relation, so a field on the parent side that would hand a selected entry more parents than the relation allows is refused, not only one that selects too many children itself. Large replacements are chunked for D1's bind-parameter limit.

Drafts. On a collection that keeps revisions, a selection changed on a published entry is staged in the draft and becomes live when the entry is published — through the publish action, a scheduled publish, or a revision restore — and is discarded with the draft. Publishing re-checks the whole selection against the relation's limits, so a draft cannot carry a selection past a schema change that would now reject it. Revision compare reports _references on both sides, filled in from the published selection for the fields a draft did not stage, so an unchanged reference field does not read as one the draft removed.

Reads. getEmDashEntry takes a references option naming the fields a page renders; getEmDashReferences walks past the first page with the cursor it returned. Both default to 50 entries per field and accept at most 100. A referenced entry is a mapped ContentEntry with a working edit proxy scoped to itself; bylines and taxonomy terms are not hydrated onto them. The reads go into the entry's cached snapshot, and the returned cacheHint names the referenced rows, so a route-cached page expires when a referenced entry changes and not only when the entry itself does.

Types. A collection with a bound reference field gets a {Collection}References interface, and getEmDashEntry narrows its result to the fields the call named. Type-level assertions run under a new vitest.types.config.ts / tsconfig.typecheck.json.

Seeds. A top-level relations array, validation.relation (and validation.relationSide for a self-relation) on a reference field, and $ref: links applied from the parent end. Re-applying a seed that names a targetCollection for a field that predates relations binds that field. export-seed emits relations, and --with-content emits each entry's links as $ref: values.

Upgrade. Migration 084_reference_field_relations binds each reference field that named a target collection in options.collection and copies the entry IDs in its column in as links, so those fields become working pickers with their selections intact. It skips a field with no resolvable target, one marked searchable or indexed, one whose relation slug {collection}_{field} is already taken, and one whose locale rows disagree about what they select. A skipped field keeps its column and behaves exactly as it did, and can be bound by hand under Content Types. The column is never dropped.

The relation routes and the reference-edge reads are wired into injectCoreRoutes; /relations/[id]/translations is removed with the per-locale rows. Links are written only with the entry that holds them, so a selection cannot bypass staging.

Admin (@emdash-cms/admin)

  • Reference fields are entry pickers: search for, pick and reorder linked entries, saved with the entry in one request.
  • A field bound to the other end of a relationship lists what points at an entry, and edits it from there.
  • A Relations page under Content Types listing every relationship, the fields bound to each end and which end they pick from, and how many links it holds. Each content type's own page repeats the ones it is an end of in a Relations panel under its fields. New, edit and delete all happen in a dialog over the list.
  • The field dialog starts from the relationship: pick one, and the label, slug and the rest of the field follow from the side the field views. Create relation is the last choice in that picker — and all a site with no relationships yet gets — turning Add field into Next and coming back with the new relationship selected. Direction is a choice only for a relationship whose two ends are the same content type.
  • Delete dialogs name what goes with a deletion: the relationship, its link count, and the field on the other content type with the direction it picks from.
  • A reference field created before this release keeps rendering as the text box it has always been, and its dialog offers the collection picker that binds it, saying what binding does.

Performance

Two fixture routes measure the cost of the read path. Loading an author and six related posts on /related is 9 queries against 6 for /related-baseline, the same page without references: one reference-field-map read (request-cached, and in the schema object-cache namespace), one link read per field, and one entry read per distinct target collection — not one per entry. A page that asks for no references runs none of those. The D1 snapshot shows the same delta (25 cold / 13 warm against 22 / 10). Both are recorded in scripts/query-counts.snapshot.{sqlite,d1}.json.

Documentation

New: guides/relations, the task path from defining a relation to reading its links, including picking entries, seeing what links to one, deletion, and binding a field that has no relation. Sidebar entry after Taxonomies.

Updated: deployment/updating (an upgrade entry for what the update binds, what it leaves unbound, and how to bind those by hand), reference/rest-api (the references write and read surface; relation and edge routes restated as internal; the section that no longer covers relations renamed), reference/field-types (all four reference validation keys and both ways to declare the field), themes/seed-files (the relations array; the field forms now link to field-types rather than restating them), guides/querying-content (reading and paginating references, preview behavior, generated types), reference/api (ReferencePage, getEmDashReferences), concepts/collections, guides/internationalization (a selection is shared across translations rather than synced), and the building-emdash-site skill references. Both changesets now link the guide and the upgrade note.

Type of change

Checklist

  • I have read CONTRIBUTING.md
  • pnpm typecheck passes
  • pnpm lint passes (lint:json reports 0 diagnostics)
  • pnpm test passes — see the output below
  • pnpm format has been run
  • I have added/updated tests for my changes
  • User-visible admin strings are wrapped for translation; no messages.po changes included
  • I have added and reviewed the user-facing changeset (emdash: minor, @emdash-cms/admin: minor)
  • New features link to an approved Discussion: Complete the reference field: collection picker in schema editor + content picker in content editor #386
  • I have included screenshots below if this PR changes the UI - a video below

AI-generated code disclosure

  • This PR includes AI-generated code — model/tool: Claude Opus 5 and Claude Opus 4.8 (Claude Code)

Screenshots / test output

https://youtu.be/Vt9FhTgPFyI

emdash   Test Files  603 passed | 2 failed | 2 skipped (607)
              Tests  7508 passed | 2 failed | 10 skipped (7520)

admin    Test Files    9 passed (9)       # picker, backlinks, relations route, field and
              Tests  303 passed (303)     # content-type editors, entry editor, singularize

The two core failures are tests/integration/database/media-usage-projection-admission-measurement.test.ts and tests/unit/components/inline-portable-text-code-block.test.ts. Neither file is touched by this branch, and both pass when run on their own; they fail only under full-suite concurrency on my machine. pnpm build, pnpm typecheck and pnpm lint:json (0 diagnostics) are clean.

The full admin suite runs under Vitest browser mode, which drops its websocket partway through on this machine, so the numbers above are the suites this PR touches rather than the whole package.

Note for reviewers

This PR is large (about 15,800 added lines across 119 files) because relations, the reference field, and the admin surface for both only make sense together: a field with no relation has nothing to point at, and a relation with no field has nothing to edit it. The maintainers agreed to review it as one change rather than a stack.

🤖 Generated with Claude Code

https://claude.ai/code/session_01BCzkfnJcdsiPK8AbbBFw3w

MA2153 and others added 19 commits July 10, 2026 11:42
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
`handleContentCreate`/`handleContentUpdate` already accept a `references`
body key, but the zod schemas didn't list it, so `parseBody` silently
stripped it before it reached the handler.
Creating a reference field now creates its backing relation def
transactionally, updating the field's label PATCHes the relation's
childLabel, and deleting the field deletes the relation and its edges.
The admin no longer has to orchestrate these multi-step writes itself.

Also fixes withTransaction to short-circuit when already inside a
transaction (db.isTransaction), rather than attempting an illegal
nested .transaction() call — required for the field-create/update/
delete handlers to nest their relation writes with SchemaRegistry's
own internally-transacted field writes.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Type STORAGELESS_FIELD_TYPES as ReadonlySet<string> so membership checks
against DB-sourced field types need no cast, resolving the lint diagnostic
introduced with stripStoragelessDataKeys.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Reference fields are storage-less, so a seed defining one now creates the
backing relation (like the schema handler) and writes a $ref value in the
field's data as a content-reference edge instead of a table column. Previously
applySeed threw "no such column" for any seed using a reference field.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- resolveEntries now attaches a display `title` (entry `title`, then `name`,
  else null) to every EntryRef, so picked entries and backlinks show a
  readable label instead of a slug; hydrated through content GET and the
  admin editor/backlinks sidebar.
- Wire the relation and reference-edge API routes into injectCoreRoutes;
  they existed but were never registered, so /_emdash/api/relations 404'd
  and the "Referenced by" panel silently hid itself.
- Preserve `targetCollection` and `multiple` on reference field validation
  so the create handler no longer rejects the field for a missing target.
- Backlinks sidebar resolves relations by translation_group, not name.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
# Conflicts:
#	packages/core/src/api/handlers/content.ts
@changeset-bot

changeset-bot Bot commented Jul 10, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 97d0eae

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 12 packages
Name Type
@emdash-cms/admin Minor
emdash Minor
@emdash-cms/cloudflare Minor
@emdash-cms/plugin-test Patch
@emdash-cms/sandbox-workerd Patch
@emdash-cms/auth Minor
@emdash-cms/blocks Minor
create-emdash Minor
@emdash-cms/gutenberg-to-portable-text Minor
@emdash-cms/x402 Minor
@emdash-cms/auth-atproto Patch
@emdash-cms/plugin-embeds Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@github-actions

Copy link
Copy Markdown
Contributor

Scope check

This PR changes 3,014 lines across 34 files. Large PRs are harder to review and more likely to be closed without review.

If this scope is intentional, no action needed. A maintainer will review it. If not, please consider splitting this into smaller PRs.

See CONTRIBUTING.md for contribution guidelines.

@github-actions github-actions Bot added the review/needs-review No maintainer or bot review yet label Jul 10, 2026
@pkg-pr-new

pkg-pr-new Bot commented Jul 10, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@emdash-cms/admin

npm i https://pkg.pr.new/@emdash-cms/admin@1928

@emdash-cms/auth

npm i https://pkg.pr.new/@emdash-cms/auth@1928

@emdash-cms/auth-atproto

npm i https://pkg.pr.new/@emdash-cms/auth-atproto@1928

@emdash-cms/blocks

npm i https://pkg.pr.new/@emdash-cms/blocks@1928

@emdash-cms/cloudflare

npm i https://pkg.pr.new/@emdash-cms/cloudflare@1928

@emdash-cms/contentful-to-portable-text

npm i https://pkg.pr.new/@emdash-cms/contentful-to-portable-text@1928

emdash

npm i https://pkg.pr.new/emdash@1928

create-emdash

npm i https://pkg.pr.new/create-emdash@1928

@emdash-cms/gutenberg-to-portable-text

npm i https://pkg.pr.new/@emdash-cms/gutenberg-to-portable-text@1928

@emdash-cms/plugin-cli

npm i https://pkg.pr.new/@emdash-cms/plugin-cli@1928

@emdash-cms/plugin-test

npm i https://pkg.pr.new/@emdash-cms/plugin-test@1928

@emdash-cms/plugin-types

npm i https://pkg.pr.new/@emdash-cms/plugin-types@1928

@emdash-cms/registry-client

npm i https://pkg.pr.new/@emdash-cms/registry-client@1928

@emdash-cms/registry-lexicons

npm i https://pkg.pr.new/@emdash-cms/registry-lexicons@1928

@emdash-cms/registry-loader

npm i https://pkg.pr.new/@emdash-cms/registry-loader@1928

@emdash-cms/registry-moderation

npm i https://pkg.pr.new/@emdash-cms/registry-moderation@1928

@emdash-cms/registry-verification

npm i https://pkg.pr.new/@emdash-cms/registry-verification@1928

@emdash-cms/sandbox-workerd

npm i https://pkg.pr.new/@emdash-cms/sandbox-workerd@1928

@emdash-cms/x402

npm i https://pkg.pr.new/@emdash-cms/x402@1928

@emdash-cms/plugin-ai-moderation

npm i https://pkg.pr.new/@emdash-cms/plugin-ai-moderation@1928

@emdash-cms/plugin-atproto

npm i https://pkg.pr.new/@emdash-cms/plugin-atproto@1928

@emdash-cms/plugin-audit-log

npm i https://pkg.pr.new/@emdash-cms/plugin-audit-log@1928

@emdash-cms/plugin-color

npm i https://pkg.pr.new/@emdash-cms/plugin-color@1928

@emdash-cms/plugin-embeds

npm i https://pkg.pr.new/@emdash-cms/plugin-embeds@1928

@emdash-cms/plugin-field-kit

npm i https://pkg.pr.new/@emdash-cms/plugin-field-kit@1928

@emdash-cms/plugin-forms

npm i https://pkg.pr.new/@emdash-cms/plugin-forms@1928

@emdash-cms/plugin-webhook-notifier

npm i https://pkg.pr.new/@emdash-cms/plugin-webhook-notifier@1928

commit: 97d0eae

@MA2153 MA2153 added the bot:review Trigger an emdashbot code review on this PR label Jul 10, 2026
# Conflicts:
#	packages/admin/src/components/ContentEditor.tsx
#	packages/admin/src/router.tsx
@MA2153
MA2153 marked this pull request as draft July 10, 2026 20:40
@github-actions github-actions Bot removed the review/needs-review No maintainer or bot review yet label Jul 10, 2026
MA2153 and others added 3 commits September 23, 2026 17:43
The legacy reference backfill sent one INSERT per edge, and a rerun after an
interruption resent every edge, so a field too large for one Worker
invocation's subrequest budget failed at the same point on every boot.

Edges are now written sixteen to a statement, within D1's bind-parameter
ceiling, and a rerun reads the edges its relation already has and sends only
the missing ones.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…route

A merge from main reintroduced routes the branch already registers under
its own headings (relations, relations/[id], and the reference children/
parents edge routes), plus a registration for
api/relations/[id]/translations.ts, a route file this branch deleted. The
dead registration broke astro build with an ENOENT on translations.mjs and
the duplicates tripped Astro's route-collision warning.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@saariuslystoned

Copy link
Copy Markdown
Contributor

Tested 3415ef55 with our Dinkus Blocks plugin—all 12 existing browser tests passed, and the combined block/reference flow passed autosave, draft isolation, publish, duplicate, and discard.

Found one restore gap: publish an original block with references [A], then publish an edited block with [B, A]. Restoring the first revision restores the original block but retains [B, A]. Publishing that restored draft exposes the same mismatch publicly.

The initial revision has no _references snapshot. This reproduces through the REST/runtime restore path with revisions enabled. Could we add regression coverage for preserving the initial reference selection through restore?

MA2153 and others added 7 commits September 25, 2026 17:55
Renumber the branch's relation migrations to 085/086 after main's
083_block_types and 084_site_transfer. Seeds apply relations, then
block types, then collections; seeded content is blocks-normalized
before reference values are split into edges.

Site transfer still targets the pre-085 relations schema; its tests
fail until it is updated in a follow-up.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Renumber this branch's migrations to 086_relations_structural and
087_reference_field_relations, after main's 085_taxonomy_def_groups.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
FieldEditor fetched both lists whenever it mounted, whatever the field
type. Enable the queries only while the dialog is open on a reference
field, as the block-types query already does for blocks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@MA2153

MA2153 commented Sep 25, 2026

Copy link
Copy Markdown
Contributor Author

@saariuslystoned Good catch. Fixed with regression tests.

emdashbot Bot and others added 3 commits September 25, 2026 16:41
The relations API no longer exposes GET /_emdash/api/relations/:id/translations,
so the injected-routes spec expected a JSON 404 from a route that is not
registered and received Astro's HTML 404 instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@ascorbic ascorbic left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Incredible work, @MA2153. Great addition. I've tried it locally and it works well. A lot of people will be very pleased by this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/admin area/core area/docs cla: signed query-count changed PR diff modifies query-count snapshot files review/approved Approved; no new commits since size/XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Admin has no editor for reference fields - renders raw-ID text input, required references cannot be saved

8 participants