Skip to content

fix(richEditor): headings that slugify alike collapse into one entry - #1208

Merged
sydevs-bot merged 13 commits into
mainfrom
claude/fix-1207-toc-duplicate-headings
Nov 19, 2026
Merged

sydevs-bot merged 13 commits into
mainfrom
claude/fix-1207-toc-duplicate-headings

Conversation

@sydevs-bot

@sydevs-bot sydevs-bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • A table-of-contents heading is identified by its position, not its slug, so two headings whose text slugifies alike are two rows that tick and untick on their own.
  • Each stored entry carries occurrence, which of the headings sharing its slug it is — what fix(rich-text): two headings that slugify alike share one anchor id WeMeditateWeb#266 needs to anchor each link. Reviewer's call, option C on the question thread: a slug-local ordinal rather than a position in the document.
  • Joined, same file: the field root was missing mergeFieldStyles, so it sat content-width while the built-ins beside it flexed (docs/rules/admin-ui.md).
  • Joined, same shape: DetectedHeading restated what jsonField already generates, which src/collections/AGENTS.md says to delete.
  • storedFrom is the one way a stored list leaves headings.ts, so "a heading goes where its parent goes" is stated once rather than in rebuildStored alone. Reviewer's ask: simplify that file.

Change outline

Types — one shape, generated

The hand-written interface is gone; the zod key carries its own prose, which Payload turns into JSDoc on the generated property.

 src/lib/richEditor/blocks/TableOfContentsBlock.ts
   jsonField({ name: 'headings', schemaTitle: 'TableOfContentsHeadings',
     schema: z.array(z.looseObject({ slug, text, level,
+      occurrence: z.int().optional().describe('Which of the headings sharing this slug this one is …'),
     })) })

 src/components/admin/TableOfContentsField/
-├── TableOfContents.tsx   # exported `DetectedHeading { slug, text, level }`
+└── every module imports `TableOfContentsHeadings` from `@/payload-types`

occurrence is optional because Payload validates this schema on every save of the page, so a required key would refuse the next save of every page stored today. That reason sits in the comment beside the schema rather than in the describe(): the generated JSDoc is read by consumers, and only this repo maintains the column.

Behaviour — what identifies a heading

Each reader of the stored list keyed on slug, which is not injective.

 TableOfContentsField
-  enabledHeadings = storedValue                    # the stored rows themselves
-  blockedSlugs: Set<string>                        # both duplicates blocked together
-  handleToggle(slug) → findIndex by slug           # always the first duplicate
+  enabledHeadings = resolveStored(detected, stored) # Set<position>
+  blocked        = blockedHeadings(detected, enabled)
+  handleToggle(position)
 TableOfContents
-  key={heading.slug}                               # two identical React keys
+  key={position}

The position is the identity inside the field, where the document is in hand. The occurrence is what the stored list carries, because a position means nothing to a reader that has not run our scan.

Flow — placing a stored entry on a heading

 resolveStored(detected, stored)                   headings.ts
   per stored entry, the first that finds an unclaimed heading of its slug:
+    the one at its own occurrence   # exact; no other heading moving disturbs it
+    else the one whose text matches # an entry stored before the key existed
+    else whatever is left           # its own occurrence was deleted
   an entry whose slug is gone is dropped, as before

 storedFrom(detected, positions)                   # every emitted list
+  drops a heading whose own parent is not kept    # rebuildStored AND toggleHeading

Files — the pure half, so a spec can reach it

 src/components/admin/TableOfContentsField/
+├── headings.ts            # stampOccurrences, resolveStored, blockedHeadings, rebuildStored, toggleHeading — no React, no Lexical
+│                          # private: parentOf, withDescendants, storedFrom
 ├── TableOfContentsField.tsx  # now the Lexical scan and the wiring only
 └── TableOfContents.tsx       # presentation, keyed on position

The unit lane cannot mount this component — nothing under tests/ renders React and the repo carries no testing-library — so the logic had to leave the editor subscription to be testable at all. stampOccurrences is the counting rule itself, moved out of the scan for the same reason: it is the half of the cross-repo contract a consumer re-derives, and it had no test while it lived inside the Lexical subscription.

Preview

  • Welcome page editor — pages 1014001 now carries two H2s, Where to begin and Where to begin?, which slugify alike. Its welcome-toc block lists both, at occurrence 0 and 1. Tick and untick each: the other must not move.

