Repository navigation
fix(richEditor): headings that slugify alike collapse into one entry - #1208
Conversation
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
Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Mg9rjXRdr4GoFycKFfHhsR
|
🚅 Deployed to the SahajCloud-pr-1208 environment in sahajcloud
1 service not affected by this PR
|
sydevs-bot
left a comment
There was a problem hiding this comment.
1 question for the reviewer, one per thread.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
|
🤖 no session running recent dispatchesWritten by the sydevs dispatcher. Sessions never edit this comment. |
sydevs-bot
left a comment
There was a problem hiding this comment.
🧐 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()thattypes:cmscopies.TableOfContentsBlock.ts:43. - consider —
atshadowsArray.prototype.atwith 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 theslugify(text, { lower: true, strict: true })it replaces, so no stored slug moves and no page loses its ticks.- Walked
resolveStoredby 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. blockedHeadingsandtoggleHeadingmatch the behaviour they replace, the enabled path the new early return guards included.- Consumer:
WeMeditateWeb'scontent-blocks.ts:127restatesTocHeadingby hand, with noindex— sydevs/WeMeditateWeb#266's work, not this PR's. - Preview:
pr-1208isON_HOST.pages1014001 isPAGE.welcome, andfixture/pages.ts:119,136are its only root headings, soindex0 and 1 hold. BlocksFeaturenests no rich text, so no heading escapes the root scan.
🤖 Written by the sydevs autonomous loop — see what this is
Generated by Claude Code
…uplicate-headings
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
|
Both critic findings adopted. Head is now 468274d.
The question thread on stamping
Body refreshed: 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
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
|
Built and pushed. Head is dd8acbb.
Security review: skipped, no changed path matches 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
…uplicate-headings
`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
|
Built and pushed. Head is a0c6e18.
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 🤖 Written by the sydevs autonomous loop — see what this is Generated by Claude Code |
Summary
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.mergeFieldStyles, so it sat content-width while the built-ins beside it flexed (docs/rules/admin-ui.md).DetectedHeadingrestated whatjsonFieldalready generates, whichsrc/collections/AGENTS.mdsays to delete.storedFromis the one way a stored list leavesheadings.ts, so "a heading goes where its parent goes" is stated once rather than inrebuildStoredalone. 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`occurrenceis 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 thedescribe(): 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.The position is the identity inside the field, where the document is in hand. The
occurrenceis 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
Files — the pure half, so a spec can reach it
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.stampOccurrencesis 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
pages1014001 now carries two H2s,Where to beginandWhere to begin?, which slugify alike. Itswelcome-tocblock lists both, atoccurrence0 and 1. Tick and untick each: the other must not move.Contract impact
src/payload-types.tsgainsoccurrence?: numberonTableOfContentsHeadings. BothcontractSyncconsumers — WeMeditateWeb and SahajAtlasWeb — pick it up through their owntypes:cmsstep, 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, notindex. 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()onoccurrencestates 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 — andgenerate:typescopies that sentence into each consumer's ownpayload-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
origin/maintests/int/pages.int.spec.ts20 passed.tests/int/fixture-load.int.spec.ts7 passed on dd8acbb, and nothing since has touched the fixtureBoth C-specific cases were watched failing first, against a shim stamping the document position and resolving without the occurrence: 2 of 15 fail there —
stampOccurrencescounting 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. Thejson-field-schemascase refusingoccurrence: '0'was watched failing with the schema key removed.toggleHeadingdropping an orphan it never touched was watched failing against the pre-storedFromfile: 1 of 16 fails there, and the other 15 pass, so the simplification moved exactly that one behaviour.Manual verification
Notes for reviewer
slugifyValue('Where to begin?')equalsslugifyValue('Where to begin'). Verified against the realslugifypackage innode_modules, not assumed — both givewhere-to-begin. The ordinals assume the welcome page'scontentholds exactly those two root-levelheading()nodes; verified by readingsrc/fixture/pages.tson this branch.pnpm db:migrations:create --skip-emptycreated nothing, which is the expected answer.shortcut:besideresolveStored: 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.toggleHeadingused 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 throughstoredFromlikerebuildStoreddoes, and the orphan is dropped. Reachable only from a list written before this rule, which the next scan rebuilt anyway.occurrenceafter 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:
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.
HeadingFeatureenablesh2/h3only and the scan reads root children alone, so a page holds 5–40 headings, ~200 at the pathological end.resolveStoredis still O(stored × detected), now with up to threefindIndexpasses 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 theslugifyValuecalls in the same tick.stampOccurrencesadds oneMappass per scan. TheJSON.stringifychange 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
afterReadhook 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