Skip to content

fix(admin): preserve RepeaterField item keys across value round-trip - #678

Merged
ascorbic merged 2 commits into
emdash-cms:mainfrom
drudge:fix/admin-repeater-key-preservation
Apr 21, 2026
Merged

ascorbic merged 2 commits into
emdash-cms:mainfrom
drudge:fix/admin-repeater-key-preservation

Conversation

@drudge

@drudge drudge commented Apr 20, 2026

Copy link
Copy Markdown
Contributor

Summary

The RepeaterField sync effect was minting fresh item keys on every parent update, causing SortableRepeaterItem to unmount/remount on every keystroke. Inputs lost focus and the item card appeared to collapse back.

Reproducer

  1. Define a content type with a repeater field (or edit any existing one).
  2. Expand an item and type a sentence into a sub-field.
  3. Observe: focus drops after each character, and the editor feels like it's constantly remounting.

Root cause

packages/admin/src/components/RepeaterField.tsx:

  • ensureKeys() assigns _key: \item-${i}-${Date.now()}`when an item has no_key`.
  • stripKeys() removes _key before onChange, so the parent's value never carries keys.
  • The useEffect([value]) sync reruns ensureKeys() against the round-tripped (keyless) value → fresh Date.now() keys on every emit.
  • SortableRepeaterItem is keyed by item._key, so changed keys = full unmount/remount of every item.
  • Secondary: collapsedItems: Set<string> is keyed by _key and becomes orphaned on every keystroke.

Fix

Preserve each item's _key by position: when the incoming value lacks _key, reuse the key from the previous state at the same index. Round-trips via stripKeys stop churning keys; new external values (add/remove/reorder) still get stable keys either from the incoming object or the previous slot. Initial loads fall back to the existing item-\${i}-\${Date.now()} generator.

No changes to emitChange, handleAdd, handleRemove, handleDragEnd, or toggleCollapse — they already operated correctly on _key-bearing items.

Test plan

  • Type a full sentence into a repeater sub-field → input keeps focus, item stays expanded.
  • Add a new item → item gets a unique key and appears expanded.
  • Remove an item → surviving items keep their keys and expand/collapse state.
  • Drag-to-reorder → order persists and keys follow items.
  • Reload the editor → persisted data loads without extraneous _key fields (still stripped in emitChange).

The sync useEffect was running ensureKeys on every parent-prop update.
Since emitChange strips _key before onChange, the round-tripped value
always came back keyless, causing ensureKeys to mint fresh Date.now()
keys. React then unmounted and remounted every SortableRepeaterItem on
every keystroke — inputs lost focus and the item card appeared to
collapse.

Preserve each item's _key by position: when the incoming value lacks
_key, reuse the key at the same index from previous state. Stable
React keys mean inputs keep focus and expand/collapse state survives
edits.
Copilot AI review requested due to automatic review settings April 20, 2026 15:33
@changeset-bot

changeset-bot Bot commented Apr 20, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 00f9058

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

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

@pkg-pr-new

pkg-pr-new Bot commented Apr 20, 2026

Copy link
Copy Markdown

Open in StackBlitz

@emdash-cms/admin

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

@emdash-cms/auth

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

@emdash-cms/blocks

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

@emdash-cms/cloudflare

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

emdash

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

create-emdash

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

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

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

@emdash-cms/x402

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

@emdash-cms/plugin-ai-moderation

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

@emdash-cms/plugin-atproto

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

@emdash-cms/plugin-audit-log

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

@emdash-cms/plugin-color

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

@emdash-cms/plugin-embeds

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

@emdash-cms/plugin-forms

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

@emdash-cms/plugin-webhook-notifier

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

commit: 00f9058

@drudge drudge mentioned this pull request Apr 20, 2026
11 of 18 tasks

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Fixes unstable RepeaterField item identity in the admin content editor by preserving each item’s internal _key across value round-trips (where _key is stripped before emitting to the parent). This prevents SortableRepeaterItem unmount/remount churn that was causing focus loss and collapse-state resets while typing.

Changes:

  • Updates the useEffect([value]) sync to reuse prior item _keys by index when the incoming value lacks keys.
  • Keeps _key stripping behavior intact for persisted values while stabilizing React/DnD keys during editing.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +71 to +86
// Sync from external value changes.
// Preserve each item's _key by position so round-trips through onChange
// (which strips _key) don't remount children on every keystroke.
React.useEffect(() => {
const incoming = Array.isArray(value) ? value : [];
setItems(ensureKeys(incoming));
setItems((prev) =>
incoming.map((item, i) => {
const obj = (typeof item === "object" && item !== null ? item : {}) as Record<
string,
unknown
>;
const existingKey = (obj._key as string) || prev[i]?._key;
return {
...obj,
_key: existingKey || `item-${i}-${Date.now()}`,
};

Copilot AI Apr 20, 2026

Copy link

Choose a reason for hiding this comment

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

The useEffect sync re-implements most of ensureKeys() inline (object coercion + key minting). This duplicates key-generation logic (now in ensureKeys, the effect, and handleAdd) and risks the behaviors drifting over time. Consider extracting a single helper (e.g. reconcileKeys(incoming, prev) or a shared createRepeaterKey(...)) and reuse it for both initial state and the sync effect.

Copilot uses AI. Check for mistakes.

@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.

Thanks!

@ascorbic
ascorbic merged commit dc0562a into emdash-cms:main Apr 21, 2026
28 checks passed
drudge added a commit to drudge/emdash that referenced this pull request Apr 22, 2026
Adds a `repeater` Block Kit element for plugin block forms: an
array-of-objects input with scalar sub-fields, drag-to-reorder
(dnd-kit), and collapsible item cards. Plugin blocks can now capture
repeating data (FAQ rows, carousel slides, card grids) inline in the
portable-text editor.

`@emdash-cms/blocks`
- `RepeaterElement` + `RepeaterSubField` types (text/number/select/
  toggle/checkbox/combobox/date/radio as sub-fields — no nested
  repeaters, no buttons)
- `elements.repeater(...)` builder
- Schema validation for the repeater: sub-field type whitelist,
  non-negative integer `min_items` / `max_items` with
  `min_items <= max_items`
- Exhaustive runtime `renderElement` arm (returns null — repeater is
  admin-authoring only)

`@emdash-cms/admin`
- `BlockKitRepeater` + `BlockKitRepeaterItem` rendered inside
  `PortableTextEditor`
- Drag-to-reorder handle, collapsible item cards, Add / Remove
  controls
- Keyboard-accessible item header (real `<button>` with
  `aria-expanded`, labeled drag handle)
- Stable `_key` preservation per item (same pattern as the merged
  `RepeaterField` fix in emdash-cms#678)
- `PluginBlockModal` body grows `max-h-[70vh] overflow-y-auto` so the
  modal scrolls when a repeater has many rows

Split from the original bundled emdash-cms#679 per maintainer review. Image-link
piece shipped in emdash-cms#704; `media_picker` follows in emdash-cms#731.
drudge added a commit to drudge/emdash that referenced this pull request Apr 23, 2026
Adds a `repeater` Block Kit element for plugin block forms: an
array-of-objects input with scalar sub-fields, drag-to-reorder
(dnd-kit), and collapsible item cards. Plugin blocks can now capture
repeating data (FAQ rows, carousel slides, card grids) inline in the
portable-text editor.

`@emdash-cms/blocks`
- `RepeaterElement` + `RepeaterSubField` types. Sub-fields are
  restricted to the four scalar inputs the admin widget renders
  inline: `text_input`, `number_input`, `select`, `toggle`. No
  nested repeaters, no buttons.
- `elements.repeater(...)` builder
- Schema validation for the repeater: non-empty `fields` array,
  sub-field type whitelist, non-negative integer `min_items` /
  `max_items` with `min_items <= max_items`, and `initial_value`
  entries must be objects
- Exhaustive runtime `renderElement` arm (returns null — repeater is
  admin-authoring only)

`@emdash-cms/admin`
- `BlockKitRepeater` + `BlockKitRepeaterItem` rendered inside
  `PortableTextEditor`
- Drag-to-reorder handle, collapsible item cards, Add / Remove
  controls
- Keyboard-accessible item header (real `<button>` with
  `aria-expanded`, labeled drag handle)
- `handleRemove` drops the removed item's key from the `expanded`
  Set so it doesn't retain stale entries
- Stable `_key` preservation per item (same pattern as the merged
  `RepeaterField` fix in emdash-cms#678)
- `PluginBlockModal` body grows `max-h-[70vh] overflow-y-auto` so the
  modal scrolls when a repeater has many rows

Split from the original bundled emdash-cms#679 per maintainer review. Image-link
piece shipped in emdash-cms#704; `media_picker` follows in emdash-cms#731.
drudge added a commit to drudge/emdash that referenced this pull request Apr 24, 2026
Adds a `repeater` Block Kit element for plugin block forms: an
array-of-objects input with scalar sub-fields, drag-to-reorder
(dnd-kit), and collapsible item cards. Plugin blocks can now capture
repeating data (FAQ rows, carousel slides, card grids) inline in the
portable-text editor.

`@emdash-cms/blocks`
- `RepeaterElement` + `RepeaterSubField` types. Sub-fields are
  restricted to the four scalar inputs the admin widget renders
  inline: `text_input`, `number_input`, `select`, `toggle`. No
  nested repeaters, no buttons.
- `elements.repeater(...)` builder
- Schema validation for the repeater: non-empty `fields` array,
  sub-field type whitelist, non-negative integer `min_items` /
  `max_items` with `min_items <= max_items`, and `initial_value`
  entries must be objects
- Unit tests in `tests/validation.test.ts` covering the new rules
  (valid repeater, empty fields, disallowed sub-field type,
  non-integer / inverted min/max, malformed `initial_value`)
- Exhaustive runtime `renderElement` arm (returns null — repeater is
  admin-authoring only)

`@emdash-cms/admin`
- `BlockKitRepeater` + `BlockKitRepeaterItem` rendered inside
  `PortableTextEditor`
- Drag-to-reorder handle, collapsible item cards, Add / Remove
  controls
- Keyboard-accessible item header (real `<button>` with
  `aria-expanded`, labeled drag handle)
- `handleRemove` drops the removed item's key from the `expanded`
  Set so it doesn't retain stale entries
- Item-card summary trims the first text_input before falling back
  to "Item N" so whitespace-only values still show the index
- Stable `_key` preservation per item (same pattern as the merged
  `RepeaterField` fix in emdash-cms#678)
- `PluginBlockModal` body grows `max-h-[70vh] overflow-y-auto` so the
  modal scrolls when a repeater has many rows

Split from the original bundled emdash-cms#679 per maintainer review. Image-link
piece shipped in emdash-cms#704; `media_picker` follows in emdash-cms#731.
drudge added a commit to drudge/emdash that referenced this pull request Apr 24, 2026
Adds a `repeater` Block Kit element for plugin block forms: an
array-of-objects input with scalar sub-fields, drag-to-reorder
(dnd-kit), and collapsible item cards. Plugin blocks can now capture
repeating data (FAQ rows, carousel slides, card grids) inline in the
portable-text editor.

`@emdash-cms/blocks`
- `RepeaterElement` + `RepeaterSubField` types. Sub-fields are
  restricted to the four scalar inputs the admin widget renders
  inline: `text_input`, `number_input`, `select`, `toggle`. No
  nested repeaters, no buttons.
- `elements.repeater(...)` builder
- Schema validation for the repeater: non-empty `fields` array,
  sub-field type whitelist, non-negative integer `min_items` /
  `max_items` with `min_items <= max_items`, and `initial_value`
  entries must be objects
- Unit tests in `tests/validation.test.ts` covering the new rules
  (valid repeater, empty fields, disallowed sub-field type,
  non-integer / inverted min/max, malformed `initial_value`)
- Exhaustive runtime `renderElement` arm (returns null — repeater is
  admin-authoring only)

`@emdash-cms/admin`
- `BlockKitRepeater` + `BlockKitRepeaterItem` rendered inside
  `PortableTextEditor`
- Drag-to-reorder handle, collapsible item cards, Add / Remove
  controls
- Keyboard-accessible item header (real `<button>` with
  `aria-expanded`, labeled drag handle)
- `handleRemove` drops the removed item's key from the `expanded`
  Set so it doesn't retain stale entries
- Item-card summary trims the first text_input before falling back
  to "Item N" so whitespace-only values still show the index
- Stable `_key` preservation per item (same pattern as the merged
  `RepeaterField` fix in emdash-cms#678)
- `PluginBlockModal` body grows `max-h-[70vh] overflow-y-auto` so the
  modal scrolls when a repeater has many rows

Split from the original bundled emdash-cms#679 per maintainer review. Image-link
piece shipped in emdash-cms#704; `media_picker` follows in emdash-cms#731.
0aveRyan pushed a commit to 0aveRyan/emdash that referenced this pull request Apr 27, 2026
…mdash-cms#678)

* fix(admin): preserve RepeaterField item keys across value round-trip

The sync useEffect was running ensureKeys on every parent-prop update.
Since emitChange strips _key before onChange, the round-tripped value
always came back keyless, causing ensureKeys to mint fresh Date.now()
keys. React then unmounted and remounted every SortableRepeaterItem on
every keystroke — inputs lost focus and the item card appeared to
collapse.

Preserve each item's _key by position: when the incoming value lacks
_key, reuse the key at the same index from previous state. Stable
React keys mean inputs keep focus and expand/collapse state survives
edits.

* style: format

---------

Co-authored-by: emdashbot[bot] <emdashbot[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants