Skip to content

[lexical-markdown] Bug Fix: keep fence-like lines inside a code block as content - #8734

Merged
etrepum merged 3 commits into
meta:mainfrom
GermanJablo:fix/markdown-normalize-nested-codeblocks
Jun 26, 2026
Merged

etrepum merged 3 commits into
meta:mainfrom
GermanJablo:fix/markdown-normalize-nested-codeblocks

Conversation

@GermanJablo

@GermanJablo GermanJablo commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

Description

normalizeMarkdown (used by $convertFromMarkdownString) tracks whether it is inside a fenced code block so it can leave code content untouched while merging adjacent prose lines. The detection toggled inCodeBlock on any fence-like line:

if (CODE_START_REGEX.test(line) || CODE_END_REGEX.test(line)) {
  inCodeBlock = !inCodeBlock;
  ...
}

This means a code block whose content contains a fence-like line is closed too early. For example:

```ts
const a = 1
```js
const b = 2
```

The inner ```js carries an info string, so per CommonMark it is content, not a closing fence. But the toggle flips inCodeBlock off there, and const b = 2 is then treated as prose and merged into the previous line, corrupting the block. The same happens with a shorter inner fence inside a longer one (e.g. a ``` line inside a ```` block).

This PR tracks the opening fence length and only closes a block on a bare closing fence (no info string) that is at least as long as the opening fence, per the CommonMark fenced-code rules (https://spec.commonmark.org/0.31.2/#code-fences). Fence-like lines that carry an info string, or that are shorter than the opening fence, are kept as code content.

This is motivated by downstream usage in Payload's rich text editor, where the current behavior forces a forked copy of normalizeMarkdown (payloadcms/payload#17064).

Test plan

Before

Fence-like lines inside a fenced code block (an info-string fence such as ```js, or a shorter inner fence) were treated as block terminators, so subsequent code lines were merged as prose and the block was corrupted. There was no unit coverage for nested fences.

After

