Skip to content

[lexical-selection] Bug Fix: Keep the part of a paste that fits when it exceeds the max length - #9423

Open
Vedthakar wants to merge 3 commits into
meta:mainfrom
Vedthakar:fix/3775-max-length-paste
Open

Vedthakar wants to merge 3 commits into
meta:mainfrom
Vedthakar:fix/3775-max-length-paste

Conversation

@Vedthakar

Copy link
Copy Markdown
Contributor

Description

This solves issue #3775: with MaxLengthPlugin, pasting text that goes over the limit into a paragraph that already has text throws the whole paste away instead of keeping the part that fits.

Current behavior. MaxLengthPlugin calls $trimTextContentFromAnchor(editor, anchor, size - maxLength) from a root transform. When the excess fits in the anchor's text node and that node already existed in the previous editor state, the function does not trim. It goes into a "revert it to what was in the last editor state" branch, which reads the node in editor.read('latest'), calls setTextContent(prevTextContent) and moves the selection back to its previous point. The paste is dropped entirely. Pasting into an empty editor works only because the text node is new, so the function falls through to the split path.

Why the branch was there. git blame traces it to the original MaxLengthPlugin (#2254, with tweaks in #2258/#2265, moved to @lexical/selection in #3145). It existed to drop a character typed at the limit. MaxLengthPlugin now handles that case itself by calling $restoreEditorState when the previous size already equals maxLength, so the branch is no longer needed for typing. For a paste, though, it is wrong.

What this changes.

  • $trimTextContentFromAnchor in packages/lexical-selection/src/lexical-node.ts drops the revert branch and always uses the existing split path. That path removes the excess characters just before the anchor, so the text ends exactly at the limit and the caret sits at the trim point.
  • Both cut points (the one just before the anchor, and the one in an earlier node when the excess spills past the anchor's node) are moved back to the start of their grapheme. This uses Intl.Segmenter, the pattern already in useCharacterLimit, and falls back to a surrogate-pair check when Intl.Segmenter is unavailable. The trim therefore never leaves half an emoji, flag or accented letter. That was the other thing the revert branch prevented, and it keeps the "can restrict emojis on boundaries" e2e test passing. When a grapheme is dropped whole, the text can end a little under the limit.
  • The editor parameter is now unused but kept, since it is public API. The JSDoc is rewritten to match: the function always trims, it may remove a few extra characters to keep a grapheme whole, and rejecting a keystroke at the limit is left to the caller (MaxLengthPlugin restores the previous editor state).

Closes #3775

Test plan

New tests:

  • packages/lexical-selection/src/__tests__/unit/$trimTextContentFromAnchor.test.ts: pastes at the caret and trims the way MaxLengthPlugin does. Each case checks the text, the size and the caret.
    • Paste into an empty editor (the control case).
    • Paste after existing text.
    • Paste in the middle of existing text.
    • Paste into the last of several paragraphs.
    • Graphemes crossing the limit: an emoji surrogate pair, a ZWJ emoji, a flag (🇨🇦) and a combining mark (e\u0301).
    • An emoji in an earlier node when the cut lands there.
    • The surrogate-pair fallback with Intl.Segmenter stubbed out.
  • packages/lexical-playground/__tests__/e2e/MaxLength.spec.mjs › "keeps the start of an over-limit paste after existing text": the repro from the issue, which types lorem ipsum and then pastes the rest.

Before

On main with the tests applied and the source change reverted:

$ pnpm exec vitest --project unit --no-watch 'packages/lexical-selection/src/__tests__/unit/$trimTextContentFromAnchor.test.ts'
  × keeps the start of a paste after existing text
  × trims a paste in the middle of the text just before the caret
  × trims a paste into the last of several paragraphs
  × drops an emoji whole instead of splitting its surrogate pair
  × drops a multi code point grapheme whole
  × drops a flag emoji whole
  × drops a letter with a combining mark whole
  × drops an emoji whole when the cut lands in an earlier node
  × keeps surrogate pairs whole without Intl.Segmenter
  Tests  9 failed | 1 passed (10)

$ E2E_BROWSER=chromium playwright test packages/lexical-playground/__tests__/e2e/MaxLength.spec.mjs
  ✘ MaxLength › keeps the start of an over-limit paste after existing text
    -   <span data-lexical-text="true">lorem ipsum dolor sit amet, co</span>
    +   <span data-lexical-text="true">lorem ipsum</span>
  1 failed, 5 passed

After

On current main:

  • $trimTextContentFromAnchor.test.ts: 10 passed (9 fail on main). Chromium e2e: MaxLength.spec.mjs passes in full, including the new over-limit paste test (fails on main) and the existing emoji-boundary test.
  • pnpm run test-unit: all 9,580 tests pass
  • tsc, pnpm run flow (0 errors), and eslint/prettier on the changed files: clean

Author: Ved Thakar (@Vedthakar)

🤖 Generated with Claude Code

@vercel

vercel Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

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

Project Deployment Actions Updated
lexical Ready Ready Preview Nov 16, 2026 11:39pm UTC
lexical-playground Ready Ready Preview Nov 16, 2026 11:39pm UTC

Request Review

@pkg-pr-new

pkg-pr-new Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
lexical

npm i https://pkg.pr.new/lexical@9423

@lexical/a11y

npm i https://pkg.pr.new/@lexical/a11y@9423

@lexical/clipboard

npm i https://pkg.pr.new/@lexical/clipboard@9423

@lexical/code

npm i https://pkg.pr.new/@lexical/code@9423

@lexical/code-core

npm i https://pkg.pr.new/@lexical/code-core@9423

@lexical/code-prism

npm i https://pkg.pr.new/@lexical/code-prism@9423

@lexical/code-shiki

npm i https://pkg.pr.new/@lexical/code-shiki@9423

@lexical/compiler

npm i https://pkg.pr.new/@lexical/compiler@9423

@lexical/devtools-core

npm i https://pkg.pr.new/@lexical/devtools-core@9423

@lexical/dragon

npm i https://pkg.pr.new/@lexical/dragon@9423

@lexical/eslint-plugin

npm i https://pkg.pr.new/@lexical/eslint-plugin@9423

@lexical/extension

npm i https://pkg.pr.new/@lexical/extension@9423

@lexical/fast-check

npm i https://pkg.pr.new/@lexical/fast-check@9423

@lexical/file

npm i https://pkg.pr.new/@lexical/file@9423

@lexical/hashtag

npm i https://pkg.pr.new/@lexical/hashtag@9423

@lexical/headless

npm i https://pkg.pr.new/@lexical/headless@9423

@lexical/history

npm i https://pkg.pr.new/@lexical/history@9423

@lexical/html

npm i https://pkg.pr.new/@lexical/html@9423

@lexical/internal

npm i https://pkg.pr.new/@lexical/internal@9423

@lexical/link

npm i https://pkg.pr.new/@lexical/link@9423

@lexical/list

npm i https://pkg.pr.new/@lexical/list@9423

@lexical/mark

npm i https://pkg.pr.new/@lexical/mark@9423

@lexical/markdown

npm i https://pkg.pr.new/@lexical/markdown@9423

@lexical/mdast

npm i https://pkg.pr.new/@lexical/mdast@9423

@lexical/offset

npm i https://pkg.pr.new/@lexical/offset@9423

@lexical/overflow

npm i https://pkg.pr.new/@lexical/overflow@9423

@lexical/plain-text

npm i https://pkg.pr.new/@lexical/plain-text@9423

@lexical/react

npm i https://pkg.pr.new/@lexical/react@9423

@lexical/rich-text

npm i https://pkg.pr.new/@lexical/rich-text@9423

@lexical/selection

npm i https://pkg.pr.new/@lexical/selection@9423

@lexical/table

npm i https://pkg.pr.new/@lexical/table@9423

@lexical/tailwind

npm i https://pkg.pr.new/@lexical/tailwind@9423

@lexical/text

npm i https://pkg.pr.new/@lexical/text@9423

@lexical/utils

npm i https://pkg.pr.new/@lexical/utils@9423

@lexical/y

npm i https://pkg.pr.new/@lexical/y@9423

@lexical/yjs

npm i https://pkg.pr.new/@lexical/yjs@9423

commit: c69c2f7

@rootnode-bot rootnode-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Thanks for picking up #3775. The root-cause analysis is right, and keeping the part of a paste that fits, with grapheme-safe cuts, is what the issue asks for. The new unit tests fail on main (9 of 10) and pass on this branch, and the issue's steps now keep lorem ipsum dolor sit amet, co in the playground. One problem needs fixing before this can merge.

Blocking: a cut inside the first grapheme of an earlier text node throws

packages/lexical-selection/src/lexical-node.ts:187 rounds offset down to a grapheme start. When the node being cut is not the anchor's node and the cut falls inside its first grapheme, offset becomes 0, so line 207 calls currentNode.splitText(0, 0). splitText returns [self] when there is only one part, so excessNode is undefined and line 208 throws TypeError: Cannot read properties of undefined (reading 'remove').

This is the ordinary path after a multi-paragraph paste: once the caret's paragraph has been removed, the anchor sits on an element point of the previous paragraph, so anchor.key never matches the text node being cut. To reproduce in the playground with ?isMaxLength=true, paste this plain text into an empty editor:

lorem ipsum dolor sit amet,
😀 next
ab

On main the result is 30 characters ending in half of the emoji. On this branch the transform throws and nothing is pasted, and because the playground's onError rethrows, later typing in that editor fails too.

A minimal fix is to send that case through the whole-node branch at line 173, which also removes the emptied parent:

if (
  !$isTextNode(currentNode) ||
  remaining >= currentNodeSize ||
  (anchor.key !== currentNode.getKey() &&
    getGraphemeStart(text, currentNodeSize - remaining) === 0)
) {

With that change the paste above keeps lorem ipsum dolor sit amet, and your ten tests still pass. A regression test with your existing helper: pasteWithMaxLength(editor, ['ab', '💏c', 'x'], [2, 1], 'yz', 5) should give text: 'ab'; today it throws.

Optional, non-blocking

  • The new JSDoc (lexical-node.ts:105-110) says a grapheme is never cut in half. Without Intl.Segmenter the fallback only keeps surrogate pairs whole, so "where Intl.Segmenter is available" would be more accurate.
  • In the fallback test, vi.stubGlobal('Intl', {...Intl, Segmenter: undefined}) replaces Intl with an object whose only key is Segmenter, because Intl's members are non-enumerable and the spread copies none of them. Object.assign(Object.create(Intl), {Segmenter: undefined}) keeps the rest.
  • When an IME composition crosses the limit, the behaviour changes from "revert the node" to "trim before the caret". AGENTS.md asks the Test plan to say explicitly when part of the matrix could not be exercised, so a short note (or a manual check with a CJK IME near the limit) would help reviewers.

Vedthakar and others added 2 commits November 16, 2026 18:29
…it exceeds the max length

$trimTextContentFromAnchor reverted the anchor's text node to its previous
content when the node already existed, discarding the whole paste instead of
trimming it. Trim the excess just before the anchor instead, and never split
a grapheme in half.

Closes meta#3775

Signed-off-by: Ved Thakar <111605341+Vedthakar@users.noreply.github.com>
Co-authored-by: Ved Thakar <111605341+Vedthakar@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…eme of an earlier node

A cut inside the first grapheme of a text node before the anchor's node
rounded the split offset down to 0, so splitText returned only the node
itself and the excess node was undefined. Remove such a node whole.

Also stub only Intl.Segmenter in the fallback test, and say in the JSDoc
that whole graphemes need Intl.Segmenter.

Co-authored-by: Ved Thakar <111605341+Vedthakar@users.noreply.github.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Co-authored-by: Ved Thakar <111605341+Vedthakar@users.noreply.github.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@Vedthakar

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Fixed in the latest push:

  • Throw when the cut lands in the first grapheme of an earlier node: that node is now removed whole, with your condition. Added the regression test you suggested (['ab', '💏c', 'x'], max 5 gives ab); it throws without the fix.
  • The Intl.Segmenter fallback test now stubs only Segmenter (Object.create(Intl)).
  • The JSDoc says whole graphemes need Intl.Segmenter.

Also rebased onto main and added a changeset.

— Ved Thakar

@rootnode-bot rootnode-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Thanks @Vedthakar, this looks good. Pasting past the limit after existing text now keeps the part that fits, as #3775 asks; emoji, flags and combining marks stay whole at the cut; and a cut that lands in the first grapheme of an earlier node now removes that node whole instead of leaving half an emoji behind. The new unit tests fail on main and pass here, and the e2e case reproduces the issue as reported.

A few optional, non-blocking suggestions:

  1. Add a Verify: paragraph to the changeset (.changeset/max-length-paste-keeps-fit.md). CONTRIBUTING.md ("Changesets") and AGENTS.md ask a fix that changes observable behavior to carry one, so it is listed under "Behavior changes". For example:

    Verify: with a max-length transform that calls `$trimTextContentFromAnchor`, paste text that crosses the limit after existing text: the start of the paste is kept up to the limit and the caret ends after it. An emoji or other grapheme that crosses the limit is dropped whole, so the text can end a few characters short of the limit. Text that is already over the limit is cut to it by the next edit instead of the edit being ignored.
  2. Text that is already over the limit (packages/lexical-selection/src/lexical-node.ts:199-201). With the revert branch gone, the next edit in content that is already longer than the limit (loaded with setEditorState, or after a caller lowers its limit) cuts existing text down to the limit. With Hello world and a limit of 5 in the playground's MaxLengthExtension, typing at the end or pressing Backspace leaves Hello, and typing at the start leaves xHell, because this fallback moves the cut to the end of the node and deletes the text after the caret. On main such edits were ignored inside an existing node (though an edit that created a new node was already trimmed), and Undo brings the text back, so this is not a blocker. It would help to either name it in the Verify: paragraph or have the example extension reject growth when the previous size is already at or over the limit (textContentSize > prevTextContentSize && prevTextContentSize >= maxLength).

  3. Pin the other two behaviors this changes. A unit case for text already over the limit, and one for a multi-character input that crosses the limit (Hell + ab with a limit of 5 now gives Hella; it used to be dropped), would lock in whichever behavior you settle on.

  4. Test plan output. AGENTS.md ("Commits and Pull Requests") asks for the real After output to be pasted, the way the Before section is.

Automated review (maintainer link)

'@lexical/selection': patch
---

[fix] `$trimTextContentFromAnchor` keeps the part of a paste that fits under the limit and no longer cuts an emoji or other grapheme in half

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Optional: CONTRIBUTING.md ("Changesets") and AGENTS.md ask a fix that changes observable behavior to carry a Verify: paragraph, so it is listed under "Behavior changes". For example:

Suggested change
[fix] `$trimTextContentFromAnchor` keeps the part of a paste that fits under the limit and no longer cuts an emoji or other grapheme in half
[fix] `$trimTextContentFromAnchor` keeps the part of a paste that fits under the limit and no longer cuts an emoji or other grapheme in half
Verify: with a max-length transform that calls `$trimTextContentFromAnchor`, paste text that crosses the limit after existing text: the start of the paste is kept up to the limit and the caret ends after it. An emoji or other grapheme that crosses the limit is dropped whole, so the text can end a few characters short of the limit. Text that is already over the limit is cut to it by the next edit instead of the edit being ignored.

Comment on lines 199 to 201
if (anchorOffset < remaining) {
anchorOffset = currentNodeSize;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Optional, non-blocking: with the revert branch gone, this fallback is now reached for an existing node too. In text that is already over the limit (loaded with setEditorState, or after a caller lowers its limit), typing near the start moves the cut to the end of the node and deletes the text after the caret while keeping the keystroke: Hello world with a limit of 5 and x typed at offset 0 gives xHell through the playground's MaxLengthExtension (main ignored that keystroke). Undo restores it, so this isn't a blocker, but it may be worth naming in the changeset's Verify: paragraph, or having the example extension reject growth when the previous size is already at or over the limit.

This branch was successfully deployed

2 active deployments
Preview – lexical — c69c2f72 Deployed Nov 16, 2026 by vercel[bot]
Preview – lexical-playground — c69c2f72 Deployed Nov 16, 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.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: Inconsistent behavior of trimTextContentFromAnchor on paste

1 participant