Contract impact

src/payload-types.ts gains occurrence?: number on TableOfContentsHeadings. Both contractSync consumers — WeMeditateWeb and SahajAtlasWeb — pick it up through their own types:cms step, in the bot's sync PR after this merges. The addition is optional, so neither breaks before that.

sydevs/WeMeditateWeb#266 is the reason this exists and is blocked on it. ⚠ C reverses the shape that ticket recorded, so its implementer reads occurrence, not index. The key was renamed rather than reinterpreted for exactly that reason: a reader written against the old rule fails to compile instead of computing an anchor from it. Nothing in production carries either key, so there is no stored data in the old shape.

The counting rule travels with the key: the describe() on occurrence states it — which of the headings sharing this slug this one is, counted from 0 in document order over top-level headings with non-empty text — and generate:types copies that sentence into each consumer's own payload-types.ts. Counting within one slug is what a consumer already does to suffix a repeated id, so it no longer has to agree with us on what the whole-document scan detected.

Test results

  • Lean gate: ✓ lint, format, typecheck (src), typecheck (tests), 3844 unit tests in 283 files — 111 s on bb47e6f, after a clean merge of origin/main
  • Targeted specs: tests/int/pages.int.spec.ts 20 passed. tests/int/fixture-load.int.spec.ts 7 passed on dd8acbb, and nothing since has touched the fixture
  • Build: N/A — Railway builds the preview

Both C-specific cases were watched failing first, against a shim stamping the document position and resolving without the occurrence: 2 of 15 fail there — stampOccurrences counting within a slug, and telling two headings with identical text apart. The other 13 are slug-and-text behaviour both shapes share, so they are regression guards rather than evidence for C. The json-field-schemas case refusing occurrence: '0' was watched failing with the schema key removed.

toggleHeading dropping an orphan it never touched was watched failing against the pre-storedFrom file: 1 of 16 fails there, and the other 15 pass, so the simplification moved exactly that one behaviour.

Manual verification

  1. Open the preview link above. Tick and untick each of the two alike headings; confirm the other does not move and neither is struck through by the other's click.
  2. Add a third heading above both whose text slugifies differently, and confirm the ticked ones stay ticked.
  3. Save, reload, and confirm the two entries persist separately.

Notes for reviewer

  • The fixture pre-mortem: the fixture assumes slugifyValue('Where to begin?') equals slugifyValue('Where to begin'). Verified against the real slugify package in node_modules, not assumed — both give where-to-begin. The ordinals assume the welcome page's content holds exactly those two root-level heading() nodes; verified by reading src/fixture/pages.ts on this branch.
  • No migration. The column is JSON, so there is no DDL. pnpm db:migrations:create --skip-empty created nothing, which is the expected answer.
  • The limit C accepts, declared as a shortcut: beside resolveStored: inserting a heading above two that already slugify alike shifts their occurrences, so their ticks move with them until the next save. A stable id per heading node is the real answer and only Lexical can mint one. Under the position ordinal, any heading inserted above shifted every entry, so this is the same failure narrowed rather than a new one.
  • The simplification changed one behaviour, deliberately: toggleHeading used to emit its set unfiltered, so a stored list already holding an orphan — a heading enabled while its own parent is not — re-stored that orphan on every click. It now goes through storedFrom like rebuildStored does, and the orphan is dropped. Reachable only from a list written before this rule, which the next scan rebuilt anyway.
  • Dismissed from the review pass: a suggestion to drop the ordinal from the stored entry and have the component derive it alone. It cannot — two headings with identical text are separated by nothing else, and the consumer has no way to re-derive which of several alike entries an editor kept.
  • fix(rich-text): two headings that slugify alike share one anchor id WeMeditateWeb#266's own body still records the old shape. Not touched from here: it is another repo's ticket and nobody authorised this run to rewrite it. Its generated type will carry occurrence after the sync PR.
Detail

What each case needs to resolve. The stored list is a subsequence of the document's headings, so neither key alone places an entry:

Case What places it
Only the second of two alike headings is ticked The occurrence. Slug order reads the one stored entry as the first
A heading inserted above Nothing — an occurrence counts within one slug, so it does not move
Two headings have identical text The occurrence, the only thing separating them
An entry stored before the key existed Its text, then its slug
An entry whose own occurrence was deleted Its text, then its slug

The position ordinal needed a text-then-distance ranking to satisfy rows 1 to 3, because row 2 moved it. A slug-local ordinal makes rows 1 to 3 exact, and the two fallbacks are what rows 4 and 5 want anyway — so the ranking is gone and the three preferences are a flat chain.

Efficiency, measured against the real bound. HeadingFeature enables h2/h3 only and the scan reads root children alone, so a page holds 5–40 headings, ~200 at the pathological end. resolveStored is still O(stored × detected), now with up to three findIndex passes per entry rather than one ranking pass, stopping at the first that places it: ~4,800 inner iterations at 40 headings in the worst case, well under the cost of the slugifyValue calls in the same tick. stampOccurrences adds one Map pass per scan. The JSON.stringify change key costs ~5–10 µs there. All left as they are.

Rejected at option B, and settled on the thread: stamping the ordinal in an afterRead hook on the rich-text column rather than storing it. It pays the heading scan on every page read, and entries stored before the key existed still need the same fallbacks, so it moves the heuristic rather than removing it.

Closes #1207


Generated by Claude Code

A heading was identified by its slug, so two headings whose text slugified
alike were one entry: ticking one ticked both, React rendered two identical
keys, and a stored entry could not say which of the two it stood for.

The entry gains `index`, its ordinal among the document's detected headings.
It is optional because Payload validates a write against this schema
directly, so a required key would refuse the next save of every page stored
today. Nothing migrates the column, which is why a consumer must read its
absence as unknown rather than as 0.

The rebuild, blocking and toggle logic moves to `headings.ts` — no React, no
Lexical — because it is pure and the unit lane cannot mount a component:
nothing under `tests/` renders React and the repo carries no testing-library.

`resolveStored` is what places a stored entry on a heading. It cannot be
`index` alone, which a heading inserted above shifts, nor slug order, because
the stored list is a subsequence: untick the first of two alike headings and
the entry left is the second one.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjXRdr4GoFycKFfHhsR
A custom field that skips mergeFieldStyles is content-width while the
built-ins beside it flex, and nothing in the field's own config says so.
Payload merges admin.style and admin.width for a built-in field and does not
export the function that does it, so each custom field owes this call.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjXRdr4GoFycKFfHhsR
…rated one

`src/collections/AGENTS.md` says a JSON column's schema replaces its
hand-written type: delete that type and import the generated one at each
call site. `DetectedHeading` restated what `jsonField` already generates as
`TableOfContentsHeadings`, so adding `index` meant editing the shape in
three places.

The `index` prose moves onto the zod key with `.describe()`, which Payload
turns into JSDoc on the generated property — one home, where the refusal it
explains actually happens.

Also from the review pass:

- Slugify through `slugifyValue`, the repo's one named spelling, rather than
  a second copy of its options. The anchor a consumer re-derives is now
  produced by the same function every `slugField` uses, and transliterates.
- Name the counting rule a consumer re-derives, and its consumer, at the
  scan that defines it.
- Rank candidates by two explicit keys instead of folding them into one
  number with a penalty constant.
- Drop an unreachable bounds check in `toggleHeading`, and the `!enabled`
  guard duplicated at three layers — `blockedHeadings` never returns an
  enabled position.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjXRdr4GoFycKFfHhsR
@railway-app

railway-app Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

🚅 Deployed to the SahajCloud-pr-1208 environment in sahajcloud

Service Status Web Updated
SahajCloud 😴 Sleeping (View Logs) Web Nov 19, 2026 at 6:15 pm UTC
1 service not affected by this PR
  • mailpit

@sydevs-bot sydevs-bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

1 question for the reviewer, one per thread.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

@sydevs-bot

sydevs-bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor Author

🤖 no session running

recent dispatches
  • 17:35Z address-review · attempt 3 · session · done
  • 17:35Z address-review · attempt 3 · session
  • 08:30Z address-review · attempt 2 · session · timed out
  • 08:30Z address-review · attempt 2 · session
  • 04:27Z address-review · attempt 1 · session · timed out

Written by the sydevs dispatcher. Sessions never edit this comment.

@sydevs-bot sydevs-bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 18, 2026
@sydevs-bot sydevs-bot moved this from Pending to Working in SYDevelopers Technical Roadmap Nov 18, 2026

@sydevs-bot sydevs-bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

🧐 Adversarial review

The diff is smaller than the problem. It deletes a hand-written type, drops a second hand-rolled slugify call for slugifyValue, and its one new file is the extraction #1207 asked for by name. Keying on position instead of slug is the fix the ticket specified, and each acceptance criterion has a spec behind it. The ladder found nothing bespoke the repo, Payload or an installed package already does.

The contract side falls short. The ordinal's definition is the one thing a consumer cannot derive, and it sits in the one file no consumer reads.

Findings

  • should-fix — the counting rule reaches no consumer. It sits in the admin component, not in the describe() that types:cms copies. TableOfContentsBlock.ts:43.
  • consider — at shadows Array.prototype.at with different semantics. headings.ts:20.

What was checked

  • Read whole on the branch: the three component files, TableOfContentsBlock.ts, slugify.ts, mergeFieldStyles.ts, both specs.
  • slugifyValue(text) is byte-identical to the slugify(text, { lower: true, strict: true }) it replaces, so no stored slug moves and no page loses its ticks.
  • Walked resolveStored by hand over two cases the specs miss: a heading reordered past its alike twin, and an entry whose text was edited without moving its slug. Both resolve correctly.
  • blockedHeadings and toggleHeading match the behaviour they replace, the enabled path the new early return guards included.
  • Consumer: WeMeditateWeb's content-blocks.ts:127 restates TocHeading by hand, with no index — sydevs/WeMeditateWeb#266's work, not this PR's.
  • Preview: pr-1208 is ON_HOST. pages 1014001 is PAGE.welcome, and fixture/pages.ts:119,136 are its only root headings, so index 0 and 1 hold.
  • BlocksFeature nests no rich text, so no heading escapes the root scan.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

@sydevs-bot sydevs-bot removed the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 18, 2026
@sydevs-bot sydevs-bot moved this from Working to Pending in SYDevelopers Technical Roadmap Nov 18, 2026
@sydevs-bot sydevs-bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 18, 2026
@sydevs-bot sydevs-bot moved this from Pending to Working in SYDevelopers Technical Roadmap Nov 18, 2026
The ordinal is a cross-repo contract, and the sentence defining it sat only
in the admin component, which no consumer reads. `describe()` is what
`generate:types` copies into a consumer's own `payload-types.ts`, and it
said "detected headings" without saying what gets detected — so a consumer
counting rendered headings counts an empty one the scan skips.

The scan's comment now points at that `describe()` rather than restating the
rule, so the two spellings cannot disagree.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjZUpPdK2bk1DirLsT4
`at` reads as `Array.prototype.at`, which takes one index and returns one
element. This takes a set of positions and returns a list.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjZUpPdK2bk1DirLsT4
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-1208 November 18, 2026 22:20 Destroyed
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

Both critic findings adopted. Head is now 468274d.

The question thread on stamping index in an afterRead hook stays open. It waits on a reviewer, not on work.

origin/main merged in clean (b557fec). Lean gate green on the merged branch: lint, format, both typechecks, 3839 unit tests. Security review ran, since src/components/admin/ matches the trigger, and found nothing — every module touched is client-side and the diff adds no sink.

Body refreshed: ## Contract impact named the admin component as the rule's home, which 2891510 made false.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

@sydevs-bot sydevs-bot removed the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 18, 2026
@sydevs-bot sydevs-bot moved this from Working to Pending in SYDevelopers Technical Roadmap Nov 18, 2026
@sydevs-bot
sydevs-bot marked this pull request as ready for review November 18, 2026 22:31
@sydevs-bot
sydevs-bot requested a review from Ardnived November 18, 2026 22:31
@sydevs-bot
sydevs-bot enabled auto-merge November 18, 2026 22:31
@sydevs-bot sydevs-bot moved this from Pending to Awaiting in SYDevelopers Technical Roadmap Nov 18, 2026
@sydevs-bot sydevs-bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 19, 2026
The `describe()` on a zod key reaches exactly one audience: a developer
hovering the generated property in `payload-types.ts`, here and in the two
contractSync consumers. Four sentences there spent most of their length on
a fact only this repo's maintainer needs — why the key is optional — which
now sits in the comment beside the schema, where the same reason already
explained the loose object.

What a consumer cannot re-derive stays: what the number counts, and that
its absence means unknown rather than 0.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjYA5FNHkYaJws9xX1d
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-1208 November 19, 2026 03:17 Destroyed
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

Built and pushed. Head is dd8acbb.

  • The occurrence description is too long — shortened, 640 chars to 165. Its one reader is a developer hovering the generated property in payload-types.ts, here and in both sync consumers, so it now states only what the number counts and that absence means unknown. Why the key is optional moved to the comment beside the schema. Nobody sets it by hand, the same thread's second question: stampOccurrences stamps it inside the Lexical scan. Left open — that half is an answer, and yours to settle.

Security review: skipped, no changed path matches securityReview.triggerPattern. Lean gate green on dd8acbb: 3841 unit tests, lint, format, both typechecks. Docs checked, nothing stale. The branch was already level with origin/main, so there was no merge. Body refreshed where the shorter text made the Change outline false.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

@sydevs-bot sydevs-bot removed the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 19, 2026
@sydevs-bot sydevs-bot moved this from Working to Awaiting in SYDevelopers Technical Roadmap Nov 19, 2026
@sydevs-bot sydevs-bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 19, 2026
@sydevs-bot sydevs-bot moved this from Awaiting to Working in SYDevelopers Technical Roadmap Nov 19, 2026
@sydevs-bot sydevs-bot removed the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 19, 2026
@sydevs-bot sydevs-bot added bot:working Lock: a cloud session is running on this item. Removed when it ends. and removed bot:working Lock: a cloud session is running on this item. Removed when it ends. labels Nov 19, 2026
`headings.ts` spelled "a heading goes where its parent goes" twice — once
as `rebuildStored`'s own walk, and once by omission in `toggleHeading`,
which emitted its set unfiltered and so could re-store an orphan it never
touched. `storedFrom` is now the one way a stored list leaves this module,
so both emit under the same rule and `rebuildStored` is its one line.

`resolveStored` built all three candidate positions, mixed `-1` with
`undefined` as sentinels, then picked. The three preferences are now a
short-circuiting chain over one `firstFree` lookup, which is the only
concept the function has.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjWQPQu9oBHDEmsT4ca
@railway-app
railway-app Bot temporarily deployed to sahajcloud / SahajCloud-pr-1208 November 19, 2026 17:45 Destroyed
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

Built and pushed. Head is a0c6e18.

  • Simplify and streamline headings.ts — adopted in bb47e6f. storedFrom is now the one way a stored list leaves the module, so the parent rule has one home: rebuildStored is its one line, and toggleHeading no longer re-stores an orphan it never touched. resolveStored built all three candidate positions and mixed -1 with undefined as sentinels; it is now a short-circuiting chain over one firstFree lookup. Resolved.

The dropped orphan is the one behaviour that moved, watched failing against the old file — 1 of 16. It is in Notes for reviewer.

Merged origin/main cleanly. Lean gate green on bb47e6f: 3844 unit tests in 283 files, lint, format, both typechecks. tests/int/pages.int.spec.ts 20 passed. Security review ran on the src/components/admin/ match: no findings. Body refreshed — Test results and the Flow outline were both false after this push.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

@sydevs-bot sydevs-bot removed the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 19, 2026
@sydevs-bot sydevs-bot moved this from Working to Awaiting in SYDevelopers Technical Roadmap Nov 19, 2026
@sydevs-bot sydevs-bot moved this from Awaiting to Pending in SYDevelopers Technical Roadmap Nov 19, 2026
@sydevs-bot
sydevs-bot added this pull request to the merge queue Nov 19, 2026
Merged via the queue into main with commit 4037f5f Nov 19, 2026
33 checks passed
@sydevs-bot
sydevs-bot deleted the claude/fix-1207-toc-duplicate-headings branch November 19, 2026 18:17
sydevs-bot added a commit to sydevs/SahajAtlasWeb that referenced this pull request Nov 19, 2026
@sydevs-bot sydevs-bot moved this from Pending to Done in SYDevelopers Technical Roadmap Nov 19, 2026

This branch was successfully deployed

No deployments
sahajcloud / SahajCloud-pr-1208 — a0c6e18b Deployed Nov 19, 2026 by railway-app[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Development

Successfully merging this pull request may close these issues.

fix(richEditor): headings that slugify alike collapse into one entry

3 participants