Added unit tests in LexicalMarkdown.test.ts:

  • An info-string fence (```js) inside a code block stays as content.
  • A shorter inner fence does not close a longer fence.
  • A longer closing fence closes a shorter opening fence (CommonMark §4.5).
  • Indented fenced code nested inside block-level tags is preserved.

All 402 lexical-markdown unit tests pass:

pnpm exec vitest --project unit --no-watch LexicalMarkdown

…ontent

`normalizeMarkdown` toggled `inCodeBlock` on any fence-like line, so a code
block whose content contained a line like ```ts (an info-string fence) or a
shorter inner fence was incorrectly closed early. The lines that followed were
then treated as prose and merged, corrupting the code block.

Track the opening fence length and only close a block on a bare closing fence
(no info string) that is at least as long as the opening fence, per CommonMark.
@vercel

vercel Bot commented Jun 22, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
lexical Ready Ready Preview Jun 23, 2026 11:06am
lexical-playground Ready Ready Preview Jun 23, 2026 11:06am

Request Review

@etrepum etrepum left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

let's also follow the pr template so that it's easier to maintain the release notes

@etrepum etrepum added the extended-tests Run extended e2e tests on a PR label Jun 22, 2026

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

Reviewed by Navi (Tater Thoughts Bobblehead) on behalf of @potatowagon.

LGTM ✅

Summary: Bug fix for normalizeMarkdown — fence-like lines inside code blocks were being incorrectly treated as code-block terminators. The fix tracks the opening fence length and only closes on a bare fence of equal or greater length, per CommonMark §4.5.

What I checked:

  • Logic correctness: The openCodeFenceLength state variable correctly tracks whether we are inside a code block and at what fence length. The closing condition (trimmedLine.length >= openCodeFenceLength && /^{3,}$|^~{3,}$/.test(trimmedLine)`) properly implements CommonMark spec §4.5 rules for fenced code block termination.
  • Edge cases: The 3 new tests cover: (1) fence-like lines with different fence characters inside a block, (2) shorter fences inside a block that should NOT close it, and (3) mixed triple-backtick/tilde scenarios. Opening fence character matching (backtick vs tilde) is handled.
  • Backward compatibility: No API surface changes, no removed/renamed exports. This only affects the internal normalizeMarkdown utility behavior. Safe for www consumers.
  • Test coverage: 3 comprehensive new test cases with round-trip verification.
  • CI status: All green (unit 22.x+24.x, browser, integrity, e2e canary chromium, CLA, Vercel).
  • www compat: No concerns — internal utility function change only, no exports modified.

Verdict: Clean, focused bug fix with proper spec compliance. Ready to approve.

@GermanJablo GermanJablo changed the title fix(lexical-markdown): keep fence-like lines inside a code block as content [lexical-markdown] Bug Fix: keep fence-like lines inside a code block as content Jun 23, 2026
…of the spec

Collapse the redundant inCodeBlock flag into codeBlockFenceLength (0 means
not inside a fenced block). Add unit tests for closing a shorter opening
fence with a longer closing fence and for an unclosed block that runs to
the end of the document, per CommonMark.
@GermanJablo
GermanJablo requested a review from etrepum June 26, 2026 07:04
@etrepum
etrepum added this pull request to the merge queue Jun 26, 2026
Merged via the queue into meta:main with commit b6c15be Jun 26, 2026
43 checks passed
GermanJablo added a commit to payloadcms/payload that referenced this pull request Jun 28, 2026
…d upgrade to lexical 0.45 (#17064)

## Summary

Payload vendored a full copy of `@lexical/markdown` because, before
lexical `0.42`, the published package transitively pulled in
`@lexical/code` + `prismjs`, which broke type generation. Lexical `0.42`
switched to `@lexical/code-core` (no prism), so the fork is no longer
needed.

- **Upgrade to lexical `0.45.0`** (all `@lexical/*` from `0.41.0`), add
`@lexical/[email protected]` as a dependency, and delete the vendored
copy.
- **Make `@payloadcms/richtext-lexical/lexical/markdown` a pure
passthrough** (`export * from '@lexical/markdown'`), consistent with
every other `@lexical/*` proxy. Payload's `normalizeMarkdown`
preprocessing moves into an internal `$convertFromMarkdownString`
helper, so the public export behaves the same.
- **Deduplicate transformers that never diverged from upstream**
(text-format, quote, list) so they import directly from
`@lexical/markdown`, and reduce the heading transformer to `{
...HEADING, regExp }` so it tracks upstream.
- **Prefix the intentional divergences with `PAYLOAD_`**
(`PAYLOAD_HEADING`, `PAYLOAD_LINK`, `PAYLOAD_UPLOAD`,
`PAYLOAD_HORIZONTAL_RULE`, `PAYLOAD_TABLE`); they handle
Payload-specific nodes with no upstream equivalent.
- **Add ESLint rule `payload/no-conflicting-lexical-markdown-imports`**
that flags Lexical's `CODE` / `LINK` / `HEADING` transformers, the
default transformer groups, and convert/register calls that omit an
explicit transformer list, since these silently conflict with Payload's
features.

## Related

Supersedes #13708.

## Payload API Breaking Changes

### 1. `$convertFromMarkdownString` no longer merges adjacent lines by
default

If you call it directly, pass `shouldMergeAdjacentLines: true` (5th arg)
to keep the old behavior:

```diff
- $convertFromMarkdownString(markdown, transformers)
+ $convertFromMarkdownString(markdown, transformers, undefined, false, true)
```

### 2. Markdown transformer defaults now match upstream lexical (not
Payload's features)

The vendored fork shipped a curated `TRANSFORMERS` set (no `CODE`, no
`LINK`). Both `@payloadcms/richtext-lexical/lexical/markdown` (now a
pure passthrough) and the default argument to
`$convertFromMarkdownString` exported from
`@payloadcms/richtext-lexical` now use lexical's `TRANSFORMERS`, which
bundles `CODE`, `LINK`, and `HEADING` transformers that conflict with
Payload's features.

You are affected if you either:
- imported a group (`TRANSFORMERS`, `ELEMENT_TRANSFORMERS`, ...) from
`@payloadcms/richtext-lexical/lexical/markdown`, or
- called `$convertFromMarkdownString(markdown)` from
`@payloadcms/richtext-lexical` without passing a transformer list.

Switch to the converters, which build the list from your editor's
enabled features:

```diff
- import { $convertFromMarkdownString, TRANSFORMERS } from '@payloadcms/richtext-lexical/lexical/markdown'
- $convertFromMarkdownString(markdown, TRANSFORMERS)
+ import { convertMarkdownToLexical } from '@payloadcms/richtext-lexical'
+ convertMarkdownToLexical({ editorConfig, markdown })
```

If you keep calling `$convertFromMarkdownString` directly, pass
`editorConfig.features.markdownTransformers` as the second argument.

Enable `payload/no-conflicting-lexical-markdown-imports` (included in
`@payloadcms/eslint-config`) to catch imports and calls that rely on
these mismatching defaults.

## Lexical Breaking Changes

This PR also bumps every `@lexical/*` package from `0.41.0` to `0.45.0`.
The releases below contain breaking changes. We recommend reading them
if you use Lexical APIs directly
(`@payloadcms/richtext-lexical/lexical/*`). None of them require action
for typical Payload usage.

- [v0.45.0](https://github.com/facebook/lexical/releases/tag/v0.45.0)
- `registerRichText` / `registerPlainText` now strip empty inline
elements (`NormalizeInlineElementsExtension`) and the triple-click
selection normalization moved into
`NormalizeTripleClickSelectionExtension`. Editors that bypass
`registerRichText` / `registerPlainText` must register these extensions
to keep the old behavior.
- Backspace at the start of a non-empty block now preserves the current
block's type instead of merging it into the previous block.
- Markdown shortcuts (`*`, `_`, `~`) now fire on IME composition commit
(fixes dropped shortcuts for Japanese / Korean / Chinese input).
- **Whitespace-only markdown table cells now import as an empty
paragraph** instead of a text node of padding spaces. No migration
needed unless you assert on those padding spaces.
- [v0.44.0](https://github.com/facebook/lexical/releases/tag/v0.44.0)
- The "press Enter three times to exit a code block" logic moved from
`CodeNode` into `CodeExtension`; using `CodeNode` without
`CodeExtension` is deprecated (backwards-compatible shim with a dev-mode
warning).
- `@lexical/offset` `OffsetView` is deprecated; import
`$createChildrenArray` from `lexical` instead.
- [v0.43.0](https://github.com/facebook/lexical/releases/tag/v0.43.0)
- `@lexical/react` nested editors use asynchronous parent editor
delegation to restore pre-`0.42.0` behavior.
- [v0.42.0](https://github.com/facebook/lexical/releases/tag/v0.42.0)
- Prism highlighting was extracted from `@lexical/code` into
`@lexical/code-prism`, with a prism-free `@lexical/code-core`. This is
the change that lets Payload drop its vendored `@lexical/markdown` fork.
- Markdown import was aligned with CommonMark (trailing-space flanking
rules, backslash handling, tabs converted to `TabNode`). The
whitespace-only table cell change noted above originates from these
markdown import changes.
- Editor listeners (`registerUpdateListener`, root/editable listeners)
may now return an unregister callback that Lexical calls on teardown.
Returning a non-function value (e.g. an accidental Promise) throws
`unregister is not a function`; Payload's toolbar listener was updated
accordingly.

## Previous Lexical Upgrades

- [#15760](#15760) — 0.35.0 →
0.41.0
- [#13715](#13715) — 0.34.0 →
0.35.0
- [#13622](#13622) — 0.28.0 →
0.34.0
- [#11764](#11764) — 0.27.2 →
0.28.0
- [#11564](#11564) — 0.21.0 →
0.27.1

## Pending / Blocked

- [ ] Delete `normalizeMarkdown` and the internal
`$convertFromMarkdownString` helper once
[meta/lexical#8734](meta/lexical#8734)
(nested code fence fix) merges and we upgrade to a release that includes
it. Both carry a matching `TODO`.

---------

Co-authored-by: German Jablonski <[email protected]>
@etrepum etrepum mentioned this pull request Jul 9, 2026
AlessioGr added a commit to payloadcms/payload that referenced this pull request Jul 29, 2026
Upgrades `lexical` and every `@lexical/*` package from `0.45.0` to
`0.48.0`.

## Changes required

Lexical widened the base `importJSON` parameter to include
`Record<string, unknown>`, which a TypeScript `interface` cannot
satisfy. Four nodes (link, autolink, and both horizontal rules)
intersect their serialized type with it to compensate, which needs no
casts and leaves the serialized types alone.

## Also included

Fifteen `@lexical/react` subpaths are re-exported to reach parity with
lexical exports. Payload's local `getScrollParent` copy is deleted now
that `@lexical/utils` exports it.

## Follow-up

#17064 deferred deleting `normalizeMarkdown` until
[meta/lexical#8734](meta/lexical#8734)
shipped, which it did in `0.47.0`. Left for its own PR.

This branch was successfully deployed

2 active deployments
Preview – lexical — 76a07d64 Deployed Jun 23, 2026 by vercel[bot]
Preview – lexical-playground — 76a07d64 Deployed Jun 23, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. extended-tests Run extended e2e tests on a PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants